diff --git a/.changeset/peering-admin-visibility.md b/.changeset/peering-admin-visibility.md new file mode 100644 index 000000000..bc6d6f60e --- /dev/null +++ b/.changeset/peering-admin-visibility.md @@ -0,0 +1,10 @@ +--- +"nostream": minor +--- + +feat(peering): show relationship state, terms and traffic split in admin + +The Peering console now shows each peer's relationship state and current terms, +reconciliation and peer-request activity, and the existing budget and +held-invoice panels in one place. Relationship state follows the same access +window as the relay, so an ended period no longer appears active. diff --git a/docs/PEERING.md b/docs/PEERING.md index 0b9110e7f..cf17f5772 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -123,8 +123,12 @@ reconciliation from being reported as stale. Each reconciliation writes the peer's state to Redis and exposes it at `GET /admin/peering`: status, last reconciliation, latest event age ("lag"), -and the number of events the last reconciliation found missing. The admin -console shows the same rows under Operations → Peering. +the number of events the last reconciliation found missing, and how many events +it stored. The admin console shows the same rows under Operations → Peering, +with the peer's current terms and an explicit relationship state (`active`, +`suspended`, `lapsed`, `unpaid`, `free` or `removed`). It also shows reconciled +events, peer requests and all events served, plus the per-peer and global +budget counters and held invoices with Approve/Reject actions. NIP-77 must be enabled on the source relay (`nip77.enabled` and the PostgreSQL event store). `peering.peers` on the receiving relay is the only trust material diff --git a/resources/admin/assets/admin-ops.js b/resources/admin/assets/admin-ops.js index d187b6652..63d622fa4 100644 --- a/resources/admin/assets/admin-ops.js +++ b/resources/admin/assets/admin-ops.js @@ -121,14 +121,25 @@ return `${Math.round(seconds / 86400)}d` } - const peeringBillingBadge = (billing) => { - if (!billing?.status) { - return 'Not billed' + const peeringStateBadge = (relationship) => { + const status = String(relationship || 'removed') + const degraded = ['lapsed', 'unpaid', 'suspended', 'removed'].includes(status) + return `${escapeHtml(status)}` + } + + const formatPeeringPeriod = (seconds) => { + if (seconds % 86400 === 0) return `${seconds / 86400}d` + if (seconds % 3600 === 0) return `${seconds / 3600}h` + if (seconds % 60 === 0) return `${seconds / 60}m` + return `${seconds}s` + } + + const peeringTerms = (terms) => { + if (!terms?.amountMsats || !terms?.periodSeconds) { + return 'Free' } - const status = String(billing.status) - const degraded = status === 'lapsed' || status === 'unpaid' - return `${escapeHtml(status)}` + return `${Math.round(Number(BigInt(terms.amountMsats) / 1000n))} sats / ${formatPeeringPeriod(terms.periodSeconds)}` } const peeringSignalBadge = (row) => { @@ -209,9 +220,10 @@ .join('') } - const renderPeering = (rows) => { if (!Array.isArray(rows) || !rows.length) { + const renderPeering = (rows) => { + if (!Array.isArray(rows) || !rows.length) { elements.peeringBody.innerHTML = - 'No peering peers configured.' + 'No peering peers configured.' return } @@ -224,13 +236,15 @@ return ` ${escapeHtml(shortPubkey(row.pubkey))} ${escapeHtml(row.relayUrl)} - ${peeringBillingBadge(row.billing)} + ${escapeHtml(peeringTerms(row.terms))} + ${peeringStateBadge(row.relationship)} ${escapeHtml(formatTime(row.billing?.periodEnd))} ${escapeHtml(formatTime(state?.lastReconciledAt))} ${escapeHtml(formatLag(state?.lagSeconds))} + ${escapeHtml(state?.receivedEvents ?? 0)} ${escapeHtml(state?.missingEvents ?? '—')} + ${escapeHtml(requests?.eventsServed ?? 0)} ${escapeHtml(requests?.requests ?? 0)} - ${escapeHtml(requests?.eventsServed ?? 0)} ${peeringSignalBadge(row)} ` }) @@ -437,11 +451,20 @@ } const decidePeeringInvoice = async (paymentHash, action) => { - const response = await adminFetch('/peering/invoices/decision', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ paymentHash, action }), - }) + let response + try { + response = await adminFetch('/peering/invoices/decision', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ paymentHash, action }), + }) + } catch (error) { + if (elements.peeringInvoicesSync) { + elements.peeringInvoicesSync.innerHTML = `> invoice: ${escapeHtml(error instanceof Error ? error.message : 'decision request failed')}` + } + return + } + const payload = await response.json().catch(() => ({})) if (!response.ok) { if (elements.peeringInvoicesSync) { @@ -449,7 +472,15 @@ } return } - await loadPeering() + + try { + await loadPeering() + } catch { + if (elements.peeringInvoicesSync) { + elements.peeringInvoicesSync.innerHTML = + '> invoice saved; refresh failed' + } + } } const refreshAll = async () => { diff --git a/resources/admin/dashboard.html b/resources/admin/dashboard.html index 6ae241595..50950decb 100644 --- a/resources/admin/dashboard.html +++ b/resources/admin/dashboard.html @@ -236,18 +236,20 @@

Peering

Peer Relay - Billing + Terms + State Access until Last reconciliation Lag + Reconciled Missing - Requests - Events served + Events served + Peer requests Signal - No peering peers configured. + No peering peers configured. diff --git a/src/controllers/admin/get-admin-peering-controller.ts b/src/controllers/admin/get-admin-peering-controller.ts index 640d73cbc..0194c701e 100644 --- a/src/controllers/admin/get-admin-peering-controller.ts +++ b/src/controllers/admin/get-admin-peering-controller.ts @@ -1,7 +1,7 @@ import { Request, Response } from 'express' import { IController } from '../../@types/controllers' -import { PeeringInvoice } from '../../@types/peering' +import { PeeringInvoice, PeeringInvoiceStatus } from '../../@types/peering' import { IPeeringPaymentRepository } from '../../@types/repositories' import { IPeeringBuyerService } from '../../@types/services' import { Settings } from '../../@types/settings' @@ -10,6 +10,9 @@ import { PeeringRequestStatsStore } from '../../utils/peering-request-stats' import { PeeringSyncStateStore } from '../../utils/peering-sync-state' import { loadMergedSettings } from '../../utils/settings-config' +const ADMIN_RECENT_INVOICES = 50 +const ADMIN_HELD_INVOICES = 500 + export const serializePeeringInvoice = (invoice: PeeringInvoice) => ({ paymentHash: invoice.paymentHash, eventId: invoice.eventId, @@ -38,14 +41,24 @@ export class GetAdminPeeringController implements IController { ) {} public async handleRequest(_request: Request, response: Response): Promise { - const [states, settings, requestStats, billing, invoices, budgets] = await Promise.all([ + const [states, settings, requestStats, billing, recentInvoices, heldInvoices, budgets] = await Promise.all([ this.stateStore.list(), this.getSettings(), this.requestStatsStore?.list() ?? [], this.peeringPaymentRepository?.list() ?? [], - this.peeringBuyerService?.list(undefined, 50) ?? [], + this.peeringBuyerService?.list(undefined, ADMIN_RECENT_INVOICES) ?? [], + this.peeringBuyerService?.list( + [PeeringInvoiceStatus.HELD, PeeringInvoiceStatus.FAILED], + ADMIN_HELD_INVOICES, + ) ?? [], this.peeringBuyerService?.budgetSummary() ?? [], ]) + const invoicesByHash = new Map( + [...heldInvoices, ...recentInvoices].map((invoice) => [invoice.paymentHash, invoice]), + ) + const invoices = [...invoicesByHash.values()].sort( + (left, right) => right.createdAt.getTime() - left.createdAt.getTime(), + ) const peers = mergePeeringRows(settings, states, undefined, requestStats, billing) response diff --git a/src/utils/admin-peering.ts b/src/utils/admin-peering.ts index 926225572..c477b6b72 100644 --- a/src/utils/admin-peering.ts +++ b/src/utils/admin-peering.ts @@ -1,6 +1,7 @@ -import { PeeringPayment, PeeringPeerSyncState } from '../@types/peering' +import { PeeringPayment, PeeringPaymentStatus, PeeringPeerSyncState } from '../@types/peering' import { Settings } from '../@types/settings' import { parsePeeringPeerPubkey } from './peering-auth' +import { isPeeringAccessActive, resolvePaidPeeringTerm } from './peering-billing' import { PeeringRequestStats } from './peering-request-stats' import { isPeeringSyncStateStale, PEERING_SYNC_STATE_STALE_AFTER_SECONDS } from './peering-sync-state' @@ -17,12 +18,21 @@ export interface AdminPeeringBilling { lastError?: string | null } +export type AdminPeeringRelationship = 'active' | 'suspended' | 'lapsed' | 'unpaid' | 'free' | 'removed' + +export interface AdminPeeringTerms { + amountMsats: string + periodSeconds: number +} + export interface AdminPeeringRow { pubkey: string relayUrl: string configured: boolean enabled: boolean stale: boolean + relationship: AdminPeeringRelationship + terms?: AdminPeeringTerms state?: PeeringPeerSyncState requests?: PeeringRequestStats billing?: AdminPeeringBilling @@ -41,16 +51,59 @@ const toAdminBilling = (payment: PeeringPayment): AdminPeeringBilling => ({ lastError: payment.lastError, }) +const relationshipFor = ( + configured: boolean, + enabled: boolean, + billing: AdminPeeringBilling | undefined, + now: Date, +): AdminPeeringRelationship => { + if (billing?.status === PeeringPaymentStatus.LAPSED) { + return 'lapsed' + } + if (!configured) { + return 'removed' + } + if (!enabled) { + return 'suspended' + } + if ( + billing?.status === PeeringPaymentStatus.ACTIVE || + billing?.status === PeeringPaymentStatus.RENEWAL_PENDING + ) { + // The billing sweep can lag the access check. Do not call a peer active + // once its saved period has already ended. + return isPeeringAccessActive(billing.status, billing.periodEnd, now) ? 'active' : 'lapsed' + } + if ( + billing?.status === PeeringPaymentStatus.UNPAID || + billing?.status === PeeringPaymentStatus.INVOICED + ) { + return 'unpaid' + } + + return 'free' +} + +const termsFor = (billing: AdminPeeringBilling | undefined): AdminPeeringTerms | undefined => + billing?.termAmountMsats && billing.termPeriodSeconds + ? { amountMsats: billing.termAmountMsats, periodSeconds: billing.termPeriodSeconds } + : undefined + export const mergePeeringRows = ( settings: Settings, states: PeeringPeerSyncState[], staleAfterSeconds = PEERING_SYNC_STATE_STALE_AFTER_SECONDS, requestStats: PeeringRequestStats[] = [], billing: PeeringPayment[] = [], + now = new Date(), ): AdminPeeringRow[] => { const statesByPubkey = new Map(states.map((state) => [state.pubkey.toLowerCase(), state])) const requestsByPubkey = new Map(requestStats.map((stats) => [stats.pubkey.toLowerCase(), stats])) const billingByPubkey = new Map(billing.map((payment) => [payment.peerPubkey.toLowerCase(), payment])) + const paidTerm = resolvePaidPeeringTerm(settings) + const configuredTerms: AdminPeeringTerms | undefined = paidTerm + ? { amountMsats: paidTerm.amountMsats.toString(), periodSeconds: paidTerm.periodSeconds } + : undefined const rows: AdminPeeringRow[] = [] const matched = new Set() @@ -62,15 +115,28 @@ export const mergePeeringRows = ( const enabled = peer.enabled !== false matched.add(normalized) + const billing = billingByPubkey.get(normalized) + ? toAdminBilling(billingByPubkey.get(normalized)!) + : undefined + const paidConfiguration = configuredTerms !== undefined + const relationship = !paidConfiguration + ? enabled + ? 'free' + : 'suspended' + : enabled && !billing + ? 'unpaid' + : relationshipFor(true, enabled, billing, now) rows.push({ pubkey, relayUrl: peer.relayUrl, configured: true, enabled, stale: enabled && (!state || isPeeringSyncStateStale(state.updatedAt, staleAfterSeconds)), + relationship, + terms: paidConfiguration ? (termsFor(billing) ?? configuredTerms) : undefined, state, requests: requestsByPubkey.get(normalized), - billing: billingByPubkey.get(normalized) ? toAdminBilling(billingByPubkey.get(normalized)!) : undefined, + billing, }) } @@ -81,17 +147,20 @@ export const mergePeeringRows = ( continue } + const billing = billingByPubkey.get(state.pubkey.toLowerCase()) + ? toAdminBilling(billingByPubkey.get(state.pubkey.toLowerCase())!) + : undefined rows.push({ pubkey: state.pubkey, relayUrl: state.relayUrl, configured: false, enabled: false, stale: isPeeringSyncStateStale(state.updatedAt, staleAfterSeconds), + relationship: relationshipFor(false, false, billing, now), + terms: termsFor(billing), state, requests: requestsByPubkey.get(state.pubkey.toLowerCase()), - billing: billingByPubkey.get(state.pubkey.toLowerCase()) - ? toAdminBilling(billingByPubkey.get(state.pubkey.toLowerCase())!) - : undefined, + billing, }) } @@ -105,13 +174,16 @@ export const mergePeeringRows = ( continue } + const billing = toAdminBilling(payment) rows.push({ pubkey: payment.peerPubkey, relayUrl: '', configured: false, enabled: false, stale: true, - billing: toAdminBilling(payment), + relationship: relationshipFor(false, false, billing, now), + terms: termsFor(billing), + billing, }) } diff --git a/test/integration/features/peering/peering-admin.feature.ts b/test/integration/features/peering/peering-admin.feature.ts index 025c0432f..81b411a23 100644 --- a/test/integration/features/peering/peering-admin.feature.ts +++ b/test/integration/features/peering/peering-admin.feature.ts @@ -157,4 +157,5 @@ Then('it contains the held invoice and the current budget', function (this: Worl const payload = this.parameters.adminResponse.send.firstCall.args[0] expect(payload.invoices.some((invoice: any) => invoice.paymentHash === this.parameters.adminPayHash)).to.equal(true) expect(payload.budgets.some((budget: any) => budget.scope === 'peer')).to.equal(true) + expect(payload.peers[0].relationship).to.equal('free') }) diff --git a/test/unit/controllers/admin/get-admin-peering-controller.spec.ts b/test/unit/controllers/admin/get-admin-peering-controller.spec.ts index 106f548f5..39b86da7e 100644 --- a/test/unit/controllers/admin/get-admin-peering-controller.spec.ts +++ b/test/unit/controllers/admin/get-admin-peering-controller.spec.ts @@ -123,6 +123,7 @@ describe('GetAdminPeeringController', () => { status: 'held', reason: 'amount_mismatch', }) + expect(peeringBuyerService.list).to.have.been.calledWith(['held', 'failed'], 500) expect(payload.budgets[0]).to.deep.include({ scope: 'peer', limitMsats: '10000000', diff --git a/test/unit/utils/admin-peering.spec.ts b/test/unit/utils/admin-peering.spec.ts index 9110c672d..5bbc5036f 100644 --- a/test/unit/utils/admin-peering.spec.ts +++ b/test/unit/utils/admin-peering.spec.ts @@ -3,6 +3,8 @@ import { PeeringPeerSyncState } from '../../../src/@types/peering' import { Settings } from '../../../src/@types/settings' import { mergePeeringRows } from '../../../src/utils/admin-peering' +const now = new Date('2026-11-23T00:00:00.000Z') + const state = (overrides: Partial = {}): PeeringPeerSyncState => ({ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com', @@ -31,6 +33,77 @@ describe('admin peering rows', () => { stale: false, }) expect(rows[0].state?.status).to.equal('live') + expect(rows[0].relationship).to.equal('free') + expect(rows[0].terms).to.be.undefined + }) + + + it('shows a paid configured peer as unpaid before its first invoice', () => { + const rows = mergePeeringRows( + { + peering: { + enabled: true, + terms: [{ amount: 21000, unit: 'sats', period: 2592000 }], + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], + }, + } as Settings, + [state()], + ) + + expect(rows[0].relationship).to.equal('unpaid') + expect(rows[0].terms).to.deep.equal({ amountMsats: '21000000', periodSeconds: 2592000 }) + }) + + it('marks a configured but disabled peer suspended', () => { + const rows = mergePeeringRows( + { + peering: { + enabled: true, + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com', enabled: false }], + }, + } as Settings, + [state()], + ) + + expect(rows[0].relationship).to.equal('suspended') + }) + + it('marks an unpaid billing state and exposes its terms', () => { + const rows = mergePeeringRows( + { + peering: { + enabled: true, + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], + }, + } as Settings, + [state()], + undefined, + [], + [ + { + peerPubkey: 'a'.repeat(64), + direction: 'sell', + status: 'unpaid', + currentInvoiceId: 'inv-1', + renewalInvoiceId: null, + periodStart: null, + periodEnd: null, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: null, + lastSettledAt: null, + lastCheckedAt: null, + lastError: null, + createdAt: new Date(), + updatedAt: new Date(), + } as any, + ], + now, + ) + + expect(rows[0].relationship).to.equal('unpaid') + expect(rows[0].terms).to.deep.equal({ amountMsats: '21000', periodSeconds: 2592000 }) }) it('marks an enabled peer stale when it has no state or the state is old', () => { @@ -54,7 +127,7 @@ describe('admin peering rows', () => { it('shows stored state for a peer that was removed from settings', () => { const rows = mergePeeringRows({} as Settings, [state({ pubkey: 'c'.repeat(64) })]) - expect(rows[0]).to.include({ configured: false, enabled: false }) + expect(rows[0]).to.include({ configured: false, enabled: false, relationship: 'removed' }) }) it('does not attach state from an old relay URL to the configured peer', () => { @@ -99,6 +172,7 @@ describe('admin peering rows', () => { { peering: { enabled: true, + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], }, } as Settings, @@ -124,6 +198,7 @@ describe('admin peering rows', () => { updatedAt: new Date('2026-11-01T00:00:00.000Z'), } as any, ], + now, ) expect(rows[0].billing).to.include({ @@ -132,6 +207,82 @@ describe('admin peering rows', () => { termPeriodSeconds: 2592000, }) expect(rows[0].billing?.periodEnd).to.equal(periodEnd) + expect(rows[0].relationship).to.equal('active') + expect(rows[0].terms).to.deep.equal({ amountMsats: '21000', periodSeconds: 2592000 }) + }) + + it('shows an ended active period as lapsed', () => { + const rows = mergePeeringRows( + { + peering: { + enabled: true, + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], + }, + } as Settings, + [state()], + undefined, + [], + [ + { + peerPubkey: 'a'.repeat(64), + direction: 'sell', + status: 'active', + currentInvoiceId: null, + renewalInvoiceId: null, + periodStart: new Date('2026-10-01T00:00:00.000Z'), + periodEnd: new Date('2026-11-01T00:00:00.000Z'), + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: 'inv-1', + lastSettledAt: new Date('2026-10-01T00:00:00.000Z'), + lastCheckedAt: null, + lastError: null, + createdAt: new Date('2026-10-01T00:00:00.000Z'), + updatedAt: new Date('2026-10-01T00:00:00.000Z'), + } as any, + ], + now, + ) + + expect(rows[0].relationship).to.equal('lapsed') + }) + + it('shows free terms instead of an old billing row', () => { + const rows = mergePeeringRows( + { + peering: { + enabled: true, + peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], + }, + } as Settings, + [state()], + undefined, + [], + [ + { + peerPubkey: 'a'.repeat(64), + direction: 'sell', + status: 'lapsed', + currentInvoiceId: null, + renewalInvoiceId: null, + periodStart: new Date('2026-10-01T00:00:00.000Z'), + periodEnd: new Date('2026-11-01T00:00:00.000Z'), + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + lastSettledInvoiceId: 'inv-1', + lastSettledAt: new Date('2026-10-01T00:00:00.000Z'), + lastCheckedAt: null, + lastError: null, + createdAt: new Date('2026-10-01T00:00:00.000Z'), + updatedAt: new Date('2026-10-01T00:00:00.000Z'), + } as any, + ], + now, + ) + + expect(rows[0].relationship).to.equal('free') + expect(rows[0].terms).to.be.undefined }) it('shows a billing row for a peer removed from settings', () => { @@ -162,7 +313,7 @@ describe('admin peering rows', () => { ) expect(rows).to.have.length(1) - expect(rows[0]).to.include({ configured: false, enabled: false }) + expect(rows[0]).to.include({ configured: false, enabled: false, relationship: 'lapsed' }) expect(rows[0].billing?.status).to.equal('lapsed') }) @@ -171,6 +322,7 @@ describe('admin peering rows', () => { { peering: { enabled: true, + terms: [{ amount: 21000, unit: 'msats', period: 2592000 }], peers: [{ pubkey: 'a'.repeat(64), relayUrl: 'wss://peer.example.com' }], }, } as Settings,