From 7bbf889cb3cfea5a6cc46242afad9a4ba938acc5 Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Mon, 23 Nov 2026 15:17:27 +0530 Subject: [PATCH 1/3] feat(peering): add owner-attested peering requests - define the owner-signed kind 28937 request and relay-signed 28938 acceptance\n- verify the owner signature, AUTH relay key, scope and term snapshots, and NIP-13 proof-of-work\n- store accepted attestations and gate required-policy AUTHs on them\n- add nostream peering request to produce and send the request\n- document the policy, configuration and operator flow --- .changeset/peering-owner-attestation.md | 14 + docs/PEERING.md | 48 ++- ...1125_120000_create_peering_attestations.js | 19 + resources/default-settings.yaml | 11 + src/@types/peering.ts | 53 ++- src/@types/repositories.ts | 14 +- src/@types/settings.ts | 20 + src/cli/commands/peering.ts | 222 +++++++++++ src/cli/index.ts | 50 ++- src/constants/base.ts | 3 + src/factories/event-strategy-factory.ts | 9 + src/factories/message-handler-factory.ts | 13 +- src/handlers/auth-message-handler.ts | 66 +++- src/handlers/event-message-handler.ts | 34 +- .../peering-acceptance-event-strategy.ts | 20 + .../peering-request-event-strategy.ts | 134 +++++++ .../request-handlers/root-request-handler.ts | 5 +- .../peering-attestation-repository.ts | 69 ++++ src/utils/peering-advertisement.ts | 6 + src/utils/peering-attestation.ts | 368 ++++++++++++++++++ src/utils/settings-config.ts | 56 +-- .../peering/peering-owner-attestation.feature | 7 + .../peering-owner-attestation.feature.ts | 136 +++++++ test/unit/cli/peering.spec.ts | 149 +++++++ .../factories/event-strategy-factory.spec.ts | 12 + .../handlers/auth-message-handler.spec.ts | 157 ++++++-- .../peering-request-event-strategy.spec.ts | 180 +++++++++ .../peering-attestation-repository.spec.ts | 65 ++++ test/unit/utils/peering-advertisement.spec.ts | 15 + test/unit/utils/peering-attestation.spec.ts | 189 +++++++++ test/unit/utils/settings-config.spec.ts | 27 ++ 31 files changed, 2089 insertions(+), 82 deletions(-) create mode 100644 .changeset/peering-owner-attestation.md create mode 100644 migrations/20261125_120000_create_peering_attestations.js create mode 100644 src/cli/commands/peering.ts create mode 100644 src/handlers/event-strategies/peering-acceptance-event-strategy.ts create mode 100644 src/handlers/event-strategies/peering-request-event-strategy.ts create mode 100644 src/repositories/peering-attestation-repository.ts create mode 100644 src/utils/peering-attestation.ts create mode 100644 test/integration/features/peering/peering-owner-attestation.feature create mode 100644 test/integration/features/peering/peering-owner-attestation.feature.ts create mode 100644 test/unit/cli/peering.spec.ts create mode 100644 test/unit/handlers/peering-request-event-strategy.spec.ts create mode 100644 test/unit/repositories/peering-attestation-repository.spec.ts create mode 100644 test/unit/utils/peering-attestation.spec.ts diff --git a/.changeset/peering-owner-attestation.md b/.changeset/peering-owner-attestation.md new file mode 100644 index 000000000..371219300 --- /dev/null +++ b/.changeset/peering-owner-attestation.md @@ -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. diff --git a/docs/PEERING.md b/docs/PEERING.md index cf17f5772..9d1715c08 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -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= \ + 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 diff --git a/migrations/20261125_120000_create_peering_attestations.js b/migrations/20261125_120000_create_peering_attestations.js new file mode 100644 index 000000000..47753f35e --- /dev/null +++ b/migrations/20261125_120000_create_peering_attestations.js @@ -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') +} diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 81c4024ad..67f6356bb 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -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. @@ -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: [] diff --git a/src/@types/peering.ts b/src/@types/peering.ts index 0ee557f32..bc5d98fcd 100644 --- a/src/@types/peering.ts +++ b/src/@types/peering.ts @@ -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 @@ -10,9 +10,60 @@ 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 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 { diff --git a/src/@types/repositories.ts b/src/@types/repositories.ts index 24cb90ff3..138df2d00 100644 --- a/src/@types/repositories.ts +++ b/src/@types/repositories.ts @@ -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' @@ -100,12 +100,16 @@ export interface IPeeringPaymentRepository { findPeriodEnded(now: Date, limit: number, offset: number): Promise } +export interface IPeeringAttestationRepository { + /** Latest accepted owner attestation for this relay key. */ + findByRelayPubkey(pubkey: Pubkey, client?: DatabaseClient): Promise + /** Replaces the relay's previous attestation with the accepted request. */ + save(attestation: PeeringAttestation, client?: DatabaseClient): Promise +} + 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 update( paymentHash: string, diff --git a/src/@types/settings.ts b/src/@types/settings.ts index 682ebe237..690205df8 100644 --- a/src/@types/settings.ts +++ b/src/@types/settings.ts @@ -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. @@ -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` @@ -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. */ diff --git a/src/cli/commands/peering.ts b/src/cli/commands/peering.ts new file mode 100644 index 000000000..ffe4897cc --- /dev/null +++ b/src/cli/commands/peering.ts @@ -0,0 +1,222 @@ +import WebSocket, { RawData } from 'ws' + +import type { Event } from '../../@types/event' +import type { PeeringAcceptancePayload, PeeringAdvertisement } from '../../@types/peering' +import type { Settings } from '../../@types/settings' +import { getPublicKey, getRelayPrivateKey } from '../../utils/event' +import { buildPeeringRequestEvent, verifyPeeringAcceptanceEvent } from '../../utils/peering-attestation' +import { fetchPeeringAdvertisement } from '../../utils/peering-advertisement' +import { authenticateToPeeringRelay } from '../../utils/peering-auth' +import { loadMergedSettings } from '../utils/config' +import { logError, logInfo } from '../utils/output' + +export interface PeeringRequestReply { + ok: boolean + message: string + acceptance?: { event: Event; acceptance: PeeringAcceptancePayload } +} + +/** + * Sends the owner-signed request over an already authenticated peer socket and + * waits for the relay's OK and optional acceptance event. + */ +export const sendPeeringRequest = ( + socket: WebSocket, + request: Event, + timeoutMs = 15_000, +): Promise => + new Promise((resolve) => { + let settled = false + let acceptance: Event | undefined + let finishTimer: NodeJS.Timeout | undefined + + const finish = (reply: PeeringRequestReply): void => { + if (settled) { + return + } + settled = true + if (finishTimer) { + clearTimeout(finishTimer) + } + clearTimeout(timer) + socket.off('message', onMessage) + socket.off('close', onClose) + resolve(reply) + } + + const accept = (): PeeringRequestReply => ({ + ok: true, + message: acceptance ? 'accepted with a signed acceptance' : 'accepted', + ...(acceptance + ? { acceptance: { event: acceptance, acceptance: acceptancePayload(acceptance) as PeeringAcceptancePayload } } + : {}), + }) + + const onMessage = (data: RawData): void => { + let message: unknown + try { + message = JSON.parse(data.toString()) + } catch { + return + } + if (!Array.isArray(message)) { + return + } + + if (message[0] === 'OK' && message[1] === request.id) { + if (message[2] !== true) { + finish({ ok: false, message: typeof message[3] === 'string' ? message[3] : 'request rejected' }) + return + } + // The acceptance may follow the OK; give the relay one frame of grace. + finishTimer = setTimeout(() => finish(accept()), 500) + return + } + + if (message[0] === 'EVENT' && typeof message[2] === 'object' && message[2] !== null) { + const event = message[2] as Event + if (event.kind === 28938) { + acceptance = event + } + } + } + + const onClose = (): void => finish({ ok: false, message: 'connection closed before the reply' }) + const timer = setTimeout(() => finish({ ok: false, message: 'timed out waiting for the peer' }), timeoutMs) + + socket.on('message', onMessage) + socket.on('close', onClose) + socket.send(JSON.stringify(['EVENT', request])) + }) + +const acceptancePayload = (event: Event): PeeringAcceptancePayload | undefined => { + try { + return JSON.parse(event.content) as PeeringAcceptancePayload + } catch { + return undefined + } +} + +export interface RunPeeringRequestOptions { + relayUrl: string + ownerKey?: string + powDifficulty?: number + json?: boolean + timeoutMs?: number +} + +export interface PeeringRequestDependencies { + loadSettings?: () => Settings + fetchAdvertisement?: typeof fetchPeeringAdvertisement + authenticate?: typeof authenticateToPeeringRelay + relayPrivateKey?: () => string + send?: typeof sendPeeringRequest +} + +/** + * Produces and presents the one establishment request. The owner key is only + * used here; invoices, renewals and event requests never ask for it. + */ +export const runPeeringRequest = async ( + options: RunPeeringRequestOptions, + dependencies: PeeringRequestDependencies = {}, +): Promise => { + const loadSettings = dependencies.loadSettings ?? loadMergedSettings + const fetchAdvertisement = dependencies.fetchAdvertisement ?? fetchPeeringAdvertisement + const authenticate = dependencies.authenticate ?? authenticateToPeeringRelay + const relayPrivateKey = dependencies.relayPrivateKey ?? (() => getRelayPrivateKey()) + const send = dependencies.send ?? sendPeeringRequest + + const ownerKey = options.ownerKey ?? process.env.PEERING_OWNER_PRIVATE_KEY + if (!ownerKey || !/^[0-9a-fA-F]{64}$/.test(ownerKey)) { + throw new Error('set PEERING_OWNER_PRIVATE_KEY or pass --owner-key with a 32-byte hex key') + } + + const settings = loadSettings() + if (!settings.info?.relay_url) { + throw new Error('info.relay_url is required to identify this relay') + } + + const advertisement: PeeringAdvertisement = await fetchAdvertisement(options.relayUrl) + if (!advertisement.enabled) { + throw new Error('peer does not advertise peering') + } + if (!advertisement.self) { + throw new Error('peer does not advertise its relay pubkey in NIP-11 `self`') + } + + const relayKey = relayPrivateKey() + const request = await buildPeeringRequestEvent({ + ownerPrivateKey: ownerKey, + relayPubkey: getPublicKey(relayKey), + relayUrl: settings.info.relay_url, + receiverPubkey: advertisement.self, + scopes: advertisement.scopes, + terms: advertisement.terms, + powDifficulty: options.powDifficulty ?? advertisement.minPowDifficulty ?? 0, + maxPowAttempts: 50_000_000, + }) + + const connection = await authenticate({ + relayUrl: options.relayUrl, + privateKey: relayKey, + timeoutMs: options.timeoutMs, + }) + + let reply: PeeringRequestReply + try { + reply = await send(connection.socket, request, options.timeoutMs) + } finally { + try { + connection.socket.close() + } catch { + // Already closed by the peer. + } + } + + if (!reply.ok) { + logError(`peer rejected the peering request: ${reply.message}`) + return 1 + } + + if (reply.acceptance) { + const verified = await verifyPeeringAcceptanceEvent(reply.acceptance.event, request) + if (verified.ok === false) { + logError(`peer returned an invalid acceptance: ${verified.reason}`) + return 1 + } + if (reply.acceptance.event.pubkey.toLowerCase() !== advertisement.self.toLowerCase()) { + logError('peer returned an acceptance signed by a different relay key') + return 1 + } + } + + if (options.json) { + logInfo( + JSON.stringify( + { + request: { + id: request.id, + owner_pubkey: request.pubkey, + relay_pubkey: getPublicKey(relayKey), + terms_hash: JSON.parse(request.content).terms_hash, + }, + acceptance: reply.acceptance?.event ?? null, + }, + null, + 2, + ), + ) + return 0 + } + + logInfo(`request: ${request.id}`) + logInfo(`owner: ${request.pubkey}`) + logInfo(`relay: ${getPublicKey(relayKey)}`) + logInfo( + reply.acceptance + ? `acceptance: ${reply.acceptance.event.id}` + : 'acceptance: not returned (the request was accepted)', + ) + return 0 +} diff --git a/src/cli/index.ts b/src/cli/index.ts index 6567f173b..ee26bb3dc 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -32,6 +32,7 @@ import { runDevTestPerfMessage, } from './commands/dev' import { runInviteCreate } from './commands/invite' +import { runPeeringRequest } from './commands/peering' import { runTui } from './tui/main' import { logError, logInfo } from './utils/output' @@ -96,6 +97,11 @@ const inviteSubHelp: Record = { create: 'Usage: nostream invite create [--uses N] [--expires-in ] [--json]', } +const peeringSubHelp: Record = { + request: + 'Usage: nostream peering request [--owner-key ] [--pow ] [--timeout ] [--json]', +} + const devSubHelp: Record = { 'db:clean': 'Usage: nostream dev db:clean [--all|--older-than=|--kinds=1,7,4] [--dry-run] [--force]', 'db:reset': 'Usage: nostream dev db:reset [--yes]', @@ -288,10 +294,46 @@ cli }), ) +cli + .command('peering [...args]', 'Manage relay peering') + .option('--owner-key ', 'Owner private key used to sign the establishment request') + .option('--pow ', "Override the peer's advertised proof-of-work difficulty", { type: [Number] }) + .option('--timeout ', 'Authentication and reply timeout', { type: [Number] }) + .option('--json', 'Print machine-readable JSON') + .action( + withErrorBoundary(async (args: unknown, options: unknown) => { + const positional = (args as string[]) ?? [] + const command = positional[0] + const resolved = options as Record + + if (resolved.help && command && peeringSubHelp[command]) { + logInfo(peeringSubHelp[command]) + return 0 + } + + if (command !== 'request' || positional.length !== 2) { + throw new CliUsageError(peeringSubHelp.request) + } + + const timeoutSeconds = Array.isArray(resolved.timeout) ? resolved.timeout[0] : resolved.timeout + const pow = Array.isArray(resolved.pow) ? resolved.pow[0] : resolved.pow + + return runPeeringRequest({ + relayUrl: positional[1], + ownerKey: typeof resolved.ownerKey === 'string' ? resolved.ownerKey : undefined, + powDifficulty: typeof pow === 'number' ? pow : undefined, + timeoutMs: typeof timeoutSeconds === 'number' ? timeoutSeconds * 1000 : undefined, + json: Boolean(resolved.json), + }) + }), + ) + cli .command('invite [...args]', 'Mint NIP-43 invite codes') .option('--uses ', 'Times the code can be claimed (default: nip43.defaultMaxUses)', { type: [Number] }) - .option('--expires-in ', 'Code lifetime in seconds (default: nip43.inviteCodeExpirySeconds)', { type: [Number] }) + .option('--expires-in ', 'Code lifetime in seconds (default: nip43.inviteCodeExpirySeconds)', { + type: [Number], + }) .option('--json', 'Print machine-readable JSON') .action( withErrorBoundary(async (args: unknown, options: unknown) => { @@ -482,6 +524,7 @@ withErrorBoundary(async () => { 'update', 'clean', 'invite', + 'peering', ]) if (userArgs.length >= 2 && userArgs.includes('--help')) { @@ -509,6 +552,11 @@ withErrorBoundary(async () => { logInfo(inviteSubHelp[userArgs[1]]) return 0 } + + if (userArgs[0] === 'peering' && peeringSubHelp[userArgs[1]]) { + logInfo(peeringSubHelp[userArgs[1]]) + return 0 + } } if (userArgs.length > 0 && !userArgs[0].startsWith('-') && !knownTopLevel.has(userArgs[0])) { diff --git a/src/constants/base.ts b/src/constants/base.ts index d82f1fc0e..2b3f2363c 100644 --- a/src/constants/base.ts +++ b/src/constants/base.ts @@ -40,6 +40,9 @@ export enum EventKinds { // NIP-43: Relay Access Metadata and Requests NIP43_ADD_USER = 8000, NIP43_REMOVE_USER = 8001, + // Relay peering: owner-signed request and relay-signed acceptance (ephemeral). + PEERING_REQUEST = 28937, + PEERING_ACCEPTANCE = 28938, // Lightning zaps ZAP_REQUEST = 9734, ZAP_RECEIPT = 9735, diff --git a/src/factories/event-strategy-factory.ts b/src/factories/event-strategy-factory.ts index 8db6d2e75..844b4d7dc 100644 --- a/src/factories/event-strategy-factory.ts +++ b/src/factories/event-strategy-factory.ts @@ -3,6 +3,7 @@ import { IDvmJobRepository, IEventRepository, IInviteCodeRepository, + IPeeringAttestationRepository, IReportRepository, IUserRepository, } from '../@types/repositories' @@ -19,6 +20,9 @@ import { isRequestToVanishEvent, } from '../utils/event' import { isNip43InviteRequest, isNip43JoinRequest, isNip43LeaveRequest } from '../utils/nip43' +import { isPeeringAcceptanceEvent, isPeeringRequestEvent } from '../utils/peering-attestation' +import { PeeringAcceptanceEventStrategy } from '../handlers/event-strategies/peering-acceptance-event-strategy' +import { PeeringRequestEventStrategy } from '../handlers/event-strategies/peering-request-event-strategy' import { isReportEvent } from '../utils/nip56' import { isRelayListEvent } from '../utils/nip65' import { ContactListEventStrategy } from '../handlers/event-strategies/contact-list-event-strategy' @@ -52,6 +56,7 @@ export const eventStrategyFactory = reportRepository: IReportRepository, cache: ICacheAdapter, settings: () => Settings, + peeringAttestations?: IPeeringAttestationRepository, ): Factory>, [Event, IWebSocketAdapter]> => ([event, adapter]: [Event, IWebSocketAdapter]) => { if (isRequestToVanishEvent(event)) { @@ -116,6 +121,10 @@ export const eventStrategyFactory = // falling through to DefaultEventStrategy. } else if (isDvmJobRequestEvent(event)) { return new DvmJobRequestEventStrategy(adapter, eventRepository, dvmJobRepository) + } else if (isPeeringRequestEvent(event)) { + return new PeeringRequestEventStrategy(adapter, settings, peeringAttestations) + } else if (isPeeringAcceptanceEvent(event)) { + return new PeeringAcceptanceEventStrategy(adapter) } else if (isEphemeralEvent(event)) { return new EphemeralEventStrategy(adapter) } else if (isDeleteEvent(event)) { diff --git a/src/factories/message-handler-factory.ts b/src/factories/message-handler-factory.ts index 51bf87818..6a841190f 100644 --- a/src/factories/message-handler-factory.ts +++ b/src/factories/message-handler-factory.ts @@ -5,6 +5,7 @@ import { IEventRepository, IInviteCodeRepository, INip05VerificationRepository, + IPeeringAttestationRepository, IReportRepository, IUserRepository, } from '../@types/repositories' @@ -20,6 +21,7 @@ import { NegMsgMessageHandler } from '../handlers/neg-msg-message-handler' import { NegOpenMessageHandler } from '../handlers/neg-open-message-handler' import { SubscribeMessageHandler } from '../handlers/subscribe-message-handler' import { UnsubscribeMessageHandler } from '../handlers/unsubscribe-message-handler' +import { PeeringAttestationRepository } from '../repositories/peering-attestation-repository' import { UserSubscriptionRepository } from '../repositories/user-subscription-repository' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' import { eventStrategyFactory } from './event-strategy-factory' @@ -52,6 +54,14 @@ export const getPeerRequestStatsStore = (): PeeringRequestStatsStore => { return peerRequestStatsStore } +let peeringAttestationRepository: IPeeringAttestationRepository | undefined = undefined +export const getPeeringAttestationRepository = (): IPeeringAttestationRepository => { + if (!peeringAttestationRepository) { + peeringAttestationRepository = new PeeringAttestationRepository(getMasterDbClient()) + } + return peeringAttestationRepository +} + let peeringBillingService: IPeeringBillingService | undefined = undefined export const getPeeringBillingService = (): IPeeringBillingService => { if (!peeringBillingService) { @@ -93,6 +103,7 @@ export const messageHandlerFactory = reportRepository, getCache(), createSettings, + getPeeringAttestationRepository(), ), eventRepository, userRepository, @@ -126,7 +137,7 @@ export const messageHandlerFactory = peeringBillingServiceFor(adapter), ) case MessageType.AUTH: - return new AuthMessageHandler(adapter, createSettings) + return new AuthMessageHandler(adapter, createSettings, getPeeringAttestationRepository()) case MessageType.NEG_OPEN: return new NegOpenMessageHandler( adapter, diff --git a/src/handlers/auth-message-handler.ts b/src/handlers/auth-message-handler.ts index 88241007f..29e207525 100644 --- a/src/handlers/auth-message-handler.ts +++ b/src/handlers/auth-message-handler.ts @@ -5,9 +5,11 @@ import { createCommandResult } from '../utils/messages' import { createLogger } from '../factories/logger-factory' import { IMessageHandler } from '../@types/message-handlers' import { IWebSocketAdapter } from '../@types/adapters' +import type { IPeeringAttestationRepository } from '../@types/repositories' import { Settings } from '../@types/settings' import { WebSocketAdapterEvent } from '../constants/adapter' -import { isConfiguredPeeringPeer } from '../utils/peering-auth' +import { findConfiguredPeeringPeer, isConfiguredPeeringPeer } from '../utils/peering-auth' +import { peeringTermsHash, samePeeringScopes } from '../utils/peering-attestation' const logger = createLogger('auth-message-handler') @@ -18,6 +20,7 @@ export class AuthMessageHandler implements IMessageHandler { public constructor( private readonly webSocket: IWebSocketAdapter, private readonly settings: () => Settings, + private readonly peeringAttestations?: IPeeringAttestationRepository, ) {} public async handleMessage(message: AuthMessage): Promise { @@ -45,17 +48,13 @@ export class AuthMessageHandler implements IMessageHandler { return } - const challengeTag = event.tags.find( - (tag) => tag.length >= 2 && tag[0] === EventTags.Challenge, - ) + const challengeTag = event.tags.find((tag) => tag.length >= 2 && tag[0] === EventTags.Challenge) if (!challengeTag || challengeTag[1] !== this.webSocket.getChallenge()) { this.sendResult(event.id, false, 'invalid: challenge does not match') return } - const relayTag = event.tags.find( - (tag) => tag.length >= 2 && tag[0] === EventTags.AuthRelay, - ) + const relayTag = event.tags.find((tag) => tag.length >= 2 && tag[0] === EventTags.AuthRelay) const relayUrl = this.settings().info.relay_url if (!relayTag || !this.isRelayUrlMatch(relayTag[1], relayUrl)) { this.sendResult(event.id, false, 'invalid: relay url does not match') @@ -71,17 +70,60 @@ export class AuthMessageHandler implements IMessageHandler { // Peer identity is a verified AUTH from a configured pubkey, never a URL // or a self-declared key. Unconfigured pubkeys stay ordinary clients. if (isConfiguredPeeringPeer(this.settings(), event.pubkey)) { - this.webSocket.setPeerPubkey(event.pubkey) + await this.applyOwnerAttestationPolicy(event.pubkey) } this.sendResult(event.id, true, '') } + /** + * `required` withholds peer treatment until an accepted owner-signed request + * exists for this relay key. A request sent after AUTH unlocks the session; + * a failed lookup fails closed. + */ + private async applyOwnerAttestationPolicy(pubkey: string): Promise { + const policy = this.settings().peering?.ownerAttestation ?? 'waived' + if (policy !== 'required') { + this.webSocket.setPeerPubkey(pubkey) + return + } + + if (!this.peeringAttestations) { + logger('peer %s authenticated but no attestation store is available', pubkey) + return + } + + try { + const attestation = await this.peeringAttestations.findByRelayPubkey(pubkey) + if (attestation) { + // Terms and scopes are part of the agreement. A material change needs + // a fresh owner signature before peer treatment resumes. + const currentTerms = this.settings().peering?.terms ?? [] + const currentScopes = this.settings().peering?.scopes ?? [] + const configuredOwner = findConfiguredPeeringPeer(this.settings(), pubkey)?.ownerPubkey + const ownerMatches = + !configuredOwner || attestation.ownerPubkey?.toLowerCase() === configuredOwner.toLowerCase() + if ( + ownerMatches && + attestation.termsHash?.toLowerCase() === peeringTermsHash(currentTerms) && + samePeeringScopes(attestation.scopes ?? [], currentScopes) + ) { + this.webSocket.setPeerPubkey(pubkey) + return + } + logger('peer %s attestation no longer matches the advertised terms or scopes', pubkey) + return + } + } catch (error) { + logger('unable to read peering attestation for %s: %o', pubkey, error) + return + } + + logger('peer %s authenticated but has no accepted owner attestation', pubkey) + } + private sendResult(eventId: string, success: boolean, message: string): void { - this.webSocket.emit( - WebSocketAdapterEvent.Message, - createCommandResult(eventId, success, message), - ) + this.webSocket.emit(WebSocketAdapterEvent.Message, createCommandResult(eventId, success, message)) } // NIP-42 says domain-match is sufficient for relay URL comparison diff --git a/src/handlers/event-message-handler.ts b/src/handlers/event-message-handler.ts index bf6cb3244..70d2957a4 100644 --- a/src/handlers/event-message-handler.ts +++ b/src/handlers/event-message-handler.ts @@ -76,10 +76,7 @@ import { recordModerationRateLimitHitSafely } from '../utils/moderation-rate-lim * must not be announced as `rate-limited`: every client would back off for a * backend outage. */ -type RateLimitVerdict = - | { status: 'allowed' } - | { status: 'limited', retryAfterMs: number } - | { status: 'unavailable' } +type RateLimitVerdict = { status: 'allowed' } | { status: 'limited'; retryAfterMs: number } | { status: 'unavailable' } const logger = createLogger('event-message-handler') @@ -274,7 +271,10 @@ export class EventMessageHandler implements IMessageHandler { // respond to relay load the way an event id's mined-per-submission pow can. // The static pubkey.minLeadingZeroBits knob is left untouched regardless of // pow.enabled -- per maintainer direction on PR #756. - if (limits.pow?.enabled) { + if (event.kind === EventKinds.PEERING_REQUEST) { + // Peering requests carry their own NIP-13 requirement, checked by the + // strategy after the owner signature and AUTH identity are known. + } else if (limits.pow?.enabled) { const computedDifficulty = getAdaptivePowDifficulty(limits.pow) // Only consult the WoT graph when thresholds are actually configured -- // a distance lookup is unnecessary work otherwise, and skipping it also @@ -295,7 +295,11 @@ export class EventMessageHandler implements IMessageHandler { } } - if (typeof limits.pubkey?.minLeadingZeroBits !== 'undefined' && limits.pubkey.minLeadingZeroBits > 0) { + if ( + event.kind !== EventKinds.PEERING_REQUEST && + typeof limits.pubkey?.minLeadingZeroBits !== 'undefined' && + limits.pubkey.minLeadingZeroBits > 0 + ) { const pow = getPubkeyProofOfWork(event.pubkey) if (pow < limits.pubkey.minLeadingZeroBits) { return `pow: pubkey difficulty ${pow}<${limits.pubkey.minLeadingZeroBits}` @@ -303,6 +307,7 @@ export class EventMessageHandler implements IMessageHandler { } if ( + event.kind !== EventKinds.PEERING_REQUEST && typeof limits.pubkey?.whitelist !== 'undefined' && limits.pubkey.whitelist.length > 0 && !limits.pubkey.whitelist.includes(event.pubkey) @@ -319,6 +324,7 @@ export class EventMessageHandler implements IMessageHandler { } if ( + event.kind !== EventKinds.PEERING_REQUEST && typeof limits.kind?.whitelist !== 'undefined' && limits.kind.whitelist.length > 0 && !limits.kind.whitelist.some(isEventKindOrRangeMatch(event)) @@ -327,6 +333,7 @@ export class EventMessageHandler implements IMessageHandler { } if ( + event.kind !== EventKinds.PEERING_REQUEST && typeof limits.kind?.blacklist !== 'undefined' && limits.kind.blacklist.length > 0 && limits.kind.blacklist.some(isEventKindOrRangeMatch(event)) @@ -340,6 +347,12 @@ export class EventMessageHandler implements IMessageHandler { return } + // The owner signs the establishment record, but the relay key is the live + // identity on the socket. The strategy verifies both. + if (event.kind === EventKinds.PEERING_REQUEST) { + return + } + if (this.getRelayPublicKey() === event.pubkey) { return } @@ -610,7 +623,8 @@ export class EventMessageHandler implements IMessageHandler { if ( event.kind === EventKinds.NIP43_JOIN_REQUEST || event.kind === EventKinds.NIP43_LEAVE_REQUEST || - event.kind === EventKinds.NIP43_INVITE_REQUEST + event.kind === EventKinds.NIP43_INVITE_REQUEST || + event.kind === EventKinds.PEERING_REQUEST ) { return } @@ -717,7 +731,11 @@ export class EventMessageHandler implements IMessageHandler { // NIP-43: join/leave requests bypass NIP-05 — a new user won't have a // verification record yet, and requiring one would block the join flow. - if (event.kind === EventKinds.NIP43_JOIN_REQUEST || event.kind === EventKinds.NIP43_LEAVE_REQUEST) { + if ( + event.kind === EventKinds.NIP43_JOIN_REQUEST || + event.kind === EventKinds.NIP43_LEAVE_REQUEST || + event.kind === EventKinds.PEERING_REQUEST + ) { return } diff --git a/src/handlers/event-strategies/peering-acceptance-event-strategy.ts b/src/handlers/event-strategies/peering-acceptance-event-strategy.ts new file mode 100644 index 000000000..4871fa562 --- /dev/null +++ b/src/handlers/event-strategies/peering-acceptance-event-strategy.ts @@ -0,0 +1,20 @@ +import type { IWebSocketAdapter } from '../../@types/adapters' +import type { Event } from '../../@types/event' +import type { IEventStrategy } from '../../@types/message-handlers' +import { WebSocketAdapterEvent } from '../../constants/adapter' +import { createEventCommandResult } from '../../telemetry/event-metrics' + +/** + * Acceptances are issued by the relay itself. A client-published kind 28938 + * would otherwise fall through to the ephemeral broadcast path. + */ +export class PeeringAcceptanceEventStrategy implements IEventStrategy> { + public constructor(private readonly webSocket: IWebSocketAdapter) {} + + public async execute(event: Event): Promise { + this.webSocket.emit( + WebSocketAdapterEvent.Message, + createEventCommandResult(event.id, false, 'invalid: kind 28938 is issued by the relay'), + ) + } +} diff --git a/src/handlers/event-strategies/peering-request-event-strategy.ts b/src/handlers/event-strategies/peering-request-event-strategy.ts new file mode 100644 index 000000000..687ba3764 --- /dev/null +++ b/src/handlers/event-strategies/peering-request-event-strategy.ts @@ -0,0 +1,134 @@ +import type { IWebSocketAdapter } from '../../@types/adapters' +import type { Event } from '../../@types/event' +import type { PeeringAttestation } from '../../@types/peering' +import type { IEventStrategy } from '../../@types/message-handlers' +import type { IPeeringAttestationRepository } from '../../@types/repositories' +import type { Settings } from '../../@types/settings' +import { WebSocketAdapterEvent } from '../../constants/adapter' +import { createEventCommandResult } from '../../telemetry/event-metrics' +import { createLogger } from '../../factories/logger-factory' +import { getPublicKey, getRelayPrivateKey } from '../../utils/event' +import { findConfiguredPeeringPeer } from '../../utils/peering-auth' +import { resolveRelaySelfPubkey } from '../../utils/nip43' +import { + buildPeeringAcceptanceEvent, + parsePeeringRequestPayload, + verifyPeeringRequestEvent, +} from '../../utils/peering-attestation' +import { createOutgoingEventMessage } from '../../utils/messages' + +const logger = createLogger('peering-request-event-strategy') + +/** + * Owner-signed request presented once over the relay's authenticated peer + * socket. The owner key signs the establishment record; the relay key is the + * live proof on the connection. Only configured peers are accepted in v1. + */ +export class PeeringRequestEventStrategy implements IEventStrategy> { + public constructor( + private readonly webSocket: IWebSocketAdapter, + private readonly settings: () => Settings, + private readonly attestations?: IPeeringAttestationRepository, + private readonly now: () => Date = () => new Date(), + private readonly relayPrivateKey: () => string = () => getRelayPrivateKey(), + ) {} + + public async execute(event: Event): Promise { + const settings = this.settings() + const peering = settings.peering + + if (peering?.enabled !== true) { + this.reject(event, 'restricted: peering is not enabled on this relay') + return + } + + const payload = parsePeeringRequestPayload(event) + if (!payload) { + this.reject(event, 'invalid: malformed peering request payload') + return + } + + const configured = findConfiguredPeeringPeer(settings, payload.relay_pubkey) + if (!configured) { + logger('rejecting peering request from unconfigured relay %s', payload.relay_pubkey) + this.reject(event, 'restricted: this relay only peers with configured relay pubkeys') + return + } + + const relayPrivateKey = this.relayPrivateKey() + const receiverPubkey = (resolveRelaySelfPubkey(settings) ?? getPublicKey(relayPrivateKey)).toLowerCase() + const verified = await verifyPeeringRequestEvent(event, { + authenticatedPubkeys: this.webSocket.getAuthenticatedPubkeys(), + receiverPubkey, + offeredScopes: peering.scopes ?? [], + offeredTerms: peering.terms ?? [], + minPowDifficulty: peering.minRequestPowDifficulty ?? 0, + isConfiguredPeer: true, + waivePowForConfiguredPeers: peering.waiveRequestPowForConfiguredPeers, + expectedOwnerPubkey: configured.ownerPubkey, + now: this.now(), + }) + + if (verified.ok === false) { + logger('rejecting peering request from %s: %s', payload.relay_pubkey, verified.reason) + this.reject(event, verified.reason) + return + } + + const acceptedAt = this.now() + const attestation: PeeringAttestation = { + relayPubkey: verified.request.relay_pubkey, + ownerPubkey: event.pubkey, + relayUrl: verified.request.relay_url, + requestEventId: event.id, + scopes: verified.request.scopes, + terms: verified.request.terms, + termsHash: verified.request.terms_hash, + powDifficulty: verified.powDifficulty, + acceptedAt, + createdAt: acceptedAt, + updatedAt: acceptedAt, + } + + if (!this.attestations) { + this.reject(event, 'error: peering attestations are unavailable') + return + } + + try { + await this.attestations.save(attestation) + } catch (error) { + logger('unable to store peering attestation for %s: %o', payload.relay_pubkey, error) + this.reject(event, 'error: unable to record peering attestation') + return + } + + // A required-attestation relay withheld peer treatment at AUTH; the valid + // request is what unlocks it for this session. + this.webSocket.setPeerPubkey(verified.request.relay_pubkey) + + try { + const acceptance = await buildPeeringAcceptanceEvent({ + request: event, + acceptance: verified.request, + relayPrivateKey, + relayUrl: settings.info.relay_url, + createdAt: Math.floor(acceptedAt.getTime() / 1000), + }) + this.webSocket.emit(WebSocketAdapterEvent.Message, createOutgoingEventMessage('peering-acceptance', acceptance)) + } catch (error) { + // The record is stored; a failed reply can be retried by the peer. + logger('unable to send peering acceptance for %s: %o', payload.relay_pubkey, error) + } + + logger('accepted peering attestation from %s for relay %s', event.pubkey, payload.relay_pubkey) + this.webSocket.emit( + WebSocketAdapterEvent.Message, + createEventCommandResult(event.id, true, 'info: peering request accepted'), + ) + } + + private reject(event: Event, reason: string): void { + this.webSocket.emit(WebSocketAdapterEvent.Message, createEventCommandResult(event.id, false, reason)) + } +} diff --git a/src/handlers/request-handlers/root-request-handler.ts b/src/handlers/request-handlers/root-request-handler.ts index 2be6efa5c..50b885d08 100644 --- a/src/handlers/request-handlers/root-request-handler.ts +++ b/src/handlers/request-handlers/root-request-handler.ts @@ -22,9 +22,7 @@ export const hasExplicitNostrJsonAcceptHeader = (request: Request): boolean => { const acceptHeaderValue = Array.isArray(acceptHeader) ? acceptHeader.join(',') : acceptHeader return acceptHeaderValue.split(',').some((token) => { - const [mediaType, ...params] = token - .split(';') - .map((value) => value.trim().toLowerCase()) + const [mediaType, ...params] = token.split(';').map((value) => value.trim().toLowerCase()) if (mediaType !== 'application/nostr+json') { return false @@ -59,6 +57,7 @@ export const buildPeeringDocument = (peering: PeeringSettings | undefined) => { // NIP-11 convention: snake_case in the document, and 0/absent both mean // no proof-of-work requirement. min_pow_difficulty: peering.minRequestPowDifficulty ?? 0, + ...(peering.ownerAttestation ? { owner_attestation: peering.ownerAttestation } : {}), scopes: (peering.scopes ?? []).map((scope) => ({ kinds: scope.kinds, ...(scope.since !== undefined ? { since: scope.since } : {}), diff --git a/src/repositories/peering-attestation-repository.ts b/src/repositories/peering-attestation-repository.ts new file mode 100644 index 000000000..cadf1694d --- /dev/null +++ b/src/repositories/peering-attestation-repository.ts @@ -0,0 +1,69 @@ +import { DatabaseClient, Pubkey } from '../@types/base' +import type { DBPeeringAttestation, PeeringAttestation } from '../@types/peering' +import type { IPeeringAttestationRepository } from '../@types/repositories' +import { fromBuffer, toBuffer } from '../utils/transform' + +const fromRow = (row: DBPeeringAttestation): PeeringAttestation => ({ + relayPubkey: fromBuffer(row.relay_pubkey), + ownerPubkey: fromBuffer(row.owner_pubkey), + relayUrl: row.relay_url, + requestEventId: row.request_event_id, + scopes: row.scopes as PeeringAttestation['scopes'], + terms: row.terms as PeeringAttestation['terms'], + termsHash: row.terms_hash, + powDifficulty: row.pow_difficulty, + acceptedAt: row.accepted_at, + createdAt: row.created_at, + updatedAt: row.updated_at, +}) + +export class PeeringAttestationRepository implements IPeeringAttestationRepository { + public constructor(private readonly dbClient: DatabaseClient) {} + + public async findByRelayPubkey( + pubkey: Pubkey, + client: DatabaseClient = this.dbClient, + ): Promise { + const row = await client('peering_attestations') + .where({ relay_pubkey: toBuffer(pubkey) }) + .first() + + return row ? fromRow(row) : undefined + } + + public async save( + attestation: PeeringAttestation, + client: DatabaseClient = this.dbClient, + ): Promise { + const now = new Date() + const [row] = await client('peering_attestations') + .insert({ + relay_pubkey: toBuffer(attestation.relayPubkey), + owner_pubkey: toBuffer(attestation.ownerPubkey), + relay_url: attestation.relayUrl, + request_event_id: attestation.requestEventId, + scopes: JSON.stringify(attestation.scopes), + terms: JSON.stringify(attestation.terms), + terms_hash: attestation.termsHash, + pow_difficulty: attestation.powDifficulty, + accepted_at: attestation.acceptedAt ?? null, + created_at: now, + updated_at: now, + }) + .onConflict('relay_pubkey') + .merge({ + owner_pubkey: toBuffer(attestation.ownerPubkey), + relay_url: attestation.relayUrl, + request_event_id: attestation.requestEventId, + scopes: JSON.stringify(attestation.scopes), + terms: JSON.stringify(attestation.terms), + terms_hash: attestation.termsHash, + pow_difficulty: attestation.powDifficulty, + accepted_at: attestation.acceptedAt ?? null, + updated_at: now, + }) + .returning('*') + + return row ? fromRow(row) : { ...attestation, createdAt: now, updatedAt: now } + } +} diff --git a/src/utils/peering-advertisement.ts b/src/utils/peering-advertisement.ts index 36ce2f706..5c828b1a2 100644 --- a/src/utils/peering-advertisement.ts +++ b/src/utils/peering-advertisement.ts @@ -59,6 +59,8 @@ const peeringTermSchema = z.object({ const peeringDocumentSchema = z .object({ enabled: z.boolean().optional(), + owner_attestation: z.enum(['required', 'preferred', 'waived']).optional(), + min_pow_difficulty: z.number().int().min(0).max(256).optional(), scopes: z.array(advertisedScopeSchema).optional(), terms: z.array(peeringTermSchema).optional(), }) @@ -94,6 +96,8 @@ export const parsePeeringAdvertisement = (document: unknown): PeeringAdvertiseme scopes: [], terms: [], self: parsed.data.self?.toLowerCase(), + ...(peering?.owner_attestation ? { ownerAttestation: peering.owner_attestation } : {}), + ...(peering?.min_pow_difficulty !== undefined ? { minPowDifficulty: peering.min_pow_difficulty } : {}), supportedNips: parsed.data.supported_nips ?? [], } } @@ -123,6 +127,8 @@ export const parsePeeringAdvertisement = (document: unknown): PeeringAdvertiseme }), ), self: parsed.data.self?.toLowerCase(), + ...(peering?.owner_attestation ? { ownerAttestation: peering.owner_attestation } : {}), + ...(peering?.min_pow_difficulty !== undefined ? { minPowDifficulty: peering.min_pow_difficulty } : {}), supportedNips: parsed.data.supported_nips ?? [], } } diff --git a/src/utils/peering-attestation.ts b/src/utils/peering-attestation.ts new file mode 100644 index 000000000..c720e146a --- /dev/null +++ b/src/utils/peering-attestation.ts @@ -0,0 +1,368 @@ +import { createHash } from 'crypto' +import { z } from 'zod' + +import type { Tag } from '../@types/base' +import type { Event, UnidentifiedEvent, UnsignedEvent } from '../@types/event' +import type { PeeringAcceptancePayload, PeeringRequestPayload } from '../@types/peering' +import type { PeeringScope, PeeringTerm } from '../@types/settings' +import { EventKinds, EventTags } from '../constants/base' +import { + getEventProofOfWork, + getPublicKey, + identifyEvent, + isEventIdValid, + isEventSignatureValid, + signEvent, +} from './event' + +export const PEERING_REQUEST_TOPIC = 'peering-request' +export const PEERING_ACCEPTANCE_TOPIC = 'peering-acceptance' +/** A request older than this is stale and must be built again. */ +export const PEERING_REQUEST_MAX_AGE_SECONDS = 10 * 60 + +const hexPubkey = z.string().regex(/^[0-9a-fA-F]{64}$/) +const relayUrl = z + .string() + .url() + .refine((value) => ['ws:', 'wss:'].includes(new URL(value).protocol), 'relay_url must be ws:// or wss://') + +const peeringTermSchema = z.object({ + amount: z.number().finite().nonnegative(), + unit: z.string().min(1), + period: z.number().int().positive(), +}) + +const peeringScopeSchema = z + .object({ + kinds: z + .array( + z.union([ + z.number().int().min(0).max(65535), + z.tuple([z.number().int().min(0).max(65535), z.number().int().min(0).max(65535)]), + ]), + ) + .min(1), + since: z.number().int().min(0).optional(), + until: z.number().int().min(0).optional(), + windowSeconds: z.number().int().positive().optional(), + }) + .strict() + +const requestPayloadSchema = z + .object({ + relay_pubkey: hexPubkey, + relay_url: relayUrl, + scopes: z.array(peeringScopeSchema).min(1), + terms: z.array(peeringTermSchema), + terms_hash: z.string().regex(/^[0-9a-fA-F]{64}$/), + }) + .strict() + +const acceptancePayloadSchema = z + .object({ + request_id: z.string().regex(/^[0-9a-fA-F]{64}$/), + relay_pubkey: hexPubkey, + relay_url: relayUrl, + terms_hash: z.string().regex(/^[0-9a-fA-F]{64}$/), + accepted_at: z.number().int().min(0), + }) + .strict() + +const kindStart = (kind: number | [number, number]): number => (Array.isArray(kind) ? kind[0] : kind) +const kindEnd = (kind: number | [number, number]): number => (Array.isArray(kind) ? kind[1] : kind) + +const canonicalKind = (kind: number | [number, number]): number | [number, number] => + Array.isArray(kind) ? [kind[0], kind[1]] : kind + +/** Stable terms shape used for hashing and equality checks. */ +export const canonicalPeeringTerms = (terms: PeeringTerm[]): PeeringTerm[] => + terms + .map((term) => ({ + amount: term.amount, + unit: term.unit, + period: term.period, + })) + .sort((left, right) => { + if (left.period !== right.period) { + return left.period - right.period + } + if (left.amount !== right.amount) { + return left.amount - right.amount + } + return left.unit.localeCompare(right.unit) + }) + +/** Stable scope shape used for equality checks. */ +export const canonicalPeeringScopes = (scopes: PeeringScope[]): PeeringScope[] => + scopes + .map((scope) => ({ + kinds: [...scope.kinds] + .map(canonicalKind) + .sort((left, right) => kindStart(left) - kindStart(right) || kindEnd(left) - kindEnd(right)), + ...(scope.since !== undefined ? { since: scope.since } : {}), + ...(scope.until !== undefined ? { until: scope.until } : {}), + ...(scope.windowSeconds !== undefined ? { windowSeconds: scope.windowSeconds } : {}), + })) + .sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right))) + +export const peeringTermsHash = (terms: PeeringTerm[]): string => + createHash('sha256') + .update(JSON.stringify(canonicalPeeringTerms(terms))) + .digest('hex') + +export const samePeeringTerms = (left: PeeringTerm[], right: PeeringTerm[]): boolean => + JSON.stringify(canonicalPeeringTerms(left)) === JSON.stringify(canonicalPeeringTerms(right)) + +export const samePeeringScopes = (left: PeeringScope[], right: PeeringScope[]): boolean => + JSON.stringify(canonicalPeeringScopes(left)) === JSON.stringify(canonicalPeeringScopes(right)) + +const nonceTags = (tags: Tag[], nonce: number, difficulty: number): Tag[] => [ + ...tags.filter((tag) => tag[0] !== 'nonce'), + ['nonce', String(nonce), String(difficulty)], +] + +const identifyWithOptionalPow = async ( + unsigned: Omit, + difficulty: number, + maxAttempts: number, +): Promise => { + if (difficulty <= 0) { + return identifyEvent(unsigned) + } + + for (let nonce = 0; nonce < maxAttempts; nonce += 1) { + const candidate = await identifyEvent({ + ...unsigned, + tags: nonceTags(unsigned.tags as Tag[], nonce, difficulty), + }) + if (getEventProofOfWork(candidate.id) >= difficulty) { + return candidate + } + } + + throw new Error(`unable to find ${difficulty}-bit proof-of-work within ${maxAttempts} attempts`) +} + +export interface BuildPeeringRequestOptions { + /** The operator's key. It is only used to sign the establishment request. */ + ownerPrivateKey: string + relayPubkey: string + relayUrl: string + receiverPubkey: string + scopes: PeeringScope[] + terms: PeeringTerm[] + powDifficulty?: number + createdAt?: number + maxPowAttempts?: number +} + +/** + * Builds the owner-signed request a relay presents once at establishment. It + * never includes an operational event, and the owner key is not stored. + */ +export const buildPeeringRequestEvent = async (options: BuildPeeringRequestOptions): Promise => { + const ownerPubkey = getPublicKey(options.ownerPrivateKey) + const relayPubkey = options.relayPubkey.toLowerCase() + const receiverPubkey = options.receiverPubkey.toLowerCase() + + if (!/^[0-9a-f]{64}$/.test(relayPubkey) || !/^[0-9a-f]{64}$/.test(receiverPubkey)) { + throw new Error('relay and receiver pubkeys must be 32-byte hex keys') + } + + const payload: PeeringRequestPayload = { + relay_pubkey: relayPubkey, + relay_url: options.relayUrl, + scopes: canonicalPeeringScopes(options.scopes), + terms: canonicalPeeringTerms(options.terms), + terms_hash: peeringTermsHash(options.terms), + } + + const identified = await identifyWithOptionalPow( + { + pubkey: ownerPubkey, + created_at: options.createdAt ?? Math.floor(Date.now() / 1000), + kind: EventKinds.PEERING_REQUEST, + tags: [ + [EventTags.Pubkey, receiverPubkey], + [EventTags.Tag, PEERING_REQUEST_TOPIC], + ] as Tag[], + content: JSON.stringify(payload), + }, + Math.max(0, Math.floor(options.powDifficulty ?? 0)), + Math.max(1, options.maxPowAttempts ?? 5_000_000), + ) + + return signEvent(options.ownerPrivateKey)(identified) +} + +export const parsePeeringRequestPayload = (event: Event): PeeringRequestPayload | undefined => { + try { + return requestPayloadSchema.parse(JSON.parse(event.content)) as PeeringRequestPayload + } catch { + return undefined + } +} + +export interface VerifyPeeringRequestOptions { + /** Pubkeys proven by NIP-42 on the connection that delivered the event. */ + authenticatedPubkeys: Iterable + /** This relay's own pubkey, which the request must target. */ + receiverPubkey: string + offeredScopes: PeeringScope[] + offeredTerms: PeeringTerm[] + minPowDifficulty?: number + isConfiguredPeer?: boolean + waivePowForConfiguredPeers?: boolean + /** When configured, only this owner key may sign the request. */ + expectedOwnerPubkey?: string + now?: Date +} + +export type PeeringRequestVerification = + | { ok: true; request: PeeringRequestPayload; powDifficulty: number } + | { ok: false; reason: string } + +/** + * Verifies the two-part establishment proof: the owner signature on the + * request, and the relay key proven by NIP-42 on the same connection. Terms + * and scopes must match this relay's current advertisement, so a stale request + * cannot silently accept changed terms. + */ +export const verifyPeeringRequestEvent = async ( + event: Event, + options: VerifyPeeringRequestOptions, +): Promise => { + if (!event || event.kind !== EventKinds.PEERING_REQUEST) { + return { ok: false, reason: 'not a peering request' } + } + + if (!(await isEventIdValid(event)) || !(await isEventSignatureValid(event))) { + return { ok: false, reason: 'invalid: event signature verification failed' } + } + + const now = options.now ?? new Date() + const nowSeconds = Math.floor(now.getTime() / 1000) + if (Math.abs(nowSeconds - event.created_at) > PEERING_REQUEST_MAX_AGE_SECONDS) { + return { ok: false, reason: 'invalid: peering request is stale' } + } + + const payload = parsePeeringRequestPayload(event) + if (!payload) { + return { ok: false, reason: 'invalid: malformed peering request payload' } + } + + const relayPubkey = payload.relay_pubkey.toLowerCase() + const authenticated = new Set([...options.authenticatedPubkeys].map((pubkey) => pubkey.toLowerCase())) + if (!authenticated.has(relayPubkey)) { + return { ok: false, reason: 'auth-required: peering request relay key is not authenticated' } + } + + if (options.expectedOwnerPubkey && event.pubkey.toLowerCase() !== options.expectedOwnerPubkey.toLowerCase()) { + return { ok: false, reason: 'invalid: request owner does not match the configured owner' } + } + + const target = event.tags.find( + (tag) => tag[0] === EventTags.Pubkey && tag[1]?.toLowerCase() === options.receiverPubkey.toLowerCase(), + ) + if (!target) { + return { ok: false, reason: 'invalid: peering request does not target this relay' } + } + + if (!samePeeringTerms(payload.terms, options.offeredTerms)) { + return { ok: false, reason: 'invalid: peering terms changed; request peering again' } + } + + if (payload.terms_hash.toLowerCase() !== peeringTermsHash(options.offeredTerms)) { + return { ok: false, reason: 'invalid: peering terms hash does not match' } + } + + if (!samePeeringScopes(payload.scopes, options.offeredScopes)) { + return { ok: false, reason: 'invalid: requested scope is not offered by this relay' } + } + + const waived = options.isConfiguredPeer === true && options.waivePowForConfiguredPeers !== false + const requiredPow = waived ? 0 : Math.max(0, Math.floor(options.minPowDifficulty ?? 0)) + const powDifficulty = getEventProofOfWork(event.id) + if (powDifficulty < requiredPow) { + return { + ok: false, + reason: `pow: peering request needs ${requiredPow} leading zero bits`, + } + } + + return { ok: true, request: { ...payload, relay_pubkey: relayPubkey }, powDifficulty } +} + +export interface BuildPeeringAcceptanceOptions { + request: Event + acceptance: PeeringRequestPayload + relayPrivateKey: string + relayUrl: string + createdAt?: number +} + +/** The receiving relay's signed record of what it accepted and on which terms. */ +export const buildPeeringAcceptanceEvent = async (options: BuildPeeringAcceptanceOptions): Promise => { + const relayPubkey = getPublicKey(options.relayPrivateKey) + const payload: PeeringAcceptancePayload = { + request_id: options.request.id, + relay_pubkey: relayPubkey, + relay_url: options.relayUrl, + terms_hash: options.acceptance.terms_hash, + accepted_at: options.createdAt ?? Math.floor(Date.now() / 1000), + } + + const unidentified: UnidentifiedEvent = { + pubkey: relayPubkey, + created_at: payload.accepted_at, + kind: EventKinds.PEERING_ACCEPTANCE, + tags: [ + [EventTags.Event, options.request.id], + [EventTags.Pubkey, options.request.pubkey], + [EventTags.Tag, PEERING_ACCEPTANCE_TOPIC], + ] as Tag[], + content: JSON.stringify(payload), + } + + return signEvent(options.relayPrivateKey)(await identifyEvent(unidentified)) +} + +export const verifyPeeringAcceptanceEvent = async ( + event: Event, + request: Event, +): Promise<{ ok: true; acceptance: PeeringAcceptancePayload } | { ok: false; reason: string }> => { + if (!event || event.kind !== EventKinds.PEERING_ACCEPTANCE) { + return { ok: false, reason: 'not a peering acceptance' } + } + if (!(await isEventIdValid(event)) || !(await isEventSignatureValid(event))) { + return { ok: false, reason: 'invalid: acceptance signature verification failed' } + } + if (!event.tags.some((tag) => tag[0] === EventTags.Event && tag[1] === request.id)) { + return { ok: false, reason: 'invalid: acceptance does not reference the request' } + } + + let acceptance: PeeringAcceptancePayload + try { + acceptance = acceptancePayloadSchema.parse(JSON.parse(event.content)) as PeeringAcceptancePayload + } catch { + return { ok: false, reason: 'invalid: malformed peering acceptance' } + } + + if (acceptance.request_id !== request.id) { + return { ok: false, reason: 'invalid: acceptance request id does not match' } + } + if (acceptance.relay_pubkey.toLowerCase() !== event.pubkey.toLowerCase()) { + return { ok: false, reason: 'invalid: acceptance signer does not match its relay key' } + } + + const requestPayload = parsePeeringRequestPayload(request) + if (!requestPayload || acceptance.terms_hash.toLowerCase() !== requestPayload.terms_hash.toLowerCase()) { + return { ok: false, reason: 'invalid: acceptance terms do not match the request' } + } + + return { ok: true, acceptance } +} + +export const isPeeringRequestEvent = (event: Event): boolean => event.kind === EventKinds.PEERING_REQUEST + +export const isPeeringAcceptanceEvent = (event: Event): boolean => event.kind === EventKinds.PEERING_ACCEPTANCE diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index eced71449..5817ab116 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -152,10 +152,7 @@ const reclaimSettingsWriteLock = (lockPath: string): void => { fs.rmSync(reclaimPath, { force: true }) } -const attemptStealStaleSettingsWriteLock = ( - lockPath: string, - expected: SettingsWriteLockMetadata, -): boolean => { +const attemptStealStaleSettingsWriteLock = (lockPath: string, expected: SettingsWriteLockMetadata): boolean => { try { const current = readSettingsWriteLockMetadata(lockPath) if ( @@ -613,14 +610,9 @@ export const filterSettingsAgainstDefaults = (settings: unknown, defaults: unkno if (hasOwn(defaults, key) || key === 'passwordHash') { // If it's a known non-schema key like passwordHash, we don't have a default schema for its children. // We can pass {} to allow it to be preserved. - const defaultSubSchema = hasOwn(defaults, key) - ? (defaults as Record)[key] - : {} + const defaultSubSchema = hasOwn(defaults, key) ? (defaults as Record)[key] : {} - filtered[key] = filterSettingsAgainstDefaults( - (settings as Record)[key], - defaultSubSchema - ) + filtered[key] = filterSettingsAgainstDefaults((settings as Record)[key], defaultSubSchema) } } return filtered @@ -952,7 +944,7 @@ const PEERING_KIND_MAX = 65535 const PEERING_POW_MAX_BITS = 256 const PEERING_SCOPE_KEYS = new Set(['kinds', 'since', 'until', 'windowSeconds']) const PEERING_TERM_KEYS = new Set(['amount', 'unit', 'period']) -const PEERING_PEER_KEYS = new Set(['pubkey', 'relayUrl', 'enabled', 'budget']) +const PEERING_PEER_KEYS = new Set(['pubkey', 'relayUrl', 'enabled', 'budget', 'ownerPubkey']) const PEERING_AUTOPAY_KEYS = new Set(['enabled', 'globalBudget']) const isValidPeeringKindValue = (value: unknown): boolean => @@ -1143,6 +1135,10 @@ const validatePeeringPeers = (peers: unknown, issues: ValidationIssue[]): void = issues.push({ path: `${prefix}.enabled`, message: 'must be a boolean' }) } + if (peer.ownerPubkey !== undefined && parsePeeringPeerPubkey(peer.ownerPubkey) === undefined) { + issues.push({ path: `${prefix}.ownerPubkey`, message: 'must be a 32-byte hex pubkey or npub' }) + } + if (peer.budget !== undefined) { validatePeeringTermValue(peer.budget, `${prefix}.budget`, issues, { allowZero: false }) } @@ -1165,12 +1161,7 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void => if (peering.minRequestPowDifficulty !== undefined) { const bits = peering.minRequestPowDifficulty - if ( - typeof bits !== 'number' || - !Number.isInteger(bits) || - bits < 0 || - bits > PEERING_POW_MAX_BITS - ) { + if (typeof bits !== 'number' || !Number.isInteger(bits) || bits < 0 || bits > PEERING_POW_MAX_BITS) { issues.push({ path: 'peering.minRequestPowDifficulty', message: `must be an integer between 0 and ${PEERING_POW_MAX_BITS}`, @@ -1178,6 +1169,26 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void => } } + if ( + peering.ownerAttestation !== undefined && + !['required', 'preferred', 'waived'].includes(peering.ownerAttestation as string) + ) { + issues.push({ + path: 'peering.ownerAttestation', + message: 'must be one of required, preferred or waived', + }) + } + + if ( + peering.waiveRequestPowForConfiguredPeers !== undefined && + typeof peering.waiveRequestPowForConfiguredPeers !== 'boolean' + ) { + issues.push({ + path: 'peering.waiveRequestPowForConfiguredPeers', + message: 'must be a boolean', + }) + } + const endpoint = typeof peering.endpoint === 'string' ? peering.endpoint.trim() : '' if (endpoint) { try { @@ -1238,9 +1249,7 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void => } const paidTerms = Array.isArray(peering.terms) - ? peering.terms.filter( - (term) => isPlainObject(term) && typeof term.amount === 'number' && term.amount > 0, - ) + ? peering.terms.filter((term) => isPlainObject(term) && typeof term.amount === 'number' && term.amount > 0) : [] if (paidTerms.length > 1) { @@ -1454,10 +1463,7 @@ const validateAdminNotifications = (settings: Settings): ValidationIssue[] => { targetIds.add(target.id) } - if ( - typeof target.type !== 'string' || - !['http', 'discord', 'slack', 'telegram'].includes(target.type) - ) { + if (typeof target.type !== 'string' || !['http', 'discord', 'slack', 'telegram'].includes(target.type)) { issues.push({ path: `${prefix}.type`, message: 'type must be http, discord, slack, or telegram' }) } diff --git a/test/integration/features/peering/peering-owner-attestation.feature b/test/integration/features/peering/peering-owner-attestation.feature new file mode 100644 index 000000000..e4746d07f --- /dev/null +++ b/test/integration/features/peering/peering-owner-attestation.feature @@ -0,0 +1,7 @@ +@peering-owner-attestation +Feature: Owner-attested peering requests + + Scenario: A configured relay is attested and later recognized at AUTH + When a configured relay presents an owner-signed peering request + Then the request is stored as an accepted attestation + And a later AUTH from that relay is recognized without repeating the request diff --git a/test/integration/features/peering/peering-owner-attestation.feature.ts b/test/integration/features/peering/peering-owner-attestation.feature.ts new file mode 100644 index 000000000..be8646b4c --- /dev/null +++ b/test/integration/features/peering/peering-owner-attestation.feature.ts @@ -0,0 +1,136 @@ +import { After, Before, Then, When, World } from '@cucumber/cucumber' +import { expect } from 'chai' +import Sinon from 'sinon' + +import { MessageType } from '../../../../src/@types/messages' +import { Settings } from '../../../../src/@types/settings' +import { getMasterDbClient } from '../../../../src/database/client' +import { AuthMessageHandler } from '../../../../src/handlers/auth-message-handler' +import { PeeringRequestEventStrategy } from '../../../../src/handlers/event-strategies/peering-request-event-strategy' +import { PeeringAttestationRepository } from '../../../../src/repositories/peering-attestation-repository' +import { getPublicKey } from '../../../../src/utils/event' +import { buildPeeringAuthEvent } from '../../../../src/utils/peering-auth' +import { buildPeeringRequestEvent } from '../../../../src/utils/peering-attestation' + +const ownerKey = '1'.repeat(64) +const relayKey = '2'.repeat(64) +const receiverKey = '3'.repeat(64) +const ownerPubkey = getPublicKey(ownerKey) +const relayPubkey = getPublicKey(relayKey) +const receiverPubkey = getPublicKey(receiverKey) +const relayUrl = 'wss://receiver.example.com' +const challenge = 'integration-peering-challenge' + +const settingsFor = (): Settings => + ({ + info: { name: 'Receiver', relay_url: relayUrl, self: receiverPubkey }, + peering: { + enabled: true, + ownerAttestation: 'required', + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + peers: [ + { + pubkey: relayPubkey, + relayUrl: 'wss://requester.example.com', + ownerPubkey, + }, + ], + }, + }) as Settings + +const adapterFor = (authenticated: string[] = []) => { + const setPeerPubkey = Sinon.stub() + const emit = Sinon.stub() + const adapter = { + emit, + setPeerPubkey, + getPeerPubkey: Sinon.stub().returns(undefined), + getAuthenticatedPubkeys: Sinon.stub().returns(new Set(authenticated)), + getChallenge: Sinon.stub().returns(challenge), + addAuthenticatedPubkey: Sinon.stub().returns(true), + } + + return { adapter, setPeerPubkey, emit } +} + +Before({ tags: '@peering-owner-attestation' }, async function (this: World>) { + this.parameters.attestationSandbox = Sinon.createSandbox() + this.parameters.attestationDb = getMasterDbClient() + await this.parameters + .attestationDb('peering_attestations') + .where('relay_pubkey', Buffer.from(relayPubkey, 'hex')) + .delete() +}) + +After({ tags: '@peering-owner-attestation' }, async function (this: World>) { + const db = this.parameters.attestationDb + if (db) { + await db('peering_attestations').where('relay_pubkey', Buffer.from(relayPubkey, 'hex')).delete() + } + this.parameters.attestationSandbox?.restore() + this.parameters.attestationDb = undefined +}) + +When('a configured relay presents an owner-signed peering request', async function (this: World>) { + const settings = settingsFor() + const repository = new PeeringAttestationRepository(this.parameters.attestationDb) + const now = new Date() + const request = await buildPeeringRequestEvent({ + ownerPrivateKey: ownerKey, + relayPubkey, + relayUrl: 'wss://requester.example.com', + receiverPubkey, + scopes: settings.peering!.scopes!, + terms: settings.peering!.terms!, + createdAt: Math.floor(now.getTime() / 1000), + }) + const { adapter, setPeerPubkey } = adapterFor([relayPubkey]) + const strategy = new PeeringRequestEventStrategy( + adapter as any, + () => settings, + repository, + () => now, + () => receiverKey, + ) + + await strategy.execute(request) + + this.parameters.attestationRepository = repository + this.parameters.attestationSettings = settings + this.parameters.attestationRequest = request + this.parameters.attestationSetPeerPubkey = setPeerPubkey +}) + +Then('the request is stored as an accepted attestation', async function (this: World>) { + const repository = this.parameters.attestationRepository as PeeringAttestationRepository + const attestation = await repository.findByRelayPubkey(relayPubkey) + + expect(attestation).to.exist + expect(attestation?.ownerPubkey).to.equal(ownerPubkey) + expect(attestation?.requestEventId).to.equal(this.parameters.attestationRequest.id) + expect(attestation?.termsHash).to.equal(JSON.parse(this.parameters.attestationRequest.content).terms_hash) + Sinon.assert.calledWith(this.parameters.attestationSetPeerPubkey, relayPubkey) +}) + +Then( + 'a later AUTH from that relay is recognized without repeating the request', + async function (this: World>) { + const authEvent = await buildPeeringAuthEvent({ + relayUrl, + challenge, + privateKey: relayKey, + createdAt: Math.floor(Date.now() / 1000), + }) + const { adapter, setPeerPubkey } = adapterFor() + const handler = new AuthMessageHandler( + adapter as any, + () => this.parameters.attestationSettings, + this.parameters.attestationRepository, + ) + + await handler.handleMessage([MessageType.AUTH, authEvent] as any) + + Sinon.assert.calledWith(setPeerPubkey, relayPubkey) + }, +) diff --git a/test/unit/cli/peering.spec.ts b/test/unit/cli/peering.spec.ts new file mode 100644 index 000000000..66bd3617c --- /dev/null +++ b/test/unit/cli/peering.spec.ts @@ -0,0 +1,149 @@ +import chai from 'chai' +import EventEmitter from 'events' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import type { Event } from '../../../src/@types/event' +import { runPeeringRequest, sendPeeringRequest } from '../../../src/cli/commands/peering' +import { getPublicKey, identifyEvent, signEvent } from '../../../src/utils/event' + +chai.use(sinonChai) +const { expect } = chai + +const ownerKey = '1'.repeat(64) +const relayKey = '2'.repeat(64) +const receiverKey = '3'.repeat(64) +const ownerPubkey = getPublicKey(ownerKey) +const relayPubkey = getPublicKey(relayKey) +const receiverPubkey = getPublicKey(receiverKey) +const scopes = [{ kinds: [1] }] +const terms = [{ amount: 21000, unit: 'msats', period: 2592000 }] + +const requestEvent = async (): Promise => + signEvent(ownerKey)( + await identifyEvent({ + pubkey: ownerPubkey, + created_at: Math.floor(Date.now() / 1000), + kind: 28937, + tags: [], + content: '{}', + }), + ) + +const acceptanceEvent = async (request: Event): Promise => + signEvent(receiverKey)( + await identifyEvent({ + pubkey: receiverPubkey, + created_at: Math.floor(Date.now() / 1000), + kind: 28938, + tags: [['e', request.id]], + content: JSON.stringify({ + request_id: request.id, + relay_pubkey: receiverPubkey, + relay_url: 'wss://receiver.example.com', + terms_hash: 'f'.repeat(64), + accepted_at: Math.floor(Date.now() / 1000), + }), + }), + ) + +class FakeSocket extends EventEmitter { + public readonly sent: string[] = [] + public close = Sinon.stub() + + public send(message: string): void { + this.sent.push(message) + } +} + +describe('peering CLI', () => { + afterEach(() => Sinon.restore()) + + it('sends the request and resolves with the acceptance', async () => { + const request = await requestEvent() + const acceptance = await acceptanceEvent(request) + const socket = new FakeSocket() + socket.send = (message: string) => { + socket.sent.push(message) + setImmediate(() => { + socket.emit('message', Buffer.from(JSON.stringify(['EVENT', 'peering-acceptance', acceptance]))) + socket.emit('message', Buffer.from(JSON.stringify(['OK', request.id, true, '']))) + }) + } + + const reply = await sendPeeringRequest(socket as any, request, 1_000) + + expect(reply.ok).to.equal(true) + expect(reply.acceptance?.event.id).to.equal(acceptance.id) + }) + + it('returns the peer rejection reason', async () => { + const request = await requestEvent() + const socket = new FakeSocket() + socket.send = (message: string) => { + socket.sent.push(message) + setImmediate(() => { + socket.emit('message', Buffer.from(JSON.stringify(['OK', request.id, false, 'restricted: not configured']))) + }) + } + + const reply = await sendPeeringRequest(socket as any, request, 1_000) + + expect(reply).to.include({ ok: false, message: 'restricted: not configured' }) + }) + + it('builds a request for the advertised terms and sends it', async () => { + const socket = new FakeSocket() + let sent: Event | undefined + const log = Sinon.stub(process.stdout, 'write') + + const code = await runPeeringRequest( + { relayUrl: 'wss://peer.example.com', ownerKey, json: true }, + { + loadSettings: () => ({ info: { relay_url: 'wss://me.example.com' } }) as any, + fetchAdvertisement: async () => ({ + enabled: true, + self: receiverPubkey, + scopes, + terms, + supportedNips: [77], + }), + authenticate: async () => ({ socket: socket as any, challenge: 'c', authEvent: {} as any }), + relayPrivateKey: () => relayKey, + send: async (_socket, request) => { + sent = request + return { ok: true, message: 'accepted' } + }, + }, + ) + + expect(code).to.equal(0) + expect(sent?.pubkey).to.equal(ownerPubkey) + expect(JSON.parse(sent!.content)).to.include({ + relay_pubkey: relayPubkey, + relay_url: 'wss://me.example.com', + }) + expect(socket.close).to.have.been.calledOnce + expect(log).to.have.been.called + }) + + it('requires an owner key', async () => { + const previous = process.env.PEERING_OWNER_PRIVATE_KEY + delete process.env.PEERING_OWNER_PRIVATE_KEY + + try { + let error: unknown + try { + await runPeeringRequest({ relayUrl: 'wss://peer.example.com' }) + } catch (caught) { + error = caught + } + expect(error).to.be.instanceOf(Error) + expect((error as Error).message).to.include('PEERING_OWNER_PRIVATE_KEY') + } finally { + if (previous !== undefined) { + process.env.PEERING_OWNER_PRIVATE_KEY = previous + } + } + }) +}) diff --git a/test/unit/factories/event-strategy-factory.spec.ts b/test/unit/factories/event-strategy-factory.spec.ts index 6d2a8db56..8d1fe1bc1 100644 --- a/test/unit/factories/event-strategy-factory.spec.ts +++ b/test/unit/factories/event-strategy-factory.spec.ts @@ -24,6 +24,8 @@ import { InviteRequestEventStrategy } from '../../../src/handlers/event-strategi import { JoinRequestEventStrategy } from '../../../src/handlers/event-strategies/join-request-event-strategy' import { LeaveRequestEventStrategy } from '../../../src/handlers/event-strategies/leave-request-event-strategy' import { ParameterizedReplaceableEventStrategy } from '../../../src/handlers/event-strategies/parameterized-replaceable-event-strategy' +import { PeeringAcceptanceEventStrategy } from '../../../src/handlers/event-strategies/peering-acceptance-event-strategy' +import { PeeringRequestEventStrategy } from '../../../src/handlers/event-strategies/peering-request-event-strategy' import { ReplaceableEventStrategy } from '../../../src/handlers/event-strategies/replaceable-event-strategy' import { ReportEventStrategy } from '../../../src/handlers/event-strategies/report-event-strategy' import { Settings } from '../../../src/@types/settings' @@ -84,6 +86,16 @@ describe('eventStrategyFactory', () => { expect(factory([event, adapter])).to.be.an.instanceOf(ReplaceableEventStrategy) }) + it('returns PeeringRequestEventStrategy for a peering request', () => { + event.kind = EventKinds.PEERING_REQUEST + expect(factory([event, adapter])).to.be.an.instanceOf(PeeringRequestEventStrategy) + }) + + it('returns PeeringAcceptanceEventStrategy for a peering acceptance', () => { + event.kind = EventKinds.PEERING_ACCEPTANCE + expect(factory([event, adapter])).to.be.an.instanceOf(PeeringAcceptanceEventStrategy) + }) + it('returns EphemeralEventStrategy given an ephemeral event', () => { event.kind = EventKinds.EPHEMERAL_FIRST expect(factory([event, adapter])).to.be.an.instanceOf(EphemeralEventStrategy) diff --git a/test/unit/handlers/auth-message-handler.spec.ts b/test/unit/handlers/auth-message-handler.spec.ts index b8606ad13..a7a1b2c73 100644 --- a/test/unit/handlers/auth-message-handler.spec.ts +++ b/test/unit/handlers/auth-message-handler.spec.ts @@ -14,6 +14,7 @@ import { IMessageHandler } from '../../../src/@types/message-handlers' import { IWebSocketAdapter } from '../../../src/@types/adapters' import { Settings } from '../../../src/@types/settings' import { WebSocketAdapterEvent } from '../../../src/constants/adapter' +import { peeringTermsHash } from '../../../src/utils/peering-attestation' describe('AuthMessageHandler', () => { let handler: IMessageHandler @@ -26,14 +27,16 @@ describe('AuthMessageHandler', () => { const privkey = 'a'.repeat(64) const pubkey = getPublicKey(privkey) - async function createAuthEvent(overrides: { - kind?: number - challenge?: string - relayUrl?: string - created_at?: number - invalidId?: boolean - invalidSig?: boolean - } = {}): Promise { + async function createAuthEvent( + overrides: { + kind?: number + challenge?: string + relayUrl?: string + created_at?: number + invalidId?: boolean + invalidSig?: boolean + } = {}, + ): Promise { const kind = overrides.kind ?? EventKinds.AUTH const now = overrides.created_at ?? Math.floor(Date.now() / 1000) const tags = [ @@ -53,9 +56,7 @@ describe('AuthMessageHandler', () => { identified.id = 'f'.repeat(64) } - const signed = overrides.invalidSig - ? { ...identified, sig: '0'.repeat(128) } - : await signEvent(privkey)(identified) + const signed = overrides.invalidSig ? { ...identified, sig: '0'.repeat(128) } : await signEvent(privkey)(identified) return [ MessageType.AUTH, @@ -102,7 +103,10 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).to.have.been.calledOnceWithExactly(pubkey, message[1].id) + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).to.have.been.calledOnceWithExactly( + pubkey, + message[1].id, + ) expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[0]).to.equal(WebSocketAdapterEvent.Message) @@ -110,12 +114,110 @@ describe('AuthMessageHandler', () => { expect(args[1][2]).to.equal(true) }) + it('withholds peer treatment when attestation is required and missing', async () => { + settingsFactory.returns({ + info: { relay_url: relayUrl }, + peering: { + enabled: true, + ownerAttestation: 'required', + peers: [{ pubkey, relayUrl }], + }, + } as Partial) + const peeringAttestations = { + findByRelayPubkey: Sinon.stub().resolves(undefined), + } + handler = new AuthMessageHandler(webSocket, settingsFactory, peeringAttestations as any) + const message = await createAuthEvent() + + await handler.handleMessage(message) + + expect(webSocket.setPeerPubkey as Sinon.SinonStub).not.to.have.been.called + expect(emitStub.firstCall.args[1][2]).to.equal(true) + }) + + it('withholds a required attestation whose terms changed', async () => { + settingsFactory.returns({ + info: { relay_url: relayUrl }, + peering: { + enabled: true, + ownerAttestation: 'required', + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + peers: [{ pubkey, relayUrl }], + }, + } as Partial) + const peeringAttestations = { + findByRelayPubkey: Sinon.stub().resolves({ + relayPubkey: pubkey, + termsHash: peeringTermsHash([{ amount: 22000, unit: 'msats', period: 2592000 }]), + scopes: [{ kinds: [1] }], + }), + } + handler = new AuthMessageHandler(webSocket, settingsFactory, peeringAttestations as any) + const message = await createAuthEvent() + + await handler.handleMessage(message) + + expect(webSocket.setPeerPubkey as Sinon.SinonStub).not.to.have.been.called + }) + + it('withholds a required attestation from a different owner', async () => { + settingsFactory.returns({ + info: { relay_url: relayUrl }, + peering: { + enabled: true, + ownerAttestation: 'required', + scopes: [{ kinds: [1] }], + terms: [], + peers: [{ pubkey, relayUrl, ownerPubkey: getPublicKey('4'.repeat(64)) }], + }, + } as Partial) + const peeringAttestations = { + findByRelayPubkey: Sinon.stub().resolves({ + relayPubkey: pubkey, + ownerPubkey: getPublicKey('5'.repeat(64)), + termsHash: peeringTermsHash([]), + scopes: [{ kinds: [1] }], + }), + } + handler = new AuthMessageHandler(webSocket, settingsFactory, peeringAttestations as any) + const message = await createAuthEvent() + + await handler.handleMessage(message) + + expect(webSocket.setPeerPubkey as Sinon.SinonStub).not.to.have.been.called + }) + + it('grants peer treatment when a required attestation exists', async () => { + settingsFactory.returns({ + info: { relay_url: relayUrl }, + peering: { + enabled: true, + ownerAttestation: 'required', + peers: [{ pubkey, relayUrl }], + }, + } as Partial) + const peeringAttestations = { + findByRelayPubkey: Sinon.stub().resolves({ + relayPubkey: pubkey, + termsHash: peeringTermsHash([]), + scopes: [], + }), + } + handler = new AuthMessageHandler(webSocket, settingsFactory, peeringAttestations as any) + const message = await createAuthEvent() + + await handler.handleMessage(message) + + expect(webSocket.setPeerPubkey as Sinon.SinonStub).to.have.been.calledWith(pubkey) + }) + it('rejects when kind is not 22242', async () => { const message = await createAuthEvent({ kind: 1 }) await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -127,7 +229,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -139,7 +241,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -152,7 +254,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -165,7 +267,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -177,7 +279,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -189,7 +291,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -201,7 +303,7 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).not.to.have.been.called + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).not.to.have.been.called expect(emitStub).to.have.been.calledOnce const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) @@ -213,7 +315,10 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).to.have.been.calledOnceWithExactly(pubkey, message[1].id) + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).to.have.been.calledOnceWithExactly( + pubkey, + message[1].id, + ) const args = emitStub.firstCall.args expect(args[1][2]).to.equal(true) }) @@ -226,7 +331,10 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).to.have.been.calledOnceWithExactly(pubkey, message[1].id) + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).to.have.been.calledOnceWithExactly( + pubkey, + message[1].id, + ) } finally { clock.restore() } @@ -238,7 +346,10 @@ describe('AuthMessageHandler', () => { await handler.handleMessage(message) - expect((webSocket.addAuthenticatedPubkey as Sinon.SinonStub)).to.have.been.calledOnceWithExactly(pubkey, message[1].id) + expect(webSocket.addAuthenticatedPubkey as Sinon.SinonStub).to.have.been.calledOnceWithExactly( + pubkey, + message[1].id, + ) const args = emitStub.firstCall.args expect(args[1][2]).to.equal(false) expect(args[1][3]).to.include('auth event already used') diff --git a/test/unit/handlers/peering-request-event-strategy.spec.ts b/test/unit/handlers/peering-request-event-strategy.spec.ts new file mode 100644 index 000000000..2d68bc9de --- /dev/null +++ b/test/unit/handlers/peering-request-event-strategy.spec.ts @@ -0,0 +1,180 @@ +import chai from 'chai' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import type { IWebSocketAdapter } from '../../../src/@types/adapters' +import type { Settings } from '../../../src/@types/settings' +import { WebSocketAdapterEvent } from '../../../src/constants/adapter' +import { PeeringRequestEventStrategy } from '../../../src/handlers/event-strategies/peering-request-event-strategy' +import { buildPeeringRequestEvent } from '../../../src/utils/peering-attestation' +import { getPublicKey } from '../../../src/utils/event' + +chai.use(sinonChai) +const { expect } = chai + +const ownerKey = '1'.repeat(64) +const receiverKey = '3'.repeat(64) +const relayPubkey = getPublicKey('2'.repeat(64)) +const receiverPubkey = getPublicKey(receiverKey) +const now = new Date('2026-11-23T12:00:00.000Z') + +const settingsFor = (overrides: Partial = {}): Settings => + ({ + info: { relay_url: 'wss://receiver.example.com', self: receiverPubkey }, + peering: { + enabled: true, + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + peers: [{ pubkey: relayPubkey, relayUrl: 'wss://requester.example.com' }], + ownerAttestation: 'preferred', + ...overrides, + }, + }) as Settings + +const requestFor = () => + buildPeeringRequestEvent({ + ownerPrivateKey: ownerKey, + relayPubkey, + relayUrl: 'wss://requester.example.com', + receiverPubkey, + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + createdAt: Math.floor(now.getTime() / 1000), + }) + +describe('PeeringRequestEventStrategy', () => { + let emit: Sinon.SinonStub + let setPeerPubkey: Sinon.SinonStub + let webSocket: IWebSocketAdapter + let attestations: { save: Sinon.SinonStub; findByRelayPubkey: Sinon.SinonStub } + + beforeEach(() => { + emit = Sinon.stub() + setPeerPubkey = Sinon.stub() + webSocket = { + emit, + setPeerPubkey, + getPeerPubkey: Sinon.stub().returns(undefined), + getAuthenticatedPubkeys: Sinon.stub().returns(new Set([relayPubkey])), + } as any as IWebSocketAdapter + attestations = { + save: Sinon.stub().callsFake(async (value) => value), + findByRelayPubkey: Sinon.stub().resolves(undefined), + } + }) + + afterEach(() => Sinon.restore()) + + it('records a valid request and returns a signed acceptance', async () => { + const event = await requestFor() + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => settingsFor(), + attestations, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(attestations.save).to.have.been.calledOnce + expect(setPeerPubkey).to.have.been.calledWith(relayPubkey) + const messages = emit.getCalls().map((call) => call.args[1]) + const ok = messages.find((message) => message[0] === 'OK') + const acceptance = messages.find((message) => message[0] === 'EVENT') + expect(ok?.[2]).to.equal(true) + expect(acceptance?.[2].kind).to.equal(28938) + expect(acceptance?.[2].pubkey).to.equal(receiverPubkey) + expect(emit.firstCall.args[0]).to.equal(WebSocketAdapterEvent.Message) + }) + + it('rejects a request signed by an owner other than the configured one', async () => { + const event = await requestFor() + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => + settingsFor({ + peers: [ + { pubkey: relayPubkey, relayUrl: 'wss://requester.example.com', ownerPubkey: getPublicKey('4'.repeat(64)) }, + ], + }), + attestations, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(attestations.save).not.to.have.been.called + const ok = emit + .getCalls() + .map((call) => call.args[1]) + .find((message) => message[0] === 'OK') + expect(ok?.[2]).to.equal(false) + expect(ok?.[3]).to.include('owner') + }) + + it('rejects a valid request from a relay that is not configured', async () => { + const event = await requestFor() + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => settingsFor({ peers: [] }), + attestations, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(attestations.save).not.to.have.been.called + expect(setPeerPubkey).not.to.have.been.called + const ok = emit + .getCalls() + .map((call) => call.args[1]) + .find((message) => message[0] === 'OK') + expect(ok?.[2]).to.equal(false) + expect(ok?.[3]).to.include('configured') + }) + + it('rejects a request whose terms no longer match the advertisement', async () => { + const event = await requestFor() + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => settingsFor({ terms: [{ amount: 22000, unit: 'msats', period: 2592000 }] }), + attestations, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(attestations.save).not.to.have.been.called + expect(setPeerPubkey).not.to.have.been.called + const ok = emit + .getCalls() + .map((call) => call.args[1]) + .find((message) => message[0] === 'OK') + expect(ok?.[2]).to.equal(false) + expect(ok?.[3]).to.include('terms changed') + }) + + it('rejects when peering is disabled', async () => { + const event = await requestFor() + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => settingsFor({ enabled: false }), + attestations, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(attestations.save).not.to.have.been.called + const ok = emit + .getCalls() + .map((call) => call.args[1]) + .find((message) => message[0] === 'OK') + expect(ok?.[3]).to.include('peering is not enabled') + }) +}) diff --git a/test/unit/repositories/peering-attestation-repository.spec.ts b/test/unit/repositories/peering-attestation-repository.spec.ts new file mode 100644 index 000000000..cdd13eedd --- /dev/null +++ b/test/unit/repositories/peering-attestation-repository.spec.ts @@ -0,0 +1,65 @@ +import { expect } from 'chai' + +import { PeeringAttestationRepository } from '../../../src/repositories/peering-attestation-repository' +import { createRecordingKnex } from './recording-knex' + +const peerPubkey = 'a'.repeat(64) +const ownerPubkey = 'b'.repeat(64) +const now = new Date('2026-11-23T12:00:00.000Z') + +const row = { + relay_pubkey: Buffer.from(peerPubkey, 'hex'), + owner_pubkey: Buffer.from(ownerPubkey, 'hex'), + relay_url: 'wss://peer.example.com', + request_event_id: 'c'.repeat(64), + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + terms_hash: 'd'.repeat(64), + pow_difficulty: 12, + accepted_at: now, + created_at: now, + updated_at: now, +} + +const attestation = { + relayPubkey: peerPubkey, + ownerPubkey, + relayUrl: 'wss://peer.example.com', + requestEventId: 'c'.repeat(64), + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + termsHash: 'd'.repeat(64), + powDifficulty: 12, + acceptedAt: now, + createdAt: now, + updatedAt: now, +} + +describe('PeeringAttestationRepository', () => { + it('maps a stored attestation back to the domain shape', async () => { + const recording = createRecordingKnex() + const repository = new PeeringAttestationRepository(recording.db) + recording.respondWith([row]) + + const result = await repository.findByRelayPubkey(peerPubkey) + + expect(result).to.deep.equal({ + ...attestation, + scopes: [{ kinds: [1] }], + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + }) + }) + + it('upserts the latest accepted request for a relay', async () => { + const recording = createRecordingKnex() + const repository = new PeeringAttestationRepository(recording.db) + recording.respondWith([row]) + + const result = await repository.save(attestation) + + expect(recording.queries[0].sql).to.include('insert into "peering_attestations"') + expect(recording.queries[0].sql).to.include('on conflict') + expect(result.relayPubkey).to.equal(peerPubkey) + expect(result.powDifficulty).to.equal(12) + }) +}) diff --git a/test/unit/utils/peering-advertisement.spec.ts b/test/unit/utils/peering-advertisement.spec.ts index bb7ca47e0..e2e29d939 100644 --- a/test/unit/utils/peering-advertisement.spec.ts +++ b/test/unit/utils/peering-advertisement.spec.ts @@ -29,6 +29,21 @@ describe('peering advertisement', () => { }) }) + it('reads owner attestation and request proof-of-work', () => { + const advertisement = parsePeeringAdvertisement({ + peering: { + enabled: true, + owner_attestation: 'required', + min_pow_difficulty: 12, + scopes: [{ kinds: [1] }], + terms: [], + }, + }) + + expect(advertisement.ownerAttestation).to.equal('required') + expect(advertisement.minPowDifficulty).to.equal(12) + }) + it('reports peering as disabled when the section is absent', () => { const advertisement = parsePeeringAdvertisement({ supported_nips: [1] }) diff --git a/test/unit/utils/peering-attestation.spec.ts b/test/unit/utils/peering-attestation.spec.ts new file mode 100644 index 000000000..31ec5b582 --- /dev/null +++ b/test/unit/utils/peering-attestation.spec.ts @@ -0,0 +1,189 @@ +import { expect } from 'chai' + +import type { PeeringScope, PeeringTerm } from '../../../src/@types/settings' +import { getPublicKey } from '../../../src/utils/event' +import { + buildPeeringAcceptanceEvent, + buildPeeringRequestEvent, + peeringTermsHash, + samePeeringScopes, + samePeeringTerms, + verifyPeeringAcceptanceEvent, + verifyPeeringRequestEvent, +} from '../../../src/utils/peering-attestation' + +const ownerKey = '1'.repeat(64) +const relayKey = '2'.repeat(64) +const receiverKey = '3'.repeat(64) +const relayPubkey = getPublicKey(relayKey) +const receiverPubkey = getPublicKey(receiverKey) +const now = new Date('2026-11-23T12:00:00.000Z') +const createdAt = Math.floor(now.getTime() / 1000) + +const scopes: PeeringScope[] = [{ kinds: [1, [10000, 19999]] }] +const terms: PeeringTerm[] = [{ amount: 21000, unit: 'msats', period: 2592000 }] + +const buildRequest = (overrides: Partial[0]> = {}) => + buildPeeringRequestEvent({ + ownerPrivateKey: ownerKey, + relayPubkey, + relayUrl: 'wss://requester.example.com', + receiverPubkey, + scopes, + terms, + createdAt, + ...overrides, + }) + +const verifyOptions = (overrides: Partial[1]> = {}) => ({ + authenticatedPubkeys: [relayPubkey], + receiverPubkey, + offeredScopes: scopes, + offeredTerms: terms, + now, + ...overrides, +}) + +describe('peering attestation', () => { + it('verifies an owner-signed request against the AUTH identity and advertised terms', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent(event, verifyOptions()) + + expect(result.ok).to.equal(true) + if (result.ok) { + expect(result.request.relay_pubkey).to.equal(relayPubkey) + expect(result.request.terms_hash).to.equal(peeringTermsHash(terms)) + expect(result.powDifficulty).to.be.greaterThanOrEqual(0) + } + }) + + it('rejects a request signed by an owner other than the configured one', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent( + event, + verifyOptions({ expectedOwnerPubkey: getPublicKey('4'.repeat(64)) }), + ) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('owner') + } + }) + + it('rejects a request whose relay key did not authenticate on the connection', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent( + event, + verifyOptions({ authenticatedPubkeys: [getPublicKey('4'.repeat(64))] }), + ) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('not authenticated') + } + }) + + it('rejects a request built against changed terms', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent( + event, + verifyOptions({ offeredTerms: [{ amount: 22000, unit: 'msats', period: 2592000 }] }), + ) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('terms changed') + } + }) + + it('rejects a scope the relay does not offer', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent(event, verifyOptions({ offeredScopes: [{ kinds: [7] }] })) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('scope') + } + }) + + it('rejects a stale request', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent( + event, + verifyOptions({ now: new Date(now.getTime() + 11 * 60 * 1000) }), + ) + + expect(result).to.include({ ok: false }) + }) + + it('requires the advertised proof-of-work from unconfigured peers', async () => { + const event = await buildRequest() + const options = verifyOptions({ minPowDifficulty: 8 }) + + const result = await verifyPeeringRequestEvent(event, options) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('pow:') + } + }) + + it('waives proof-of-work for configured peers by default', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent( + event, + verifyOptions({ minPowDifficulty: 8, isConfiguredPeer: true }), + ) + + expect(result.ok).to.equal(true) + }) + + it('accepts a correctly ground request', async () => { + const event = await buildRequest({ powDifficulty: 4 }) + + const result = await verifyPeeringRequestEvent(event, verifyOptions({ minPowDifficulty: 4 })) + + expect(result.ok).to.equal(true) + }) + + it('produces a relay-signed acceptance for the exact request', async () => { + const request = await buildRequest() + const requestPayload = await verifyPeeringRequestEvent(request, verifyOptions()) + expect(requestPayload.ok).to.equal(true) + if (!requestPayload.ok) { + return + } + + const acceptance = await buildPeeringAcceptanceEvent({ + request, + acceptance: requestPayload.request, + relayPrivateKey: receiverKey, + relayUrl: 'wss://receiver.example.com', + createdAt, + }) + const verified = await verifyPeeringAcceptanceEvent(acceptance, request) + + expect(acceptance.pubkey).to.equal(receiverPubkey) + expect(verified.ok).to.equal(true) + if (verified.ok) { + expect(verified.acceptance.request_id).to.equal(request.id) + expect(verified.acceptance.terms_hash).to.equal(peeringTermsHash(terms)) + } + }) + + it('treats term and scope order as insignificant', () => { + const reversedTerms = [...terms].reverse() + const scopesA: PeeringScope[] = [{ kinds: [[10000, 19999], 1] }] + const scopesB: PeeringScope[] = [{ kinds: [1, [10000, 19999]] }] + + expect(samePeeringTerms(terms, reversedTerms)).to.equal(true) + expect(samePeeringScopes(scopesA, scopesB)).to.equal(true) + }) +}) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index b94deab3f..2afe73643 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -382,6 +382,33 @@ describe('settings-config', () => { expect(issues.some((issue) => issue.path === 'peering.minRequestPowDifficulty')).to.equal(true) }) + it('rejects an unknown owner attestation policy', () => { + const issues = peeringIssues({ ...settlementFreePeering, ownerAttestation: 'sometimes' }) + + expect(issues.some((issue) => issue.path === 'peering.ownerAttestation')).to.equal(true) + }) + + it('rejects a non-boolean configured-peer PoW waiver', () => { + const issues = peeringIssues({ ...settlementFreePeering, waiveRequestPowForConfiguredPeers: 'yes' }) + + expect(issues.some((issue) => issue.path === 'peering.waiveRequestPowForConfiguredPeers')).to.equal(true) + }) + + it('validates an optional peer owner pubkey', () => { + expect( + peeringIssues({ + ...settlementFreePeering, + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com', ownerPubkey: 'b'.repeat(64) }], + }), + ).to.deep.equal([]) + + const issues = peeringIssues({ + ...settlementFreePeering, + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com', ownerPubkey: 'nope' }], + }) + expect(issues.some((issue) => issue.path === 'peering.peers[0].ownerPubkey')).to.equal(true) + }) + it('accepts configured peers by hex or npub', () => { expect( peeringIssues({ From 38ebff9fc9e48f37871aa4157b451d6e4dbcb146 Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Mon, 23 Nov 2026 19:55:24 +0530 Subject: [PATCH 2/3] fix(peering): harden owner attestation and CLI failure paths - derive relay keys with the relay URL in the CLI and request strategy\n- normalize configured owner pins, relay URLs and singleton kind ranges\n- keep positive CLI acknowledgements through short timeouts, closes and errors\n- emit machine-readable JSON for explicit CLI rejections\n- withdraw peer identity when a required agreement stops matching\n- exclude peering requests from adaptive PoW and fix the integration fixture --- src/@types/adapters.ts | 5 +- src/@types/peering.ts | 3 + src/adapters/web-socket-adapter.ts | 42 +++- src/cli/commands/peering.ts | 51 ++++- src/handlers/auth-message-handler.ts | 24 ++- src/handlers/event-message-handler.ts | 2 +- .../peering-request-event-strategy.ts | 10 +- src/utils/peering-attestation.ts | 36 +++- .../peering-owner-attestation.feature.ts | 2 + test/unit/adapters/web-socket-adapter.spec.ts | 57 +++++- test/unit/cli/peering.spec.ts | 191 ++++++++++++++++++ .../handlers/auth-message-handler.spec.ts | 1 + .../peering-request-event-strategy.spec.ts | 56 +++++ test/unit/utils/peering-attestation.spec.ts | 176 +++++++++++++++- 14 files changed, 611 insertions(+), 45 deletions(-) diff --git a/src/@types/adapters.ts b/src/@types/adapters.ts index e8dc537cc..c1b3da64f 100644 --- a/src/@types/adapters.ts +++ b/src/@types/adapters.ts @@ -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 { @@ -28,7 +29,9 @@ 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. */ + clearPeerPubkey(): 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 diff --git a/src/@types/peering.ts b/src/@types/peering.ts index bc5d98fcd..38ecd6919 100644 --- a/src/@types/peering.ts +++ b/src/@types/peering.ts @@ -35,6 +35,9 @@ export interface PeeringAcceptancePayload { accepted_at: number } +/** The agreement a required-policy socket must still match. */ +export type PeeringAttestationAgreement = Pick + /** The latest accepted owner attestation for one relay key. */ export interface PeeringAttestation { relayPubkey: Pubkey diff --git a/src/adapters/web-socket-adapter.ts b/src/adapters/web-socket-adapter.ts index 767519e38..421e14498 100644 --- a/src/adapters/web-socket-adapter.ts +++ b/src/adapters/web-socket-adapter.ts @@ -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' @@ -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' @@ -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 @@ -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', ), ) } @@ -379,20 +381,44 @@ 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 configuredOwner = parsePeeringPeerPubkey(findConfiguredPeeringPeer(settings, this.peerPubkey)?.ownerPubkey) + const agreement = this.peerAgreement + const currentTerms = settings.peering?.terms ?? [] + const currentScopes = settings.peering?.scopes ?? [] + if ( + !agreement || + agreement.termsHash?.toLowerCase() !== peeringTermsHash(currentTerms) || + !samePeeringScopes(agreement.scopes, currentScopes) || + (configuredOwner !== undefined && agreement.ownerPubkey.toLowerCase() !== configuredOwner) + ) { + 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(): void { + this.peerPubkey = undefined + this.peerAgreement = undefined } private async onClientMessage(raw: Buffer) { diff --git a/src/cli/commands/peering.ts b/src/cli/commands/peering.ts index ffe4897cc..053c3534f 100644 --- a/src/cli/commands/peering.ts +++ b/src/cli/commands/peering.ts @@ -27,6 +27,7 @@ export const sendPeeringRequest = ( ): Promise => new Promise((resolve) => { let settled = false + let acknowledged = false let acceptance: Event | undefined let finishTimer: NodeJS.Timeout | undefined @@ -41,6 +42,7 @@ export const sendPeeringRequest = ( clearTimeout(timer) socket.off('message', onMessage) socket.off('close', onClose) + socket.off('error', onError) resolve(reply) } @@ -52,6 +54,15 @@ export const sendPeeringRequest = ( : {}), }) + const succeedOrWait = (): void => { + if (acceptance) { + finish(accept()) + return + } + // The acceptance may follow the OK; give the relay one frame of grace. + finishTimer = setTimeout(() => finish(accept()), 500) + } + const onMessage = (data: RawData): void => { let message: unknown try { @@ -68,8 +79,8 @@ export const sendPeeringRequest = ( finish({ ok: false, message: typeof message[3] === 'string' ? message[3] : 'request rejected' }) return } - // The acceptance may follow the OK; give the relay one frame of grace. - finishTimer = setTimeout(() => finish(accept()), 500) + acknowledged = true + succeedOrWait() return } @@ -77,15 +88,27 @@ export const sendPeeringRequest = ( const event = message[2] as Event if (event.kind === 28938) { acceptance = event + if (acknowledged) { + finish(accept()) + } } } } - const onClose = (): void => finish({ ok: false, message: 'connection closed before the reply' }) - const timer = setTimeout(() => finish({ ok: false, message: 'timed out waiting for the peer' }), timeoutMs) + const onClose = (): void => + finish(acknowledged ? accept() : { ok: false, message: 'connection closed before the reply' }) + const onError = (error: Error): void => + finish( + acknowledged ? accept() : { ok: false, message: error instanceof Error ? error.message : 'connection failed' }, + ) + const timer = setTimeout( + () => finish(acknowledged ? accept() : { ok: false, message: 'timed out waiting for the peer' }), + timeoutMs, + ) socket.on('message', onMessage) socket.on('close', onClose) + socket.on('error', onError) socket.send(JSON.stringify(['EVENT', request])) }) @@ -124,7 +147,6 @@ export const runPeeringRequest = async ( const loadSettings = dependencies.loadSettings ?? loadMergedSettings const fetchAdvertisement = dependencies.fetchAdvertisement ?? fetchPeeringAdvertisement const authenticate = dependencies.authenticate ?? authenticateToPeeringRelay - const relayPrivateKey = dependencies.relayPrivateKey ?? (() => getRelayPrivateKey()) const send = dependencies.send ?? sendPeeringRequest const ownerKey = options.ownerKey ?? process.env.PEERING_OWNER_PRIVATE_KEY @@ -136,6 +158,7 @@ export const runPeeringRequest = async ( if (!settings.info?.relay_url) { throw new Error('info.relay_url is required to identify this relay') } + const relayPrivateKey = dependencies.relayPrivateKey ?? (() => getRelayPrivateKey(settings.info.relay_url)) const advertisement: PeeringAdvertisement = await fetchAdvertisement(options.relayUrl) if (!advertisement.enabled) { @@ -174,20 +197,26 @@ export const runPeeringRequest = async ( } } - if (!reply.ok) { - logError(`peer rejected the peering request: ${reply.message}`) + const fail = (message: string): number => { + if (options.json) { + process.stderr.write(`${JSON.stringify({ error: { message, code: 1 } })}\n`) + } else { + logError(message) + } return 1 } + if (!reply.ok) { + return fail(`peer rejected the peering request: ${reply.message}`) + } + if (reply.acceptance) { const verified = await verifyPeeringAcceptanceEvent(reply.acceptance.event, request) if (verified.ok === false) { - logError(`peer returned an invalid acceptance: ${verified.reason}`) - return 1 + return fail(`peer returned an invalid acceptance: ${verified.reason}`) } if (reply.acceptance.event.pubkey.toLowerCase() !== advertisement.self.toLowerCase()) { - logError('peer returned an acceptance signed by a different relay key') - return 1 + return fail('peer returned an acceptance signed by a different relay key') } } diff --git a/src/handlers/auth-message-handler.ts b/src/handlers/auth-message-handler.ts index 29e207525..25179e170 100644 --- a/src/handlers/auth-message-handler.ts +++ b/src/handlers/auth-message-handler.ts @@ -8,7 +8,7 @@ import { IWebSocketAdapter } from '../@types/adapters' import type { IPeeringAttestationRepository } from '../@types/repositories' import { Settings } from '../@types/settings' import { WebSocketAdapterEvent } from '../constants/adapter' -import { findConfiguredPeeringPeer, isConfiguredPeeringPeer } from '../utils/peering-auth' +import { findConfiguredPeeringPeer, isConfiguredPeeringPeer, parsePeeringPeerPubkey } from '../utils/peering-auth' import { peeringTermsHash, samePeeringScopes } from '../utils/peering-attestation' const logger = createLogger('auth-message-handler') @@ -88,8 +88,15 @@ export class AuthMessageHandler implements IMessageHandler { return } + const withhold = (): void => { + // A re-AUTH must not leave an earlier peer identity alive after the + // agreement stops matching. + this.webSocket.clearPeerPubkey() + } + if (!this.peeringAttestations) { logger('peer %s authenticated but no attestation store is available', pubkey) + withhold() return } @@ -100,26 +107,35 @@ export class AuthMessageHandler implements IMessageHandler { // a fresh owner signature before peer treatment resumes. const currentTerms = this.settings().peering?.terms ?? [] const currentScopes = this.settings().peering?.scopes ?? [] - const configuredOwner = findConfiguredPeeringPeer(this.settings(), pubkey)?.ownerPubkey + const configuredOwnerRaw = findConfiguredPeeringPeer(this.settings(), pubkey)?.ownerPubkey + const configuredOwner = configuredOwnerRaw ? parsePeeringPeerPubkey(configuredOwnerRaw) : undefined const ownerMatches = - !configuredOwner || attestation.ownerPubkey?.toLowerCase() === configuredOwner.toLowerCase() + !configuredOwnerRaw || + (configuredOwner !== undefined && attestation.ownerPubkey?.toLowerCase() === configuredOwner) if ( ownerMatches && attestation.termsHash?.toLowerCase() === peeringTermsHash(currentTerms) && samePeeringScopes(attestation.scopes ?? [], currentScopes) ) { - this.webSocket.setPeerPubkey(pubkey) + this.webSocket.setPeerPubkey(pubkey, { + termsHash: attestation.termsHash, + scopes: attestation.scopes ?? [], + ownerPubkey: attestation.ownerPubkey, + }) return } logger('peer %s attestation no longer matches the advertised terms or scopes', pubkey) + withhold() return } } catch (error) { logger('unable to read peering attestation for %s: %o', pubkey, error) + withhold() return } logger('peer %s authenticated but has no accepted owner attestation', pubkey) + withhold() } private sendResult(eventId: string, success: boolean, message: string): void { diff --git a/src/handlers/event-message-handler.ts b/src/handlers/event-message-handler.ts index 70d2957a4..a2a8b704a 100644 --- a/src/handlers/event-message-handler.ts +++ b/src/handlers/event-message-handler.ts @@ -191,7 +191,7 @@ export class EventMessageHandler implements IMessageHandler { // any real work. Note: a duplicate/no-op write still counts here, since // dedup is decided later inside the event strategy's own execute(). const powSettings = this.settings().limits?.event?.pow - if (powSettings?.enabled) { + if (powSettings?.enabled && event.kind !== EventKinds.PEERING_REQUEST) { recordAdaptivePowEvent(powSettings.periodMs) } diff --git a/src/handlers/event-strategies/peering-request-event-strategy.ts b/src/handlers/event-strategies/peering-request-event-strategy.ts index 687ba3764..4f10ff8b2 100644 --- a/src/handlers/event-strategies/peering-request-event-strategy.ts +++ b/src/handlers/event-strategies/peering-request-event-strategy.ts @@ -30,7 +30,7 @@ export class PeeringRequestEventStrategy implements IEventStrategy Settings, private readonly attestations?: IPeeringAttestationRepository, private readonly now: () => Date = () => new Date(), - private readonly relayPrivateKey: () => string = () => getRelayPrivateKey(), + private readonly relayPrivateKey?: () => string, ) {} public async execute(event: Event): Promise { @@ -55,7 +55,7 @@ export class PeeringRequestEventStrategy implements IEventStrategy (Array.isArray(kind) ? kind[0] : kind) const kindEnd = (kind: number | [number, number]): number => (Array.isArray(kind) ? kind[1] : kind) -const canonicalKind = (kind: number | [number, number]): number | [number, number] => - Array.isArray(kind) ? [kind[0], kind[1]] : kind +const canonicalKind = (kind: number | [number, number]): number | [number, number] => { + if (!Array.isArray(kind)) { + return kind + } + + return kind[0] === kind[1] ? kind[0] : [kind[0], kind[1]] +} + +/** Relay URLs are accepted as http(s) in settings but peering payloads use ws(s). */ +export const normalizePeeringRelayUrl = (value: string): string => { + const trimmed = value.trim() + if (/^https:\/\//i.test(trimmed)) { + return `wss://${trimmed.slice('https://'.length)}` + } + if (/^http:\/\//i.test(trimmed)) { + return `ws://${trimmed.slice('http://'.length)}` + } + return trimmed +} /** Stable terms shape used for hashing and equality checks. */ export const canonicalPeeringTerms = (terms: PeeringTerm[]): PeeringTerm[] => @@ -171,7 +189,7 @@ export const buildPeeringRequestEvent = async (options: BuildPeeringRequestOptio const payload: PeeringRequestPayload = { relay_pubkey: relayPubkey, - relay_url: options.relayUrl, + relay_url: normalizePeeringRelayUrl(options.relayUrl), scopes: canonicalPeeringScopes(options.scopes), terms: canonicalPeeringTerms(options.terms), terms_hash: peeringTermsHash(options.terms), @@ -257,8 +275,14 @@ export const verifyPeeringRequestEvent = async ( return { ok: false, reason: 'auth-required: peering request relay key is not authenticated' } } - if (options.expectedOwnerPubkey && event.pubkey.toLowerCase() !== options.expectedOwnerPubkey.toLowerCase()) { - return { ok: false, reason: 'invalid: request owner does not match the configured owner' } + if (options.expectedOwnerPubkey) { + const expectedOwner = parsePeeringPeerPubkey(options.expectedOwnerPubkey) + if (!expectedOwner) { + return { ok: false, reason: 'invalid: configured owner pubkey is malformed' } + } + if (event.pubkey.toLowerCase() !== expectedOwner) { + return { ok: false, reason: 'invalid: request owner does not match the configured owner' } + } } const target = event.tags.find( @@ -307,7 +331,7 @@ export const buildPeeringAcceptanceEvent = async (options: BuildPeeringAcceptanc const payload: PeeringAcceptancePayload = { request_id: options.request.id, relay_pubkey: relayPubkey, - relay_url: options.relayUrl, + relay_url: normalizePeeringRelayUrl(options.relayUrl), terms_hash: options.acceptance.terms_hash, accepted_at: options.createdAt ?? Math.floor(Date.now() / 1000), } diff --git a/test/integration/features/peering/peering-owner-attestation.feature.ts b/test/integration/features/peering/peering-owner-attestation.feature.ts index be8646b4c..a74ae4e76 100644 --- a/test/integration/features/peering/peering-owner-attestation.feature.ts +++ b/test/integration/features/peering/peering-owner-attestation.feature.ts @@ -45,6 +45,8 @@ const adapterFor = (authenticated: string[] = []) => { const adapter = { emit, setPeerPubkey, + clearPeerPubkey: Sinon.stub(), + getClientId: Sinon.stub().returns('peering-attestation-client'), getPeerPubkey: Sinon.stub().returns(undefined), getAuthenticatedPubkeys: Sinon.stub().returns(new Set(authenticated)), getChallenge: Sinon.stub().returns(challenge), diff --git a/test/unit/adapters/web-socket-adapter.spec.ts b/test/unit/adapters/web-socket-adapter.spec.ts index b0dd8def4..9a93a43ca 100644 --- a/test/unit/adapters/web-socket-adapter.spec.ts +++ b/test/unit/adapters/web-socket-adapter.spec.ts @@ -15,6 +15,7 @@ import { WebSocketAdapter } from '../../../src/adapters/web-socket-adapter' import { WebSocketAdapterEvent, WebSocketServerAdapterEvent } from '../../../src/constants/adapter' import { markActionableTarget, resetHiddenContentCache } from '../../../src/utils/hidden-content-cache' import { Negentropy, NegentropyStorageVector } from '../../../src/utils/negentropy' +import { peeringTermsHash } from '../../../src/utils/peering-attestation' describe('WebSocketAdapter', () => { let sandbox: Sinon.SinonSandbox @@ -204,11 +205,7 @@ describe('WebSocketAdapter', () => { it('closes the subscription when paid access ends', async () => { adapter.onSubscribed('sub-1', [{ kinds: [1] }]) - adapter.setSubscriptionExpiry( - 'sub-1', - new Date('2026-11-09T12:00:01.000Z'), - sandbox.stub().resolves(undefined), - ) + adapter.setSubscriptionExpiry('sub-1', new Date('2026-11-09T12:00:01.000Z'), sandbox.stub().resolves(undefined)) await clock.tickAsync(1000) @@ -237,11 +234,7 @@ describe('WebSocketAdapter', () => { it('keeps the subscription open when access becomes free', async () => { adapter.onSubscribed('sub-1', [{ kinds: [1] }]) - adapter.setSubscriptionExpiry( - 'sub-1', - new Date('2026-11-09T12:00:01.000Z'), - sandbox.stub().resolves(null), - ) + adapter.setSubscriptionExpiry('sub-1', new Date('2026-11-09T12:00:01.000Z'), sandbox.stub().resolves(null)) await clock.tickAsync(1000) @@ -1239,6 +1232,50 @@ describe('WebSocketAdapter', () => { expect(adapter.getPeerPubkey()).to.equal(undefined) }) + it('rechecks a required owner agreement against live settings', () => { + const pubkey = 'a'.repeat(64) + const terms = [{ amount: 21000, unit: 'msats', period: 2592000 }] + const scopes = [{ kinds: [1] }] + const settings = { + peering: { + enabled: true, + ownerAttestation: 'required' as const, + peers: [{ pubkey, relayUrl: 'wss://peer.example.com' }], + terms, + scopes, + }, + } + settingsFactory.returns(settings) + + adapter.addAuthenticatedPubkey(pubkey, '1'.repeat(64)) + adapter.setPeerPubkey(pubkey, { + termsHash: peeringTermsHash(terms), + scopes, + ownerPubkey: 'b'.repeat(64), + }) + expect(adapter.getPeerPubkey()).to.equal(pubkey) + + settingsFactory.returns({ + ...settings, + peering: { ...settings.peering, terms: [{ amount: 22000, unit: 'msats', period: 2592000 }] }, + }) + expect(adapter.getPeerPubkey()).to.equal(undefined) + }) + + it('clears peer status explicitly', () => { + const pubkey = 'a'.repeat(64) + settingsFactory.returns({ + peering: { enabled: true, peers: [{ pubkey, relayUrl: 'wss://peer.example.com' }] }, + }) + + adapter.addAuthenticatedPubkey(pubkey, '1'.repeat(64)) + adapter.setPeerPubkey(pubkey) + expect(adapter.getPeerPubkey()).to.equal(pubkey) + + adapter.clearPeerPubkey() + expect(adapter.getPeerPubkey()).to.equal(undefined) + }) + it('expires authenticated pubkeys after sessionExpirySeconds', () => { const clock = sandbox.useFakeTimers({ now: 1_700_000_000_000 }) settingsFactory.returns({ nip42: { sessionExpirySeconds: 60 } }) diff --git a/test/unit/cli/peering.spec.ts b/test/unit/cli/peering.spec.ts index 66bd3617c..d82423370 100644 --- a/test/unit/cli/peering.spec.ts +++ b/test/unit/cli/peering.spec.ts @@ -6,6 +6,7 @@ import sinonChai from 'sinon-chai' import type { Event } from '../../../src/@types/event' import { runPeeringRequest, sendPeeringRequest } from '../../../src/cli/commands/peering' import { getPublicKey, identifyEvent, signEvent } from '../../../src/utils/event' +import { buildPeeringAcceptanceEvent } from '../../../src/utils/peering-attestation' chai.use(sinonChai) const { expect } = chai @@ -77,6 +78,51 @@ describe('peering CLI', () => { expect(reply.acceptance?.event.id).to.equal(acceptance.id) }) + it('keeps success when the acceptance and OK arrive before a short timeout', async () => { + const request = await requestEvent() + const acceptance = await acceptanceEvent(request) + const socket = new FakeSocket() + socket.send = (message: string) => { + socket.sent.push(message) + socket.emit('message', Buffer.from(JSON.stringify(['EVENT', 'peering-acceptance', acceptance]))) + socket.emit('message', Buffer.from(JSON.stringify(['OK', request.id, true, '']))) + } + + const reply = await sendPeeringRequest(socket as any, request, 100) + + expect(reply.ok).to.equal(true) + expect(reply.acceptance?.event.id).to.equal(acceptance.id) + }) + + it('keeps a positive acknowledgement when the socket closes', async () => { + const request = await requestEvent() + const socket = new FakeSocket() + socket.send = (message: string) => { + socket.sent.push(message) + socket.emit('message', Buffer.from(JSON.stringify(['OK', request.id, true, '']))) + socket.emit('close') + } + + const reply = await sendPeeringRequest(socket as any, request, 1_000) + + expect(reply.ok).to.equal(true) + expect(reply.acceptance).to.equal(undefined) + }) + + it('settles a positive acknowledgement on a socket error', async () => { + const request = await requestEvent() + const socket = new FakeSocket() + socket.send = (message: string) => { + socket.sent.push(message) + socket.emit('message', Buffer.from(JSON.stringify(['OK', request.id, true, '']))) + socket.emit('error', new Error('broken pipe')) + } + + const reply = await sendPeeringRequest(socket as any, request, 1_000) + + expect(reply.ok).to.equal(true) + }) + it('returns the peer rejection reason', async () => { const request = await requestEvent() const socket = new FakeSocket() @@ -127,6 +173,151 @@ describe('peering CLI', () => { expect(log).to.have.been.called }) + it('fails when the peer does not advertise peering', async () => { + let error: unknown + try { + await runPeeringRequest( + { relayUrl: 'wss://peer.example.com', ownerKey }, + { + loadSettings: () => ({ info: { relay_url: 'wss://me.example.com' } }) as any, + fetchAdvertisement: async () => ({ + enabled: false, + self: receiverPubkey, + scopes: [], + terms: [], + supportedNips: [], + }), + relayPrivateKey: () => relayKey, + }, + ) + } catch (caught) { + error = caught + } + + expect((error as Error).message).to.include('does not advertise peering') + }) + + it('fails when the peer does not advertise its relay key', async () => { + let error: unknown + try { + await runPeeringRequest( + { relayUrl: 'wss://peer.example.com', ownerKey }, + { + loadSettings: () => ({ info: { relay_url: 'wss://me.example.com' } }) as any, + fetchAdvertisement: async () => ({ enabled: true, scopes, terms, supportedNips: [] }), + relayPrivateKey: () => relayKey, + }, + ) + } catch (caught) { + error = caught + } + + expect((error as Error).message).to.include('relay pubkey') + }) + + it('rejects an invalid acceptance with --json', async () => { + const socket = new FakeSocket() + const stderr = Sinon.stub(process.stderr, 'write') + + const code = await runPeeringRequest( + { relayUrl: 'wss://peer.example.com', ownerKey, json: true }, + { + loadSettings: () => ({ info: { relay_url: 'wss://me.example.com' } }) as any, + fetchAdvertisement: async () => ({ + enabled: true, + self: receiverPubkey, + scopes, + terms, + supportedNips: [77], + }), + authenticate: async () => ({ socket: socket as any, challenge: 'c', authEvent: {} as any }), + relayPrivateKey: () => relayKey, + send: async () => ({ + ok: true, + message: 'accepted', + acceptance: { event: await requestEvent(), acceptance: {} as any }, + }), + }, + ) + + expect(code).to.equal(1) + expect(JSON.parse(String(stderr.firstCall.args[0])).error.message).to.include('invalid acceptance') + }) + + it('rejects an acceptance signed by a different relay key', async () => { + const socket = new FakeSocket() + const stderr = Sinon.stub(process.stderr, 'write') + + const code = await runPeeringRequest( + { relayUrl: 'wss://peer.example.com', ownerKey, json: true }, + { + loadSettings: () => ({ info: { relay_url: 'wss://me.example.com' } }) as any, + fetchAdvertisement: async () => ({ + enabled: true, + self: receiverPubkey, + scopes, + terms, + supportedNips: [77], + }), + authenticate: async () => ({ socket: socket as any, challenge: 'c', authEvent: {} as any }), + relayPrivateKey: () => relayKey, + send: async (_socket, request) => ({ + ok: true, + message: 'accepted', + acceptance: { + event: await buildPeeringAcceptanceEvent({ + request, + acceptance: JSON.parse(request.content), + relayPrivateKey: relayKey, + relayUrl: 'wss://receiver.example.com', + }), + acceptance: JSON.parse(request.content), + }, + }), + }, + ) + + expect(code).to.equal(1) + expect(JSON.parse(String(stderr.firstCall.args[0])).error.message).to.include('different relay key') + }) + + it('times out when the peer never answers', async () => { + const request = await requestEvent() + const socket = new FakeSocket() + socket.send = (message: string) => socket.sent.push(message) + + const reply = await sendPeeringRequest(socket as any, request, 20) + + expect(reply).to.include({ ok: false }) + }) + + it('prints a machine-readable rejection with --json', async () => { + const socket = new FakeSocket() + const stderr = Sinon.stub(process.stderr, 'write') + + const code = await runPeeringRequest( + { relayUrl: 'wss://peer.example.com', ownerKey, json: true }, + { + loadSettings: () => ({ info: { relay_url: 'wss://me.example.com' } }) as any, + fetchAdvertisement: async () => ({ + enabled: true, + self: receiverPubkey, + scopes, + terms, + supportedNips: [77], + }), + authenticate: async () => ({ socket: socket as any, challenge: 'c', authEvent: {} as any }), + relayPrivateKey: () => relayKey, + send: async () => ({ ok: false, message: 'restricted: not configured' }), + }, + ) + + expect(code).to.equal(1) + expect(JSON.parse(String(stderr.firstCall.args[0]))).to.deep.equal({ + error: { message: 'peer rejected the peering request: restricted: not configured', code: 1 }, + }) + }) + it('requires an owner key', async () => { const previous = process.env.PEERING_OWNER_PRIVATE_KEY delete process.env.PEERING_OWNER_PRIVATE_KEY diff --git a/test/unit/handlers/auth-message-handler.spec.ts b/test/unit/handlers/auth-message-handler.spec.ts index a7a1b2c73..db5dda7a2 100644 --- a/test/unit/handlers/auth-message-handler.spec.ts +++ b/test/unit/handlers/auth-message-handler.spec.ts @@ -84,6 +84,7 @@ describe('AuthMessageHandler', () => { addAuthenticatedPubkey: Sinon.stub().returns(true), getPeerPubkey: Sinon.stub().returns(undefined), setPeerPubkey: Sinon.stub(), + clearPeerPubkey: Sinon.stub(), } as any as IWebSocketAdapter settingsFactory = Sinon.stub().returns({ diff --git a/test/unit/handlers/peering-request-event-strategy.spec.ts b/test/unit/handlers/peering-request-event-strategy.spec.ts index 2d68bc9de..3d47c1900 100644 --- a/test/unit/handlers/peering-request-event-strategy.spec.ts +++ b/test/unit/handlers/peering-request-event-strategy.spec.ts @@ -5,6 +5,7 @@ import sinonChai from 'sinon-chai' import type { IWebSocketAdapter } from '../../../src/@types/adapters' import type { Settings } from '../../../src/@types/settings' import { WebSocketAdapterEvent } from '../../../src/constants/adapter' +import { PeeringAcceptanceEventStrategy } from '../../../src/handlers/event-strategies/peering-acceptance-event-strategy' import { PeeringRequestEventStrategy } from '../../../src/handlers/event-strategies/peering-request-event-strategy' import { buildPeeringRequestEvent } from '../../../src/utils/peering-attestation' import { getPublicKey } from '../../../src/utils/event' @@ -114,6 +115,47 @@ describe('PeeringRequestEventStrategy', () => { expect(ok?.[3]).to.include('owner') }) + it('rejects when the attestation store is unavailable', async () => { + const event = await requestFor() + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => settingsFor(), + undefined, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(setPeerPubkey).not.to.have.been.called + const ok = emit + .getCalls() + .map((call) => call.args[1]) + .find((message) => message[0] === 'OK') + expect(ok?.[3]).to.include('unavailable') + }) + + it('rejects when the attestation cannot be stored', async () => { + const event = await requestFor() + attestations.save.rejects(new Error('database down')) + const strategy = new PeeringRequestEventStrategy( + webSocket, + () => settingsFor(), + attestations, + () => now, + () => receiverKey, + ) + + await strategy.execute(event) + + expect(setPeerPubkey).not.to.have.been.called + const ok = emit + .getCalls() + .map((call) => call.args[1]) + .find((message) => message[0] === 'OK') + expect(ok?.[3]).to.include('unable to record') + }) + it('rejects a valid request from a relay that is not configured', async () => { const event = await requestFor() const strategy = new PeeringRequestEventStrategy( @@ -178,3 +220,17 @@ describe('PeeringRequestEventStrategy', () => { expect(ok?.[3]).to.include('peering is not enabled') }) }) + +describe('PeeringAcceptanceEventStrategy', () => { + it('rejects a client-published acceptance', async () => { + const emit = Sinon.stub() + const strategy = new PeeringAcceptanceEventStrategy({ emit } as any) + + await strategy.execute({ id: 'event-1' } as any) + + const ok = emit.firstCall.args[1] + expect(ok[0]).to.equal('OK') + expect(ok[2]).to.equal(false) + expect(ok[3]).to.include('issued by the relay') + }) +}) diff --git a/test/unit/utils/peering-attestation.spec.ts b/test/unit/utils/peering-attestation.spec.ts index 31ec5b582..e020a9cc5 100644 --- a/test/unit/utils/peering-attestation.spec.ts +++ b/test/unit/utils/peering-attestation.spec.ts @@ -1,10 +1,12 @@ import { expect } from 'chai' import type { PeeringScope, PeeringTerm } from '../../../src/@types/settings' -import { getPublicKey } from '../../../src/utils/event' +import { getPublicKey, identifyEvent, signEvent } from '../../../src/utils/event' +import { toBech32 } from '../../../src/utils/transform' import { buildPeeringAcceptanceEvent, buildPeeringRequestEvent, + normalizePeeringRelayUrl, peeringTermsHash, samePeeringScopes, samePeeringTerms, @@ -15,6 +17,7 @@ import { const ownerKey = '1'.repeat(64) const relayKey = '2'.repeat(64) const receiverKey = '3'.repeat(64) +const ownerPubkey = getPublicKey(ownerKey) const relayPubkey = getPublicKey(relayKey) const receiverPubkey = getPublicKey(receiverKey) const now = new Date('2026-11-23T12:00:00.000Z') @@ -35,6 +38,17 @@ const buildRequest = (overrides: Partial + signEvent(key)( + await identifyEvent({ + pubkey: getPublicKey(key), + created_at: createdAt, + kind, + tags: tags as never, + content, + }), + ) + const verifyOptions = (overrides: Partial[1]> = {}) => ({ authenticatedPubkeys: [relayPubkey], receiverPubkey, @@ -58,6 +72,17 @@ describe('peering attestation', () => { } }) + it('accepts an npub form of the configured owner key', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent( + event, + verifyOptions({ expectedOwnerPubkey: toBech32('npub')(ownerPubkey) }), + ) + + expect(result.ok).to.equal(true) + }) + it('rejects a request signed by an owner other than the configured one', async () => { const event = await buildRequest() @@ -153,6 +178,76 @@ describe('peering attestation', () => { expect(result.ok).to.equal(true) }) + it('rejects malformed relay or receiver pubkeys when building', async () => { + let error: unknown + try { + await buildRequest({ relayPubkey: 'not-a-pubkey' }) + } catch (caught) { + error = caught + } + + expect((error as Error).message).to.include('32-byte hex') + }) + + it('fails when proof-of-work cannot be found in the attempt budget', async () => { + let error: unknown + try { + await buildRequest({ powDifficulty: 200, maxPowAttempts: 1 }) + } catch (caught) { + error = caught + } + + expect((error as Error).message).to.include('proof-of-work') + }) + + it('rejects an event with the wrong kind', async () => { + const event = await signedEvent(1, '{}', []) + + const result = await verifyPeeringRequestEvent(event, verifyOptions()) + + expect(result).to.include({ ok: false, reason: 'not a peering request' }) + }) + + it('rejects malformed request content', async () => { + const event = await signedEvent(28937, 'not-json', [ + ['p', receiverPubkey], + ['t', 'peering-request'], + ]) + + const result = await verifyPeeringRequestEvent(event, verifyOptions()) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('malformed') + } + }) + + it('rejects a request that does not target this relay', async () => { + const payload = JSON.parse((await buildRequest()).content) + const event = await signedEvent(28937, JSON.stringify(payload), [ + ['p', getPublicKey('4'.repeat(64))], + ['t', 'peering-request'], + ]) + + const result = await verifyPeeringRequestEvent(event, verifyOptions()) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('target') + } + }) + + it('rejects a malformed configured owner key', async () => { + const event = await buildRequest() + + const result = await verifyPeeringRequestEvent(event, verifyOptions({ expectedOwnerPubkey: 'nope' })) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('configured owner') + } + }) + it('produces a relay-signed acceptance for the exact request', async () => { const request = await buildRequest() const requestPayload = await verifyPeeringRequestEvent(request, verifyOptions()) @@ -178,6 +273,16 @@ describe('peering attestation', () => { } }) + it('normalizes http relay URLs for signed payloads', () => { + expect(normalizePeeringRelayUrl('https://peer.example.com')).to.equal('wss://peer.example.com') + expect(normalizePeeringRelayUrl('http://peer.example.com')).to.equal('ws://peer.example.com') + expect(normalizePeeringRelayUrl('wss://peer.example.com')).to.equal('wss://peer.example.com') + }) + + it('treats a singleton kind range as the same kind', () => { + expect(samePeeringScopes([{ kinds: [[1, 1]] }], [{ kinds: [1] }])).to.equal(true) + }) + it('treats term and scope order as insignificant', () => { const reversedTerms = [...terms].reverse() const scopesA: PeeringScope[] = [{ kinds: [[10000, 19999], 1] }] @@ -187,3 +292,72 @@ describe('peering attestation', () => { expect(samePeeringScopes(scopesA, scopesB)).to.equal(true) }) }) + +describe('peering acceptance verification', () => { + it('rejects an acceptance with the wrong kind', async () => { + const request = await buildRequest() + const event = await signedEvent(1, '{}', [], receiverKey) + + const result = await verifyPeeringAcceptanceEvent(event, request) + + expect(result).to.include({ ok: false, reason: 'not a peering acceptance' }) + }) + + it('rejects an acceptance that does not reference the request', async () => { + const request = await buildRequest() + const event = await signedEvent( + 28938, + JSON.stringify({ + request_id: request.id, + relay_pubkey: receiverPubkey, + relay_url: 'wss://receiver.example.com', + terms_hash: peeringTermsHash(terms), + accepted_at: createdAt, + }), + [['p', ownerPubkey]], + receiverKey, + ) + + const result = await verifyPeeringAcceptanceEvent(event, request) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('reference') + } + }) + + it('rejects malformed acceptance content', async () => { + const request = await buildRequest() + const event = await signedEvent(28938, 'not-json', [['e', request.id]], receiverKey) + + const result = await verifyPeeringAcceptanceEvent(event, request) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('malformed') + } + }) + + it('rejects an acceptance whose signer does not match its relay key', async () => { + const request = await buildRequest() + const event = await signedEvent( + 28938, + JSON.stringify({ + request_id: request.id, + relay_pubkey: relayPubkey, + relay_url: 'wss://receiver.example.com', + terms_hash: peeringTermsHash(terms), + accepted_at: createdAt, + }), + [['e', request.id]], + receiverKey, + ) + + const result = await verifyPeeringAcceptanceEvent(event, request) + + expect(result).to.include({ ok: false }) + if (result.ok === false) { + expect(result.reason).to.include('signer') + } + }) +}) From 206714aac67fd716650f996cfd248f95ff64f139 Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Mon, 23 Nov 2026 20:19:16 +0530 Subject: [PATCH 3/3] fix(peering): keep peer identities scoped and fail closed on bad pins - clear only the identity being withdrawn on multi-AUTH sockets\n- fail closed when a configured owner pin cannot be parsed\n- update the NIP-11 integration expectation for the default attestation policy\n- cover the adapter, auth and repository guard paths --- src/@types/adapters.ts | 8 +- src/adapters/web-socket-adapter.ts | 13 ++- src/handlers/auth-message-handler.ts | 2 +- .../features/nip-11/nip-11.feature.ts | 101 +++++++++--------- test/unit/adapters/web-socket-adapter.spec.ts | 46 +++++++- .../handlers/auth-message-handler.spec.ts | 21 ++++ .../peering-attestation-repository.spec.ts | 19 ++++ 7 files changed, 152 insertions(+), 58 deletions(-) diff --git a/src/@types/adapters.ts b/src/@types/adapters.ts index c1b3da64f..c57aed5cc 100644 --- a/src/@types/adapters.ts +++ b/src/@types/adapters.ts @@ -30,8 +30,12 @@ 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, agreement?: PeeringAttestationAgreement): void - /** Withdraw peer treatment for the rest of this socket's AUTH session. */ - clearPeerPubkey(): 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 diff --git a/src/adapters/web-socket-adapter.ts b/src/adapters/web-socket-adapter.ts index 421e14498..b947e988f 100644 --- a/src/adapters/web-socket-adapter.ts +++ b/src/adapters/web-socket-adapter.ts @@ -391,15 +391,19 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter } if ((settings.peering?.ownerAttestation ?? 'waived') === 'required') { - const configuredOwner = parsePeeringPeerPubkey(findConfiguredPeeringPeer(settings, this.peerPubkey)?.ownerPubkey) + 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) || - (configuredOwner !== undefined && agreement.ownerPubkey.toLowerCase() !== configuredOwner) + ownerMismatch ) { this.clearPeerPubkey() return undefined @@ -416,7 +420,10 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter this.peerAgreement = allowed ? agreement : undefined } - public clearPeerPubkey(): void { + public clearPeerPubkey(pubkey?: string): void { + if (pubkey && this.peerPubkey !== pubkey) { + return + } this.peerPubkey = undefined this.peerAgreement = undefined } diff --git a/src/handlers/auth-message-handler.ts b/src/handlers/auth-message-handler.ts index 25179e170..adcb7dd4a 100644 --- a/src/handlers/auth-message-handler.ts +++ b/src/handlers/auth-message-handler.ts @@ -91,7 +91,7 @@ export class AuthMessageHandler implements IMessageHandler { const withhold = (): void => { // A re-AUTH must not leave an earlier peer identity alive after the // agreement stops matching. - this.webSocket.clearPeerPubkey() + this.webSocket.clearPeerPubkey(pubkey) } if (!this.peeringAttestations) { diff --git a/test/integration/features/nip-11/nip-11.feature.ts b/test/integration/features/nip-11/nip-11.feature.ts index ea8ba8eaa..c7bbbecc6 100644 --- a/test/integration/features/nip-11/nip-11.feature.ts +++ b/test/integration/features/nip-11/nip-11.feature.ts @@ -13,7 +13,7 @@ const { expect } = chai const BASE_URL = 'http://localhost:18808' -When('a client requests the relay information document', async function(this: World>) { +When('a client requests the relay information document', async function (this: World>) { const response: AxiosResponse = await axios.get(BASE_URL, { headers: { Accept: 'application/nostr+json' }, validateStatus: () => true, @@ -21,18 +21,18 @@ When('a client requests the relay information document', async function(this: Wo this.parameters.httpResponse = response }) -When('a client requests the root path with Accept header {string}', async function( - this: World>, - acceptHeader: string, -) { - const response: AxiosResponse = await axios.get(BASE_URL, { - headers: { Accept: acceptHeader }, - validateStatus: () => true, - }) - this.parameters.httpResponse = response -}) +When( + 'a client requests the root path with Accept header {string}', + async function (this: World>, acceptHeader: string) { + const response: AxiosResponse = await axios.get(BASE_URL, { + headers: { Accept: acceptHeader }, + validateStatus: () => true, + }) + this.parameters.httpResponse = response + }, +) -When('a browser requests the root path', async function(this: World>) { +When('a browser requests the root path', async function (this: World>) { const response: AxiosResponse = await axios.get(BASE_URL, { headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', @@ -42,57 +42,55 @@ When('a browser requests the root path', async function(this: World>, status: number) { +Then('the response status is {int}', function (this: World>, status: number) { expect(this.parameters.httpResponse.status).to.equal(status) }) -Then('the response Content-Type includes {string}', function( - this: World>, - contentType: string, -) { +Then('the response Content-Type includes {string}', function (this: World>, contentType: string) { expect(this.parameters.httpResponse.headers['content-type']).to.include(contentType) }) -Then('the response Content-Type does not include {string}', function( - this: World>, - contentType: string, -) { - expect(this.parameters.httpResponse.headers['content-type']).to.not.include(contentType) -}) +Then( + 'the response Content-Type does not include {string}', + function (this: World>, contentType: string) { + expect(this.parameters.httpResponse.headers['content-type']).to.not.include(contentType) + }, +) -Then('the relay information document contains the required fields', function(this: World>) { +Then('the relay information document contains the required fields', function (this: World>) { const doc = this.parameters.httpResponse.data for (const field of ['name', 'description', 'pubkey', 'supported_nips', 'software', 'version']) { expect(doc, `expected relay info doc to have field "${field}"`).to.have.property(field) } }) -Then('the supported_nips field matches the NIPs declared in package.json', function(this: World>) { +Then('the supported_nips field matches the NIPs declared in package.json', function (this: World>) { const doc = this.parameters.httpResponse.data // NIP-43 and NIP-77 are only advertised when enabled in settings; the integration // relay runs with both disabled, so they are filtered from the document. expect(doc.supported_nips).to.deep.equal(packageJson.supportedNips.filter((nip: number) => nip !== 43 && nip !== 77)) }) -Then('the response body is not a relay information document', function(this: World>) { +Then('the response body is not a relay information document', function (this: World>) { const body = this.parameters.httpResponse.data const isRelayInfoDoc = typeof body === 'object' && body !== null && 'supported_nips' in body expect(isRelayInfoDoc).to.equal(false) }) -Then('the limitation object contains a max_filters field', function(this: World>) { +Then('the limitation object contains a max_filters field', function (this: World>) { const doc = this.parameters.httpResponse.data const expectedMaxFilters = createSettings().limits?.client?.subscription?.maxFilters expect(doc.limitation.max_filters).to.equal(expectedMaxFilters) }) -Then('the peering object matches the configured peering settings', function(this: World>) { +Then('the peering object matches the configured peering settings', function (this: World>) { const doc = this.parameters.httpResponse.data expect(doc.peering).to.deep.equal({ enabled: true, contact: 'mailto:peering@example.com', endpoint: 'wss://relay.example.com', min_pow_difficulty: 16, + owner_attestation: 'waived', scopes: [ { kinds: [1, 6], window_seconds: 3600 }, { kinds: [3], since: 1700000000 }, @@ -110,7 +108,7 @@ const peeringIssuesFor = (peering: unknown) => { } as Settings).filter((issue) => issue.path.startsWith('peering')) } -When('peering settings are validated with a complete configuration', function(this: World>) { +When('peering settings are validated with a complete configuration', function (this: World>) { this.parameters.peeringValidationIssues = peeringIssuesFor({ enabled: true, contact: 'mailto:peering@example.com', @@ -124,7 +122,7 @@ When('peering settings are validated with a complete configuration', function(th }) }) -When('peering settings are validated with an invalid configuration', function(this: World>) { +When('peering settings are validated with an invalid configuration', function (this: World>) { this.parameters.peeringValidationIssues = [ { enabled: true, @@ -143,30 +141,31 @@ When('peering settings are validated with an invalid configuration', function(th ].flatMap(peeringIssuesFor) }) -Then('the peering settings validation reports no issues', function(this: World>) { +Then('the peering settings validation reports no issues', function (this: World>) { expect(this.parameters.peeringValidationIssues).to.deep.equal([]) }) -Then('the peering settings validation reports an issue at {string}', function( - this: World>, - path: string, -) { - expect( - this.parameters.peeringValidationIssues.some((issue: { path: string }) => issue.path === path), - `expected a validation issue at "${path}"`, - ).to.equal(true) -}) - -Then('the relay information response includes required NIP-11 CORS headers', function( - this: World>, -) { - const headers = this.parameters.httpResponse.headers - expect(headers['access-control-allow-origin']).to.equal('*') - expect(headers['access-control-allow-headers']).to.equal('*') - expect(headers['access-control-allow-methods']).to.equal('GET, OPTIONS') -}) - -Then('the limitation object contains NIP-11 parity fields and values', function(this: World>) { +Then( + 'the peering settings validation reports an issue at {string}', + function (this: World>, path: string) { + expect( + this.parameters.peeringValidationIssues.some((issue: { path: string }) => issue.path === path), + `expected a validation issue at "${path}"`, + ).to.equal(true) + }, +) + +Then( + 'the relay information response includes required NIP-11 CORS headers', + function (this: World>) { + const headers = this.parameters.httpResponse.headers + expect(headers['access-control-allow-origin']).to.equal('*') + expect(headers['access-control-allow-headers']).to.equal('*') + expect(headers['access-control-allow-methods']).to.equal('GET, OPTIONS') + }, +) + +Then('the limitation object contains NIP-11 parity fields and values', function (this: World>) { const doc = this.parameters.httpResponse.data const settings = createSettings() const eventLimits = settings.limits?.event diff --git a/test/unit/adapters/web-socket-adapter.spec.ts b/test/unit/adapters/web-socket-adapter.spec.ts index 9a93a43ca..d874ce909 100644 --- a/test/unit/adapters/web-socket-adapter.spec.ts +++ b/test/unit/adapters/web-socket-adapter.spec.ts @@ -1262,6 +1262,47 @@ describe('WebSocketAdapter', () => { expect(adapter.getPeerPubkey()).to.equal(undefined) }) + it('fails closed when a configured owner pin cannot be parsed', () => { + const pubkey = 'a'.repeat(64) + const terms = [{ amount: 21000, unit: 'msats', period: 2592000 }] + const scopes = [{ kinds: [1] }] + settingsFactory.returns({ + peering: { + enabled: true, + ownerAttestation: 'required', + peers: [{ pubkey, relayUrl: 'wss://peer.example.com', ownerPubkey: 'not-a-pubkey' }], + terms, + scopes, + }, + }) + + adapter.addAuthenticatedPubkey(pubkey, '1'.repeat(64)) + adapter.setPeerPubkey(pubkey, { + termsHash: peeringTermsHash(terms), + scopes, + ownerPubkey: 'b'.repeat(64), + }) + + expect(adapter.getPeerPubkey()).to.equal(undefined) + }) + + it('requires an agreement for a required policy', () => { + const pubkey = 'a'.repeat(64) + settingsFactory.returns({ + peering: { + enabled: true, + ownerAttestation: 'required', + peers: [{ pubkey, relayUrl: 'wss://peer.example.com' }], + terms: [], + scopes: [], + }, + }) + + adapter.addAuthenticatedPubkey(pubkey, '1'.repeat(64)) + adapter.setPeerPubkey(pubkey) + expect(adapter.getPeerPubkey()).to.equal(undefined) + }) + it('clears peer status explicitly', () => { const pubkey = 'a'.repeat(64) settingsFactory.returns({ @@ -1272,7 +1313,10 @@ describe('WebSocketAdapter', () => { adapter.setPeerPubkey(pubkey) expect(adapter.getPeerPubkey()).to.equal(pubkey) - adapter.clearPeerPubkey() + adapter.clearPeerPubkey('b'.repeat(64)) + expect(adapter.getPeerPubkey()).to.equal(pubkey) + + adapter.clearPeerPubkey(pubkey) expect(adapter.getPeerPubkey()).to.equal(undefined) }) diff --git a/test/unit/handlers/auth-message-handler.spec.ts b/test/unit/handlers/auth-message-handler.spec.ts index db5dda7a2..586b4ea38 100644 --- a/test/unit/handlers/auth-message-handler.spec.ts +++ b/test/unit/handlers/auth-message-handler.spec.ts @@ -189,6 +189,27 @@ describe('AuthMessageHandler', () => { expect(webSocket.setPeerPubkey as Sinon.SinonStub).not.to.have.been.called }) + it('fails closed when the attestation lookup errors', async () => { + settingsFactory.returns({ + info: { relay_url: relayUrl }, + peering: { + enabled: true, + ownerAttestation: 'required', + peers: [{ pubkey, relayUrl }], + }, + } as Partial) + const peeringAttestations = { + findByRelayPubkey: Sinon.stub().rejects(new Error('database down')), + } + handler = new AuthMessageHandler(webSocket, settingsFactory, peeringAttestations as any) + const message = await createAuthEvent() + + await handler.handleMessage(message) + + expect(webSocket.setPeerPubkey as Sinon.SinonStub).not.to.have.been.called + expect(webSocket.clearPeerPubkey as Sinon.SinonStub).to.have.been.calledWith(pubkey) + }) + it('grants peer treatment when a required attestation exists', async () => { settingsFactory.returns({ info: { relay_url: relayUrl }, diff --git a/test/unit/repositories/peering-attestation-repository.spec.ts b/test/unit/repositories/peering-attestation-repository.spec.ts index cdd13eedd..d31206ec7 100644 --- a/test/unit/repositories/peering-attestation-repository.spec.ts +++ b/test/unit/repositories/peering-attestation-repository.spec.ts @@ -50,6 +50,25 @@ describe('PeeringAttestationRepository', () => { }) }) + it('returns undefined when no attestation exists', async () => { + const recording = createRecordingKnex() + const repository = new PeeringAttestationRepository(recording.db) + recording.respondWith([]) + + expect(await repository.findByRelayPubkey(peerPubkey)).to.equal(undefined) + }) + + it('uses the input when an upsert returns no row', async () => { + const recording = createRecordingKnex() + const repository = new PeeringAttestationRepository(recording.db) + recording.respondWith([]) + + const result = await repository.save(attestation) + + expect(result.relayPubkey).to.equal(peerPubkey) + expect(result.termsHash).to.equal(attestation.termsHash) + }) + it('upserts the latest accepted request for a relay', async () => { const recording = createRecordingKnex() const repository = new PeeringAttestationRepository(recording.db)