Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/peering-owner-attestation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
"nostream": minor
---

feat(peering): add owner-attested peering requests

Peers can present a one-time, owner-signed request over their authenticated
NIP-42 connection. The receiving relay verifies the owner signature, the AUTH
relay key, the requested scopes, the current terms snapshot and NIP-13
proof-of-work, stores the accepted attestation, and returns a relay-signed
acceptance. Operators choose `required`, `preferred` or `waived`; configured
peers keep working without proof-of-work by default. `nostream peering request`
produces and sends the request using an owner key supplied outside settings.
Operational traffic never requires the owner's key.
48 changes: 45 additions & 3 deletions docs/PEERING.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,51 @@ Only the public half of the keypair is ever visible on the wire. Inbound AUTH is
verified by `AuthMessageHandler`: event id, signature, timestamp, challenge, and
relay host. Outbound AUTH proves this relay's identity to the peer; it does not
authenticate the remote relay, because NIP-42 is a client-to-relay proof. The
remote relay's identity is established separately by the configured
`peering.peers` pubkey (and, in later phases, by discovery and owner
attestation).
remote relay's identity is established by the configured `peering.peers`
pubkey. When `peering.ownerAttestation` is `required`, an accepted owner-signed
request must also exist before peer treatment is granted. Discovery remains a
later phase.

## Owner attestation

A relay keypair is free to mint, so peering can optionally be backed by the
operator's own key. The relay owner signs a one-time request; the relay key
proves itself on the same NIP-42 connection. The request names the relay's
pubkey and URL, the scopes it accepts, and a hash of the advertised terms. The
receiver checks:

- the owner signature and event id;
- that the request's relay pubkey is authenticated on this connection;
- that the request targets this relay and is fresh;
- that the scopes and terms still match this relay's NIP-11 advertisement;
- that NIP-13 proof-of-work meets `peering.minRequestPowDifficulty`.

`peering.ownerAttestation` controls the policy:

- `waived` — configured peers are trusted without a request (default).
- `preferred` — a presented request is recorded, but peers are not blocked.
- `required` — a configured peer gets no peer treatment until an accepted
request exists for its key.

Requests are only accepted from relays already listed in `peering.peers`;
discovery is a later phase. Add the requesting relay's pubkey on the receiver
first. Configured peers skip the proof-of-work requirement by default
(`peering.waiveRequestPowForConfiguredPeers`). Set `peering.peers[].ownerPubkey`
to require a specific operator key rather than accepting any owner signature
for that relay.

Produce and send a request from the requesting relay:

```bash
PEERING_OWNER_PRIVATE_KEY=<owner hex> \
nostream peering request wss://peer.example.com --json
```

The command reads the peer's NIP-11 document, requests its advertised scopes
and terms, grinds the advertised proof-of-work, authenticates with this relay's
key, and prints the accepted request and relay-signed acceptance. The owner key
is used only for this establishment request; invoices, renewals and on-demand
event requests never ask for it.

## Paid peering

Expand Down
19 changes: 19 additions & 0 deletions migrations/20261125_120000_create_peering_attestations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
exports.up = async function (knex) {
await knex.schema.createTable('peering_attestations', (table) => {
table.binary('relay_pubkey').primary()
table.binary('owner_pubkey').notNullable()
table.text('relay_url').notNullable()
table.text('request_event_id').notNullable()
table.jsonb('scopes').notNullable()
table.jsonb('terms').notNullable()
table.text('terms_hash').notNullable()
table.integer('pow_difficulty').notNullable()
table.timestamp('accepted_at', { useTz: true }).nullable()
table.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now())
table.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(knex.fn.now())
})
}

exports.down = async function (knex) {
await knex.schema.dropTable('peering_attestations')
}
11 changes: 11 additions & 0 deletions resources/default-settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ peering:
# NIP-13 proof-of-work bits a peering request must carry. 0 means none.
# Advertised as peering.min_pow_difficulty.
minRequestPowDifficulty: 0
# Owner attestation for incoming peering requests:
# waived - configured peers are trusted without a request (default)
# preferred - record a valid request when presented, but do not require it
# required - withhold peer treatment until a valid owner-signed request is
# accepted on an authenticated connection
ownerAttestation: waived
# Configured peers are already trusted by pubkey, so their request does not
# need to meet minRequestPowDifficulty. Set false to require it anyway.
waiveRequestPowForConfiguredPeers: true
# Feeds this relay is willing to serve. Each scope lists event kinds and,
# optionally, an absolute time range (unix seconds) or a rolling window.
# At least one scope is required when peering is enabled.
Expand Down Expand Up @@ -213,6 +222,8 @@ peering:
# - pubkey: replace-with-peer-relay-pubkey-in-hex
# relayUrl: wss://peer.example.com
# enabled: true
# # Optional: require this operator key on the owner attestation.
# ownerPubkey: replace-with-peer-owner-pubkey-in-hex
# # Buying side: auto-pay this peer's invoices up to this budget.
# budget: { amount: 10000, unit: sats, period: 2592000 }
peers: []
Expand Down
9 changes: 8 additions & 1 deletion src/@types/adapters.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EventEmitter } from 'node:stream'
import { Event } from './event'
import { INegentropySessions } from './negentropy'
import { PeeringAttestationAgreement } from './peering'
import { SubscriptionFilter } from './subscription'

export interface IWebSocketServerAdapter extends EventEmitter, IWebServerAdapter {
Expand Down Expand Up @@ -28,7 +29,13 @@ export type IWebSocketAdapter = EventEmitter & {
*/
getPeerPubkey(): string | undefined
/** Mark `pubkey` as the peer identity for this socket. Ignored if it is not authenticated. */
setPeerPubkey(pubkey: string): void
setPeerPubkey(pubkey: string, agreement?: PeeringAttestationAgreement): void
/**
* Withdraw peer treatment for the rest of this socket's AUTH session. When
* `pubkey` is given, only that identity is cleared, leaving a different
* authenticated peer on the same socket intact.
*/
clearPeerPubkey(pubkey?: string): void
/**
* Resolves once the previous send has flushed to the underlying socket, or
* immediately when there is nothing pending. Used to pause a full-feed read
Expand Down
56 changes: 55 additions & 1 deletion src/@types/peering.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Pubkey } from './base'
import { PeeringScope, PeeringTerm } from './settings'
import { PeeringOwnerAttestationPolicy, PeeringScope, PeeringTerm } from './settings'

/** One scope advertised by a peer in its NIP-11 `peering` section. */
export type AdvertisedPeeringScope = PeeringScope
Expand All @@ -10,9 +10,63 @@ export interface PeeringAdvertisement {
terms: PeeringTerm[]
/** The relay key the peer advertises as `self`, when it publishes one. */
self?: string
/** How the peer treats owner attestation on incoming requests. */
ownerAttestation?: PeeringOwnerAttestationPolicy
/** NIP-13 bits the peer requires on a peering request. */
minPowDifficulty?: number
supportedNips: number[]
}

/** An owner-signed peering request, carried in an ephemeral kind 28937 event. */
export interface PeeringRequestPayload {
relay_pubkey: string
relay_url: string
scopes: PeeringScope[]
terms: PeeringTerm[]
terms_hash: string
}

/** A relay-signed acceptance of one specific peering request. */
export interface PeeringAcceptancePayload {
request_id: string
relay_pubkey: string
relay_url: string
terms_hash: string
accepted_at: number
}

/** The agreement a required-policy socket must still match. */
export type PeeringAttestationAgreement = Pick<PeeringAttestation, 'termsHash' | 'scopes' | 'ownerPubkey'>

/** The latest accepted owner attestation for one relay key. */
export interface PeeringAttestation {
relayPubkey: Pubkey
ownerPubkey: Pubkey
relayUrl: string
requestEventId: string
scopes: PeeringScope[]
terms: PeeringTerm[]
termsHash: string
powDifficulty: number
acceptedAt?: Date | null
createdAt: Date
updatedAt: Date
}

export interface DBPeeringAttestation {
relay_pubkey: Buffer
owner_pubkey: Buffer
relay_url: string
request_event_id: string
scopes: unknown
terms: unknown
terms_hash: string
pow_difficulty: number
accepted_at: Date | null
created_at: Date
updated_at: Date
}

export type PeeringSyncStatus = 'idle' | 'connecting' | 'reconciling' | 'live' | 'error' | 'stopped'

export enum PeeringPaymentDirection {
Expand Down
14 changes: 9 additions & 5 deletions src/@types/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
NotificationDeliveryStatus,
OperatorNotificationChannelType,
} from './operator-notifications'
import { PeeringBudgetUsage, PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering'
import { PeeringAttestation, PeeringBudgetUsage, PeeringInvoice, PeeringInvoiceStatus, PeeringPayment } from './peering'
import { Report } from './report'
import { EventKindsRange } from './settings'
import { SubscriptionFilter } from './subscription'
Expand Down Expand Up @@ -100,12 +100,16 @@ export interface IPeeringPaymentRepository {
findPeriodEnded(now: Date, limit: number, offset: number): Promise<PeeringPayment[]>
}

export interface IPeeringAttestationRepository {
/** Latest accepted owner attestation for this relay key. */
findByRelayPubkey(pubkey: Pubkey, client?: DatabaseClient): Promise<PeeringAttestation | undefined>
/** Replaces the relay's previous attestation with the accepted request. */
save(attestation: PeeringAttestation, client?: DatabaseClient): Promise<PeeringAttestation>
}

export interface IPeeringInvoiceRepository {
/** Inserts once per payment hash; returns the stored row and whether it was new. */
insertIfNew(
invoice: PeeringInvoice,
client?: DatabaseClient,
): Promise<{ inserted: boolean; invoice: PeeringInvoice }>
insertIfNew(invoice: PeeringInvoice, client?: DatabaseClient): Promise<{ inserted: boolean; invoice: PeeringInvoice }>
findByHash(paymentHash: string, client?: DatabaseClient): Promise<PeeringInvoice | undefined>
update(
paymentHash: string,
Expand Down
20 changes: 20 additions & 0 deletions src/@types/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,12 @@ export interface PeeringPeer {
relayUrl: string
/** Whether this configured peer is active. Defaults to true. */
enabled?: boolean
/**
* The operator key expected to sign this peer's owner attestation. When set,
* a request signed by any other key is rejected, and a stored attestation for
* a different owner no longer grants peer treatment.
*/
ownerPubkey?: Pubkey
/**
* Buying side only: how much this relay may auto-pay to this peer per budget
* period. Absent means invoices from this peer are held for an operator.
Expand All @@ -599,6 +605,8 @@ export interface PeeringAutoPaySettings {
globalBudget?: PeeringTerm
}

export type PeeringOwnerAttestationPolicy = 'required' | 'preferred' | 'waived'

export interface PeeringSettings {
/**
* Whether this relay offers peering feeds. Advertised as `peering.enabled`
Expand All @@ -620,6 +628,18 @@ export interface PeeringSettings {
* none. Advertised as `peering.min_pow_difficulty`.
*/
minRequestPowDifficulty?: number
/**
* Whether a peer must present a valid owner-signed request before it is
* recognized. `required` withholds peer treatment until a valid request is
* recorded; `preferred` records one when presented; `waived` ignores
* attestation. Defaults to `waived` so configured peers keep working.
*/
ownerAttestation?: PeeringOwnerAttestationPolicy
/**
* Skip the request proof-of-work requirement for peers already configured by
* pubkey. Defaults to true: configured trust is the v1 path.
*/
waiveRequestPowForConfiguredPeers?: boolean
/**
* Feeds this relay offers. At least one scope is required when enabled.
*/
Expand Down
49 changes: 41 additions & 8 deletions src/adapters/web-socket-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { EventEmitter } from 'stream'
import { WebSocket } from 'ws'
import { ZodError } from 'zod'
import { IWebSocketAdapter, IWebSocketServerAdapter } from '../@types/adapters'
import type { PeeringAttestationAgreement } from '../@types/peering'
import { ContextMetadata, Factory } from '../@types/base'
import { Event } from '../@types/event'
import { IAbortable, IMessageHandler } from '../@types/message-handlers'
Expand Down Expand Up @@ -32,7 +33,8 @@ import { NegentropySessions } from '../utils/negentropy-sessions'
import { createReadAuthorizationGuard } from '../utils/nip42'
import { Nip42SessionManager } from '../utils/nip42-session'
import { messageLimitsFor } from '../utils/peer-limits'
import { isConfiguredPeeringPeer } from '../utils/peering-auth'
import { findConfiguredPeeringPeer, isConfiguredPeeringPeer, parsePeeringPeerPubkey } from '../utils/peering-auth'
import { peeringTermsHash, samePeeringScopes } from '../utils/peering-attestation'
import { PeeringRequestStatsStore } from '../utils/peering-request-stats'
import { attemptValidation } from '../utils/validation'

Expand Down Expand Up @@ -81,6 +83,8 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
private readonly session: Nip42SessionManager
/** Configured peering peer proven by AUTH on this socket, if any. */
private peerPubkey: string | undefined
/** Agreement the peer proved at AUTH; rechecked against live settings on read. */
private peerAgreement: PeeringAttestationAgreement | undefined
// NIP-77
private readonly negentropySessions: NegentropySessions

Expand Down Expand Up @@ -227,9 +231,7 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
this.sendMessage(
createClosedMessage(
subscriptionId,
checkFailed
? 'error: unable to check peering access'
: 'payment-required: peering access expired',
checkFailed ? 'error: unable to check peering access' : 'payment-required: peering access expired',
),
)
}
Expand Down Expand Up @@ -379,20 +381,51 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
// Peer status lives and dies with its AUTH session, and with the operator's
// current trust list: disabling or removing the peer revokes it on the next
// read even if the socket stays authenticated.
const settings = this.settings()
if (
!this.session.getAuthenticatedPubkeys().has(this.peerPubkey) ||
!isConfiguredPeeringPeer(this.settings(), this.peerPubkey)
!isConfiguredPeeringPeer(settings, this.peerPubkey)
) {
this.peerPubkey = undefined
this.clearPeerPubkey()
return undefined
}

if ((settings.peering?.ownerAttestation ?? 'waived') === 'required') {
const configuredOwnerRaw = findConfiguredPeeringPeer(settings, this.peerPubkey)?.ownerPubkey
const configuredOwner = configuredOwnerRaw ? parsePeeringPeerPubkey(configuredOwnerRaw) : undefined
const agreement = this.peerAgreement
const currentTerms = settings.peering?.terms ?? []
const currentScopes = settings.peering?.scopes ?? []
const ownerMismatch =
configuredOwnerRaw !== undefined &&
(configuredOwner === undefined || agreement?.ownerPubkey.toLowerCase() !== configuredOwner)
if (
!agreement ||
agreement.termsHash?.toLowerCase() !== peeringTermsHash(currentTerms) ||
!samePeeringScopes(agreement.scopes, currentScopes) ||
ownerMismatch
) {
this.clearPeerPubkey()
return undefined
}
}

return this.peerPubkey
}

public setPeerPubkey(pubkey: string): void {
public setPeerPubkey(pubkey: string, agreement?: PeeringAttestationAgreement): void {
const authenticated = this.session.getAuthenticatedPubkeys().has(pubkey)
this.peerPubkey = authenticated && isConfiguredPeeringPeer(this.settings(), pubkey) ? pubkey : undefined
const allowed = authenticated && isConfiguredPeeringPeer(this.settings(), pubkey)
this.peerPubkey = allowed ? pubkey : undefined
this.peerAgreement = allowed ? agreement : undefined
}

public clearPeerPubkey(pubkey?: string): void {
if (pubkey && this.peerPubkey !== pubkey) {
return
}
this.peerPubkey = undefined
this.peerAgreement = undefined
}

private async onClientMessage(raw: Buffer) {
Expand Down
Loading
Loading