app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit 518f47c5899d27ed8f5e6a85704a2714c00b0d5f
parent f011fa8879ec777bc1ba870fc47428df408dfd0d
Author: triesap <tyson@radroots.org>
Date:   Wed,  7 Oct 2026 06:28:14 +0000

messages: resolve newest known inbox preferences (HCP-062)

- Discover recipient preferences through the fixed anonymous pool and shared budgets.
- Preserve bounded decoded JSON without getters or SDK verification symbols.
- Track newest heads, source completeness and immutable known base versions.
- Test saturation, unsupported heads, cleanup and generation invalidation.

Diffstat:
Aweb/src/lib/messaging/resolve-inbox.ts | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/nostr/decoded-inbox-wire.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/nostr/inbox-queries.ts | 17+++++++++++++++++
Mweb/src/lib/nostr/ingress.ts | 16+++++++++++++---
Mweb/src/lib/nostr/request-result.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mweb/src/lib/nostr/request-scope.ts | 37+++++++++++++++++++++++++++----------
Mweb/src/lib/nostr/verified-envelope.ts | 8++++++++
Mweb/src/lib/runtime/public-runtime.ts | 23+++++++++++++++++++++++
Aweb/tests/integration/inbox-discovery.test.ts | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/inbox-resolution.test.ts | 463+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 2+-
11 files changed, 1127 insertions(+), 18 deletions(-)

diff --git a/web/src/lib/messaging/resolve-inbox.ts b/web/src/lib/messaging/resolve-inbox.ts @@ -0,0 +1,193 @@ +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { + verifiedEnvelopeWire, + type VerifiedEnvelope +} from '../nostr/verified-envelope.ts'; +import { + readInboxPreference, + inboxPreferenceSnapshot, + type InboxPreference +} from '../nostr/inbox-preferences.ts'; +import { + closePublicRequest, + publicRequestScopeSnapshot, + publicRunObservations, + publicRunSnapshot, + type PublicRun, + type PublicRequest +} from '../nostr/request-scope.ts'; +import { + subscribeInboxPreference, + publicViewOwnsRun, + publicViewRunCurrent, + type PublicView +} from '../runtime/public-runtime.ts'; + +declare const resolverBrand: unique symbol; +export type InboxResolver = Readonly<{ readonly [resolverBrand]: true }>; +export type InboxResolution = Readonly<{ + author: string; + status: 'ready' | 'missing' | 'unsupported' | 'inconclusive'; + head: InboxPreference | undefined; + knownBase: + Readonly<{ author: string; id: string; createdAt: number }> | undefined; + request: PublicRequest; + sources: (ReturnType< + typeof publicRequestScopeSnapshot + >['result']['sources'][number] & { + head?: Readonly<{ id: string; createdAt: number }>; + })[]; + coverage: 'bounded-eose' | 'partial'; + definitiveAbsence: false; + wireProvenance: 'decoded-sdk-json'; +}>; +interface Owner { + readonly snapshot: () => InboxResolution; + readonly close: () => void; +} +const owners = new WeakMap<InboxResolver, Owner>(); +function ownerOf(token: InboxResolver): Owner { + const owner = owners.get(token); + if (!owner) throw new Error('inbox_resolver_invalid'); + return owner; +} +// Trusted request factory, like catalog resolvers. Production binds this to the +// current view and real anonymous pool. UI cannot manufacture request/proof tokens. +export function createInboxResolver( + run: PublicRun, + author: unknown, + subscribe: (onVerified: (event: VerifiedEnvelope) => void) => PublicRequest, + current: () => boolean = () => true +): InboxResolver { + const key = canonicalPublicKey(author); + if (!key) throw new Error('inbox_author_invalid'); + if (!publicRunSnapshot(run).active || !current()) + throw new Error('inbox_resolver_inactive'); + let head: InboxPreference | undefined, + closed = false, + rejected = false; + const request = subscribe((proof) => { + if (closed || !current()) return; + const result = readInboxPreference(verifiedEnvelopeWire(proof), key); + if (result.status !== 'supported' && result.status !== 'unsupported') { + rejected = true; + return; + } + const candidate = inboxPreferenceSnapshot(result.value)!, + previous = head && inboxPreferenceSnapshot(head); + if ( + !previous || + candidate.createdAt > previous.createdAt || + (candidate.createdAt === previous.createdAt && candidate.id < previous.id) + ) + head = result.value; + }); + try { + publicRunObservations(run, request); + const snapshot = publicRequestScopeSnapshot(request); + if (snapshot.kind !== 'inbox' || snapshot.result.inbox?.author !== key) + throw new Error('inbox_resolver_request_owner'); + } catch { + closePublicRequest(request); + throw new Error('inbox_resolver_request_owner'); + } + const token = Object.freeze({}) as InboxResolver; + owners.set(token, { + snapshot() { + // Sample the external clock first, then recheck generation ownership. + // Clock reentry may supersede this run before it returns an active value. + const active = publicRunSnapshot(run).active; + const available = !closed && current() && active; + const scope = publicRequestScopeSnapshot(request), + saved = head && inboxPreferenceSnapshot(head); + const complete = + available && + !rejected && + scope.state === 'eose' && + scope.inboxSettled === true && + scope.result.coverage === 'bounded-eose'; + const status = !available + ? 'inconclusive' + : saved?.status === 'unsupported' + ? 'unsupported' + : !complete + ? 'inconclusive' + : saved + ? 'ready' + : 'missing'; + return { + author: key, + status, + head, + knownBase: saved && { + author: key, + id: saved.id, + createdAt: saved.createdAt + }, + request, + sources: scope.result.sources.map((row) => { + const sourceHead = scope.result.inbox?.heads.find( + (h) => h.source === row.source + ); + return { + ...row, + ...(sourceHead + ? { head: { id: sourceHead.id, createdAt: sourceHead.createdAt } } + : {}) + }; + }), + coverage: complete ? 'bounded-eose' : 'partial', + definitiveAbsence: false, + wireProvenance: 'decoded-sdk-json' + }; + }, + close() { + closed = true; + closePublicRequest(request); + } + }); + return token; +} +// One recipient resolver per run prevents repeated lookups from resetting work. +const viewResolvers = new WeakMap< + PublicRun, + Readonly<{ view: PublicView; author: string; resolver?: InboxResolver }> +>(); +export function resolveInboxPreference( + view: PublicView, + run: PublicRun, + author: unknown +): InboxResolver { + const key = canonicalPublicKey(author); + if (!key) throw new Error('inbox_author_invalid'); + const prior = viewResolvers.get(run); + if (prior) { + if (prior.view !== view || prior.author !== key) + throw new Error('inbox_resolver_owner_changed'); + if (!prior.resolver) throw new Error('inbox_resolver_opening'); + return prior.resolver; + } + // Reserve before clock/subscription acquisition can synchronously reenter. + viewResolvers.set(run, { view, author: key }); + try { + if (!publicViewRunCurrent(view, run)) + throw new Error('inbox_resolver_inactive'); + const resolver = createInboxResolver( + run, + key, + (next) => subscribeInboxPreference(view, run, key, next), + () => publicViewOwnsRun(view, run) + ); + viewResolvers.set(run, { view, author: key, resolver }); + return resolver; + } catch { + viewResolvers.delete(run); + throw new Error('inbox_resolver_open_failed'); + } +} +export function inboxResolutionSnapshot(token: InboxResolver): InboxResolution { + return ownerOf(token).snapshot(); +} +export function closeInboxResolver(token: InboxResolver): void { + ownerOf(token).close(); +} diff --git a/web/src/lib/nostr/decoded-inbox-wire.ts b/web/src/lib/nostr/decoded-inbox-wire.ts @@ -0,0 +1,96 @@ +import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; + +// The qualified SDK exposes parsed JSON, not original transport text. Preserve +// every decoded JSON field without invoking getters, toJSON or SDK symbols. +// Bounds are post-parse logical work; this makes no allocation/preparse claim. +export function decodedInboxWire( + input: unknown, + assertActive: () => void +): string | undefined { + const parts: string[] = []; + const encoder = new TextEncoder(); + let bytes = 0, + nodes = 0; + function append(text: string) { + bytes += encoder.encode(text).length; + if (bytes > PUBLIC_INGRESS_BUDGETS.eventBytes) + throw new Error('candidate_invalid'); + parts.push(text); + } + function inspect( + value: object, + name: string + ): PropertyDescriptor | undefined { + assertActive(); + const descriptor = Object.getOwnPropertyDescriptor(value, name); + assertActive(); + return descriptor; + } + function data(value: object, name: string): unknown { + const descriptor = inspect(value, name); + if (!descriptor || !('value' in descriptor)) + throw new Error('candidate_invalid'); + return descriptor.value; + } + function visit(value: unknown): void { + assertActive(); + if (++nodes > PUBLIC_INGRESS_BUDGETS.eventBytes) + throw new Error('candidate_invalid'); + if ( + value === null || + typeof value === 'boolean' || + typeof value === 'number' + ) { + if (typeof value === 'number' && !Number.isFinite(value)) + throw new Error('candidate_invalid'); + append(JSON.stringify(value)); + } else if (typeof value === 'string') { + if (value.length > PUBLIC_INGRESS_BUDGETS.eventBytes) + throw new Error('candidate_invalid'); + append(JSON.stringify(value)); + } else if (typeof value === 'object') { + if (Array.isArray(value)) { + const length = data(value, 'length'); + if ( + typeof length !== 'number' || + !Number.isSafeInteger(length) || + length < 0 || + length > PUBLIC_INGRESS_BUDGETS.eventBytes + ) + throw new Error('candidate_invalid'); + append('['); + for (let index = 0; index < length; index++) { + if (index) append(','); + visit(data(value, String(index))); + } + append(']'); + } else { + append('{'); + let index = 0; + for (const name in value) { + assertActive(); + const descriptor = inspect(value, name); + if (!descriptor) continue; + if (index >= PUBLIC_INGRESS_BUDGETS.eventBytes) + throw new Error('candidate_invalid'); + if (index) append(','); + if (name.length > PUBLIC_INGRESS_BUDGETS.eventBytes) + throw new Error('candidate_invalid'); + append(JSON.stringify(name)); + append(':'); + visit(data(value, name)); + index++; + } + append('}'); + } + } else throw new Error('candidate_invalid'); + } + try { + if (!input || typeof input !== 'object' || Array.isArray(input)) + return undefined; + visit(input); + return parts.join(''); + } catch { + return undefined; + } +} diff --git a/web/src/lib/nostr/inbox-queries.ts b/web/src/lib/nostr/inbox-queries.ts @@ -0,0 +1,17 @@ +import { canonicalPublicKey } from '../contracts/public-key.ts'; +import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts'; +import type { PublicFilter } from './exports.ts'; + +export function inboxPreferenceQueries( + author: unknown +): readonly PublicFilter[] { + const key = canonicalPublicKey(author); + if (!key) throw new Error('inbox_author_invalid'); + return [ + { + kinds: [10050], + authors: [key], + limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay + } + ]; +} diff --git a/web/src/lib/nostr/ingress.ts b/web/src/lib/nostr/ingress.ts @@ -1,5 +1,6 @@ import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; import { boundedEnvelopeNumbers } from './envelope-bounds.ts'; +import { decodedInboxWire } from './decoded-inbox-wire.ts'; import { boundedEnvelopeTags, verifyEnvelope, @@ -18,7 +19,7 @@ export type IngressStats = Readonly<{ stopped: boolean; }>; interface Owner { - readonly admit: (input: unknown) => IngressResult; + readonly admit: (input: unknown, inbox?: boolean) => IngressResult; readonly stats: () => IngressStats; } const owners = new WeakMap<PublicIngress, Owner>(); @@ -141,7 +142,7 @@ export function createPublicIngress(): PublicIngress { chargedBytes: chargedBytes, stopped: stopped }), - admit(input) { + admit(input, inbox = false) { if (stopped || deliveries >= PUBLIC_INGRESS_BUDGETS.deliveries) { stopped = true; return { status: 'limit' }; @@ -159,7 +160,9 @@ export function createPublicIngress(): PublicIngress { const rawAvailable = typeof input === 'string'; const wire = rawAvailable ? input - : reconstructedWire(input, assertActive); + : inbox + ? decodedInboxWire(input, assertActive) + : reconstructedWire(input, assertActive); if (stopped) { charge(PUBLIC_INGRESS_BUDGETS.eventBytes + 1); return { status: 'limit' }; @@ -208,3 +211,10 @@ export function admitPublicEvent( export function publicIngressStats(token: PublicIngress): IngressStats { return ownerOf(token).stats(); } + +export function admitInboxEvent( + token: PublicIngress, + input: unknown +): IngressResult { + return ownerOf(token).admit(input, true); +} diff --git a/web/src/lib/nostr/request-result.ts b/web/src/lib/nostr/request-result.ts @@ -1,8 +1,10 @@ import { PUBLIC_INGRESS_BUDGETS, + PUBLIC_QUERY_BUDGETS, PUBLIC_NIP50_BUDGETS } from '../config/budgets.ts'; import { requireNip50Source } from './search-sources.ts'; +import { canonicalPublicKey } from '../contracts/public-key.ts'; import { publicRelayTargets, type RelayPolicy } from '../config/relays.ts'; import { createObservationContext, @@ -13,6 +15,7 @@ import { } from '../catalog/observations.ts'; import { admitPublicEvent, + admitInboxEvent, publicIngressStats, type PublicIngress } from './ingress.ts'; @@ -40,6 +43,12 @@ export type RequestSnapshot = Readonly<{ coverage: 'bounded-eose' | 'partial'; definitiveAbsence: false; inactive: boolean; + inbox?: Readonly<{ author: string; heads: readonly InboxSourceHead[] }>; +}>; +export type InboxSourceHead = Readonly<{ + source: string; + id: string; + createdAt: number; }>; export type RequestMessageResult = | Readonly<{ status: 'accepted' | 'duplicate'; value: VerifiedEnvelope }> @@ -109,6 +118,25 @@ export function createPublicRequestResult( journal: ObservationJournal, sampleSource?: string ): PublicRequestResult { + return createResult(policy, ingress, journal, sampleSource); +} +export function createInboxRequestResult( + policy: RelayPolicy, + ingress: PublicIngress, + journal: ObservationJournal, + author: unknown +): PublicRequestResult { + const key = canonicalPublicKey(author); + if (!key) throw new Error('inbox_author_invalid'); + return createResult(policy, ingress, journal, undefined, key); +} +function createResult( + policy: RelayPolicy, + ingress: PublicIngress, + journal: ObservationJournal, + sampleSource?: string, + inboxAuthor?: string +): PublicRequestResult { publicIngressStats(ingress); const allOrigins = publicRelayTargets(policy, 'read'); const expected = observationSourceOrigins(journal); @@ -127,8 +155,10 @@ export function createPublicRequestResult( const context = createObservationContext(journal); runIngress.set(journal, ingress); const sources = new Map<string, ReturnType<typeof sourceOwner>>(); + const heads = new Map<string, InboxSourceHead>(); for (const source of origins) sources.set(source, sourceOwner(source)); let inactive = false; + let unknownDelivery = false; const owner: Owner = { handle(message) { if (inactive) return { status: 'inactive' }; @@ -139,9 +169,14 @@ export function createPublicRequestResult( ); const source = origin === undefined ? undefined : sources.get(origin); if (message.type === 'EVENT') { - const admitted = admitPublicEvent(ingress, message.event); - if (!source || origin === undefined) + const admitted = + inboxAuthor === undefined + ? admitPublicEvent(ingress, message.event) + : admitInboxEvent(ingress, message.event); + if (!source || origin === undefined) { + unknownDelivery = true; return { status: 'source_unknown' }; + } const pending = source.state() === 'pending'; source.candidate(); // Preserve the inclusive100th admitted delivery, then settle this sample @@ -152,6 +187,11 @@ export function createPublicRequestResult( PUBLIC_NIP50_BUDGETS.candidatesPerSource ) source.control('limit'); + if ( + inboxAuthor !== undefined && + source.snapshot().candidates >= PUBLIC_QUERY_BUDGETS.requestedPerRelay + ) + source.control('limit'); if (admitted.status === 'limit') { source.control('limit'); return { status: 'limit' }; @@ -166,16 +206,35 @@ export function createPublicRequestResult( } if (!('value' in admitted)) return { status: 'rejected' }; const event = verifiedEnvelopeSnapshot(admitted.value); - if (!event || !isPublicEnvelopeKind(event.kind)) { + if ( + !event || + (inboxAuthor === undefined + ? !isPublicEnvelopeKind(event.kind) + : event.kind !== 10050 || event.pubkey !== inboxAuthor) + ) { source.reject(); return { status: 'not_public' }; } if ( + inboxAuthor === undefined && !recordPublicObservation(journal, context, origin, admitted.value) ) { source.control('limit'); return { status: 'limit' }; } + if (inboxAuthor !== undefined) { + const previous = heads.get(origin); + if ( + !previous || + event.created_at > previous.createdAt || + (event.created_at === previous.createdAt && event.id < previous.id) + ) + heads.set(origin, { + source: origin, + id: event.id, + createdAt: event.created_at + }); + } source.admit(admitted.status === 'duplicate'); // Record exact source evidence BEFORE any caller inserts/deduplicates into // EventStore. Only verified proof leaves this boundary, never SDK metadata. @@ -192,13 +251,22 @@ export function createPublicRequestResult( const outcomes = Array.from(sources.values(), (row) => row.snapshot()); const complete = outcomes.length > 0 && + (inboxAuthor === undefined || !unknownDelivery) && outcomes.every((row) => row.state === 'eose' && row.rejected === 0); return { context: context, sources: outcomes, coverage: complete ? 'bounded-eose' : 'partial', definitiveAbsence: false, - inactive: inactive + inactive: inactive, + ...(inboxAuthor === undefined + ? {} + : { + inbox: { + author: inboxAuthor, + heads: Array.from(heads.values(), (row) => ({ ...row })) + } + }) }; }, dispose() { diff --git a/web/src/lib/nostr/request-scope.ts b/web/src/lib/nostr/request-scope.ts @@ -1,5 +1,6 @@ import { PUBLIC_REQUEST_BUDGETS } from '../config/budgets.ts'; import type { RelayPolicy } from '../config/relays.ts'; +import { canonicalPublicKey } from '../contracts/public-key.ts'; import { requireNip50Source } from './search-sources.ts'; import { createPublicIngress, @@ -14,6 +15,7 @@ import { } from '../catalog/observations.ts'; import { createPublicRequestResult, + createInboxRequestResult, handlePublicRequestMessage, publicRequestSnapshot, disposePublicRequestResult, @@ -27,7 +29,7 @@ declare const requestBrand: unique symbol; export type PublicScheduler = Readonly<{ readonly [schedulerBrand]: true }>; export type PublicRun = Readonly<{ readonly [runBrand]: true }>; export type PublicRequest = Readonly<{ readonly [requestBrand]: true }>; -export type RequestKind = 'search' | 'head' | 'deletion' | 'profile'; +export type RequestKind = 'search' | 'head' | 'deletion' | 'profile' | 'inbox'; export type RequestState = 'active' | 'eose' | 'partial' | 'cancelled' | 'deadline' | 'limit' | 'error'; export interface RequestClock { @@ -65,7 +67,8 @@ interface RunOwner { kind: RequestKind, open: (next: (message: PublicPoolMessage) => void) => () => void, onVerified: (event: VerifiedEnvelope) => void, - sampleSource?: string + sampleSource?: string, + inboxAuthor?: string ) => PublicRequest; readonly active: () => boolean; readonly snapshot: () => Readonly<{ @@ -84,6 +87,7 @@ interface RequestOwner { kind: RequestKind; deadline: number; state: RequestState; + inboxSettled?: boolean; result: ReturnType<typeof publicRequestSnapshot>; }>; readonly close: () => boolean; @@ -208,14 +212,18 @@ export function createPublicRun( }), cancel, dispose, - open(kind, open, onVerified, sampleSource) { + open(kind, open, onVerified, sampleSource, inboxAuthor) { + if (kind === 'inbox' && !canonicalPublicKey(inboxAuthor)) + throw new Error('inbox_author_invalid'); + if (kind !== 'inbox' && inboxAuthor !== undefined) + throw new Error('inbox_request_kind_invalid'); if (sampleSource !== undefined) { if (kind !== 'search') throw new Error('nip50_request_kind'); requireNip50Source(policy, sampleSource); } shared.available(); if (!owner.active()) throw new Error('public_run_inactive'); - if (!['search', 'head', 'deletion', 'profile'].includes(kind)) + if (!['search', 'head', 'deletion', 'profile', 'inbox'].includes(kind)) throw new Error('public_request_kind_invalid'); const request = Object.freeze({}) as PublicRequest; const expires = Math.min( @@ -233,12 +241,10 @@ export function createPublicRun( shared.reserve(request, () => finish('cancelled')); let result: PublicRequestResult; try { - result = createPublicRequestResult( - policy, - ingress, - journal, - sampleSource - ); + result = + inboxAuthor === undefined + ? createPublicRequestResult(policy, ingress, journal, sampleSource) + : createInboxRequestResult(policy, ingress, journal, inboxAuthor); } catch { shared.release(request); throw new Error('public_request_prepare_failed'); @@ -281,6 +287,7 @@ export function createPublicRun( kind: kind, deadline: expires, state: state, + ...(kind === 'inbox' ? { inboxSettled: cleanupComplete } : {}), result: publicRequestSnapshot(result) }), close: () => finish('cancelled') @@ -377,6 +384,16 @@ export function closePublicRequest(request: PublicRequest): void { if (!requestOf(request).close()) throw new Error('public_request_close_failed'); } +export function openInboxRequest( + run: PublicRun, + author: unknown, + open: (next: (message: PublicPoolMessage) => void) => () => void, + onVerified: (event: VerifiedEnvelope) => void +): PublicRequest { + const key = canonicalPublicKey(author); + if (!key) throw new Error('inbox_author_invalid'); + return runOf(run).open('inbox', open, onVerified, undefined, key); +} export function cancelPublicRun(run: PublicRun): void { if (!runOf(run).cancel()) throw new Error('public_run_close_failed'); } diff --git a/web/src/lib/nostr/verified-envelope.ts b/web/src/lib/nostr/verified-envelope.ts @@ -168,3 +168,11 @@ export function verifiedEnvelopeSnapshot( const raw = snapshots.get(token); return raw === undefined ? undefined : (JSON.parse(raw) as NostrEvent); } + +// Genuine proof-owned input only. SDK object ingress records reconstructed +// decoded JSON; callers must not mislabel that as original transport bytes. +export function verifiedEnvelopeWire( + token: VerifiedEnvelope +): string | undefined { + return snapshots.get(token); +} diff --git a/web/src/lib/runtime/public-runtime.ts b/web/src/lib/runtime/public-runtime.ts @@ -20,6 +20,7 @@ import { createPublicScheduler, createPublicRun, openPublicRequest, + openInboxRequest, disposePublicRun, closePublicScheduler, publicRunSnapshot, @@ -30,6 +31,7 @@ import { type RequestClock } from '../nostr/request-scope.ts'; import type { PublicFilter } from '../nostr/exports.ts'; +import { inboxPreferenceQueries } from '../nostr/inbox-queries.ts'; import { publicHeadEnvelope, publicHeadSnapshot, @@ -369,6 +371,27 @@ export function publicViewNip50Sources(view: PublicView): readonly string[] { return qualifiedNip50Sources(viewOf(view).runtime.policy); } +// Public metadata, dedicated ownership: no preference enters the food store. +// Fixed anonymous origins, clocks, scheduler and aggregate ingress stay shared. +export function subscribeInboxPreference( + view: PublicView, + run: PublicRun, + author: unknown, + onVerified: (event: VerifiedEnvelope) => void +): PublicRequest { + const owner = viewOf(view), + filters = inboxPreferenceQueries(author); + if (!owner.current(run)) throw new Error('public_view_run_inactive'); + return openInboxRequest( + run, + author, + (next) => subscribePublicPool(owner.runtime.pool, filters, next), + (event) => { + if (owner.current(run)) onVerified(event); + } + ); +} + // Capacity invalidation differs from ordinary teardown: last-known snapshots // remain available on normal close, while a breached working set clears all views. export function publicViewProjectionAvailable(view: PublicView): boolean { diff --git a/web/tests/integration/inbox-discovery.test.ts b/web/tests/integration/inbox-discovery.test.ts @@ -0,0 +1,214 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import WebSocket, { WebSocketServer } from 'ws'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { + createPublicRuntimeContext, + mountPublicRuntime, + createPublicView, + beginPublicViewRun, + subscribePublicView, + closePublicRuntime +} from '../../src/lib/runtime/public-runtime.ts'; +import { + resolveInboxPreference, + inboxResolutionSnapshot +} from '../../src/lib/messaging/resolve-inbox.ts'; +import { inboxPreferenceWire } from '../../src/lib/nostr/inbox-preferences.ts'; +import { publicRunSnapshot } from '../../src/lib/nostr/request-scope.ts'; + +void test('actual anonymous SDK discovers only fixed recipient10050 sources and preserves decoded extras independently of public catalog', async () => { + const origins = ['wss://one.example.org', 'wss://two.example.org']; + const key = crypto.getRandomValues(new Uint8Array(32)); + let old, newer, profile; + try { + old = finalizeEvent( + { + kind: 10050, + created_at: 100, + tags: [ + ['relay', origins[0]], + ['unknown', 'keep'] + ], + content: 'original' + }, + key + ); + newer = finalizeEvent( + { kind: 10050, created_at: 200, tags: [['relay']], content: '' }, + key + ); + profile = finalizeEvent( + { kind: 0, created_at: 100, tags: [], content: '{}' }, + key + ); + } finally { + key.fill(0); + } + const servers = origins.map( + () => new WebSocketServer({ host: '127.0.0.1', port: 0, maxPayload: 8192 }) + ); + const sockets: WebSocket[] = [], + requests: { origin: string; filter: unknown }[] = []; + let closed = 0, + catalogSeen = () => {}, + allClosed = () => {}, + nextClosed = () => {}; + const seen = [0, 0]; + const catalog = new Promise<void>((resolve) => { + catalogSeen = resolve; + }), + finished = new Promise<void>((resolve) => { + allClosed = resolve; + }), + nextFinished = new Promise<void>((resolve) => { + nextClosed = resolve; + }); + for (let index = 0; index < servers.length; index++) + servers[index].on('connection', (socket) => { + sockets.push(socket); + socket.on('message', (bytes) => { + const buffer = Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes); + const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; + if (frame[0] === 'REQ') { + const filter = frame[2] as { + kinds: number[]; + authors?: string[]; + limit: number; + }; + requests.push({ origin: origins[index], filter }); + const id = String(frame[1]); + if (filter.kinds[0] === 10050) { + seen[index]++; + assert.deepEqual(filter, { + kinds: [10050], + authors: [old.pubkey], + limit: 200 + }); + socket.send( + JSON.stringify([ + 'EVENT', + id, + seen[index] > 1 || index === 0 + ? { ...old, extra: { items: ['keep', null, true] } } + : newer + ]) + ); + socket.send(JSON.stringify(['EOSE', id])); + } else { + socket.send(JSON.stringify(['EVENT', id, profile])); + } + } else if (frame[0] === 'CLOSE') { + closed++; + if (closed === 2) allClosed(); + if (closed === 4) nextClosed(); + } + assert.notEqual(frame[0], 'AUTH'); + assert.notEqual(frame[0], 'EVENT'); + }); + }); + await Promise.all(servers.map((server) => once(server, 'listening'))); + const ports = servers.map((server) => { + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + return address.port; + }); + const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), + oldSocket = globalThis.WebSocket; + class FixtureSocket extends WebSocket { + constructor(url: string | URL) { + const index = origins.indexOf(String(url).replace(/\/$/, '')); + assert.ok(index >= 0); + super(`ws://127.0.0.1:${ports[index]}`); + } + } + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + globalThis.WebSocket = + FixtureSocket as unknown as typeof globalThis.WebSocket; + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: origins.map((origin) => ({ + origin, + read: true, + write: false, + nip50: false + })), + inbox: [{ origin: 'wss://archive.example.org', read: true, write: true }], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + const context = createPublicRuntimeContext(), + runtime = mountPublicRuntime(context, policy)!, + view = createPublicView(runtime), + run = beginPublicViewRun(view), + catalogView = createPublicView(runtime), + catalogRun = beginPublicViewRun(catalogView); + try { + subscribePublicView( + catalogView, + catalogRun, + 'profile', + [{ kinds: [0], authors: [old.pubkey], limit: 200 }], + () => catalogSeen() + ); + const resolver = resolveInboxPreference(view, run, old.pubkey); + await Promise.all([finished, catalog]); + const result = inboxResolutionSnapshot(resolver); + assert.equal(result.status, 'unsupported'); + assert.equal(result.knownBase?.id, newer.id); + assert.equal(result.coverage, 'bounded-eose'); + assert.equal(result.sources.length, 2); + assert.equal(publicRunSnapshot(run).ingress.deliveries, 2); + assert.ok(publicRunSnapshot(catalogRun).active); + const another = beginPublicViewRun(view); + assert.equal(inboxResolutionSnapshot(resolver).status, 'inconclusive'); + assert.ok(publicRunSnapshot(another).active); + const compatible = resolveInboxPreference(view, another, old.pubkey); + assert.equal(resolveInboxPreference(view, another, old.pubkey), compatible); + await nextFinished; + const compatibleResult = inboxResolutionSnapshot(compatible); + assert.equal(compatibleResult.status, 'ready'); + assert.equal(compatibleResult.knownBase?.id, old.id); + const preserved: unknown = JSON.parse( + inboxPreferenceWire(compatibleResult.head!)! + ); + assert.deepEqual(preserved, { + ...(JSON.parse(JSON.stringify(old)) as object), + extra: { items: ['keep', null, true] } + }); + assert.equal( + requests.filter( + (row) => (row.filter as { kinds: number[] }).kinds[0] === 10050 + ).length, + 4 + ); + assert.equal(result.wireProvenance, 'decoded-sdk-json'); + assert.ok(inboxPreferenceWire(result.head!)?.includes('"relay"')); + } finally { + closePublicRuntime(context); + for (const socket of sockets) socket.terminate(); + await Promise.all( + servers.map( + (server) => + new Promise<void>((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())) + ) + ) + ); + globalThis.WebSocket = oldSocket; + if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); + else Reflect.deleteProperty(globalThis, 'window'); + } +}); diff --git a/web/tests/unit/inbox-resolution.test.ts b/web/tests/unit/inbox-resolution.test.ts @@ -0,0 +1,463 @@ +import { describe, it, expect } from 'vitest'; +import { finalizeEvent } from 'applesauce-core/helpers'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { + createPublicScheduler, + createPublicRun, + openInboxRequest, + openPublicRequest, + closePublicScheduler, + publicRunSnapshot, + publicRunObservations, + publicSchedulerSnapshot, + type RequestClock +} from '../../src/lib/nostr/request-scope.ts'; +import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts'; +import { + createInboxResolver, + inboxResolutionSnapshot, + closeInboxResolver +} from '../../src/lib/messaging/resolve-inbox.ts'; +import { + inboxPreferenceWire, + inboxPreferenceSnapshot +} from '../../src/lib/nostr/inbox-preferences.ts'; +import { inboxPreferenceQueries } from '../../src/lib/nostr/inbox-queries.ts'; +const origins = ['wss://one.example.org', 'wss://two.example.org']; +function signed() { + const key = crypto.getRandomValues(new Uint8Array(32)); + try { + const old = finalizeEvent( + { + kind: 10050, + created_at: 100, + tags: [ + ['relay', origins[0]], + ['unknown', 'keep'] + ], + content: 'preserve' + }, + key + ); + const newer = finalizeEvent( + { kind: 10050, created_at: 200, tags: [['relay']], content: '' }, + key + ); + const tie = finalizeEvent( + { + kind: 10050, + created_at: 100, + tags: [['relay', origins[1]]], + content: '' + }, + key + ); + const unrelated = finalizeEvent( + { kind: 10002, created_at: 300, tags: [['r', origins[0]]], content: '' }, + key + ); + return { old, newer, tie, unrelated }; + } finally { + key.fill(0); + } +} +function setup(author: string, sources = origins, stopFailures = 0) { + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: sources.map((origin) => ({ + origin, + read: true, + write: false, + nip50: false + })), + inbox: [{ origin: 'wss://archive.example.org', read: true, write: true }], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + let now = 0, + stops = 0; + let clockHook: (() => void) | undefined; + const timers = new Map<() => void, () => void>(); + const clock: RequestClock = { + now: () => { + const hook = clockHook; + clockHook = undefined; + hook?.(); + return now; + }, + schedule(callback) { + const cancel = () => { + timers.delete(cancel); + }; + timers.set(cancel, callback); + return cancel; + } + }; + const scheduler = createPublicScheduler(clock), + run = createPublicRun(scheduler, policy); + let sink: (message: PublicPoolMessage) => void = () => {}, + current = true; + const resolver = createInboxResolver( + run, + author, + (next) => + openInboxRequest( + run, + author, + (callback) => { + sink = callback; + return () => { + stops++; + if (stops <= stopFailures) + throw new Error('fixture_cleanup_failed'); + }; + }, + next + ), + () => current + ); + return { + resolver, + scheduler, + run, + emit(message: PublicPoolMessage) { + sink(message); + }, + eose() { + for (const from of sources) sink({ type: 'EOSE', from, id: 'fixture' }); + }, + stale() { + current = false; + }, + duringClock(callback: () => void) { + clockHook = callback; + }, + expire() { + now = 10001; + for (const callback of [...timers.values()]) callback(); + }, + stops: () => stops + }; +} +function event( + from: string, + value: ReturnType<typeof signed>['old'] +): PublicPoolMessage { + return { type: 'EVENT', from, id: 'fixture', event: value }; +} +describe('bounded recipient preference discovery', () => { + it('rechecks current generation after the injected clock synchronously invalidates discovery ownership', () => { + const f = signed(), + s = setup(f.old.pubkey); + try { + s.emit(event(origins[0], f.old)); + s.eose(); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('ready'); + s.duringClock(() => s.stale()); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('cleanup failure cannot enable ready and explicit close retries retained admission', () => { + const f = signed(), + s = setup(f.old.pubkey, origins, 1); + try { + s.emit(event(origins[0], f.old)); + s.eose(); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + expect(publicSchedulerSnapshot(s.scheduler).activeRequests).toBe(1); + closeInboxResolver(s.resolver); + expect(publicSchedulerSnapshot(s.scheduler).activeRequests).toBe(0); + expect(s.stops()).toBe(2); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('rejects non-JSON extras, cycles, huge decoded fields and reentrant descriptor traps under shared ingress bounds', () => { + const f = signed(); + let getterCalls = 0; + const cycle: Record<string, unknown> = {}; + cycle.self = cycle; + for (const extra of [ + () => { + getterCalls++; + return 'unsafe'; + }, + cycle, + 'x'.repeat(262145), + { + get nested() { + getterCalls++; + return 'unsafe'; + } + } + ]) { + const s = setup(f.old.pubkey); + try { + const candidate = { ...f.old, extra }; + s.emit(event(origins[0], candidate)); + s.eose(); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(1); + } finally { + closePublicScheduler(s.scheduler); + } + } + expect(getterCalls).toBe(0); + const s = setup(f.old.pubkey); + let entered = false; + try { + const hostile = new Proxy( + { ...f.old }, + { + getOwnPropertyDescriptor(target, name) { + if (!entered) { + entered = true; + s.emit(event(origins[0], f.old)); + } + return Reflect.getOwnPropertyDescriptor(target, name); + } + } + ); + s.emit(event(origins[0], hostile)); + expect(publicRunSnapshot(s.run).ingress).toMatchObject({ + stopped: true, + deliveries: 2 + }); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('fixes exact kind and author without time filters or sender routing', () => { + const f = signed(); + expect(inboxPreferenceQueries(f.old.pubkey)).toEqual([ + { kinds: [10050], authors: [f.old.pubkey], limit: 200 } + ]); + expect(() => inboxPreferenceQueries('f'.repeat(64))).toThrow( + 'inbox_author_invalid' + ); + }); + it('requires every admitted fixed source and never caches degraded empty lookup as missing', () => { + const f = signed(), + s = setup(f.old.pubkey); + try { + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + s.emit({ type: 'EOSE', from: origins[0], id: 'fixture' }); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + s.eose(); + expect(inboxResolutionSnapshot(s.resolver)).toMatchObject({ + status: 'missing', + coverage: 'bounded-eose', + definitiveAbsence: false + }); + s.stale(); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('empty discovery manifest stays inconclusive without falling back to configured archive', () => { + const f = signed(), + s = setup(f.old.pubkey, []); + try { + expect(inboxResolutionSnapshot(s.resolver)).toMatchObject({ + status: 'inconclusive', + sources: [] + }); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('new verified incompatible head blocks older compatible preference and retains both source versions', () => { + const f = signed(), + s = setup(f.old.pubkey); + try { + s.emit(event(origins[0], f.old)); + s.emit(event(origins[1] + '/', f.newer)); + s.eose(); + const r = inboxResolutionSnapshot(s.resolver); + expect(r.status).toBe('unsupported'); + expect(inboxPreferenceSnapshot(r.head!)?.id).toBe(f.newer.id); + expect(r.knownBase).toEqual({ + author: f.old.pubkey, + id: f.newer.id, + createdAt: 200 + }); + expect(r.sources.map((row) => row.head?.id)).toEqual([ + f.old.id, + f.newer.id + ]); + expect(publicRunObservations(s.run, r.request)).toEqual([]); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('selects timestamp then lower ID deterministically independently of arrival order', () => { + const f = signed(); + for (const rows of [ + [f.old, f.tie], + [f.tie, f.old] + ]) { + const s = setup(f.old.pubkey); + try { + for (const row of rows) s.emit(event(origins[0], row)); + s.eose(); + const r = inboxResolutionSnapshot(s.resolver); + expect(r.status).toBe('ready'); + expect(r.knownBase?.id).toBe([f.old.id, f.tie.id].sort()[0]); + } finally { + closePublicScheduler(s.scheduler); + } + } + }); + it('preserves decoded unknown JSON and signed tags without trusting getters or cached SDK metadata', () => { + const f = signed(), + s = setup(f.old.pubkey); + try { + const extra = { + ...f.old, + extra: { nested: [null, true, 1, 'untrusted'] } + }; + s.emit(event(origins[0], extra)); + s.eose(); + const r = inboxResolutionSnapshot(s.resolver); + expect(r.status).toBe('ready'); + const raw: unknown = JSON.parse(inboxPreferenceWire(r.head!)!); + expect(raw).toEqual(JSON.parse(JSON.stringify(extra))); + expect(Object.getOwnPropertySymbols(raw as object)).toHaveLength(0); + r.sources.pop(); + expect(inboxResolutionSnapshot(s.resolver).sources).toHaveLength(2); + expect(r.wireProvenance).toBe('decoded-sdk-json'); + } finally { + closePublicScheduler(s.scheduler); + } + const t = setup(f.old.pubkey); + let reads = 0; + try { + const hostile = { + ...f.old, + get extra() { + reads++; + throw new Error('unsafe'); + } + }; + t.emit(event(origins[0], hostile)); + t.eose(); + expect(reads).toBe(0); + expect(inboxResolutionSnapshot(t.resolver).status).toBe('inconclusive'); + } finally { + closePublicScheduler(t.scheduler); + } + }); + it('rejects wrong author, wrong kind and bad signature without turning a partial lookup ready or missing', () => { + const f = signed(), + other = signed(); + for (const bad of [ + other.old, + f.unrelated, + { ...f.old, sig: '0'.repeat(128) } + ]) { + const s = setup(f.old.pubkey); + try { + s.emit(event(origins[0], bad)); + s.eose(); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(1); + } finally { + closePublicScheduler(s.scheduler); + } + } + }); + it('saturation and failed source prevent bounded readiness despite a valid known head', () => { + const f = signed(), + s = setup(f.old.pubkey); + try { + for (let i = 0; i < 200; i++) s.emit(event(origins[0], f.old)); + s.eose(); + const r = inboxResolutionSnapshot(s.resolver); + expect(r.status).toBe('inconclusive'); + expect(r.knownBase?.id).toBe(f.old.id); + expect(r.sources[0]).toMatchObject({ state: 'limit', candidates: 200 }); + expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(200); + } finally { + closePublicScheduler(s.scheduler); + } + const t = setup(f.old.pubkey); + try { + t.emit(event(origins[0], f.old)); + t.emit({ + type: 'ERROR', + from: origins[1], + error: new Error('untrusted') + }); + t.emit({ type: 'EOSE', from: origins[0], id: 'fixture' }); + expect(inboxResolutionSnapshot(t.resolver).status).toBe('inconclusive'); + } finally { + closePublicScheduler(t.scheduler); + } + }); + it('unknown source never supplies preference authority and deadline/close revoke readiness', () => { + const f = signed(), + s = setup(f.old.pubkey); + try { + s.emit(event('wss://hint.example.org', f.old)); + s.expire(); + expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive'); + expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(1); + s.emit(event(origins[0], f.old)); + expect(inboxResolutionSnapshot(s.resolver).head).toBeUndefined(); + closeInboxResolver(s.resolver); + expect(s.stops()).toBe(1); + } finally { + closePublicScheduler(s.scheduler); + } + }); + it('shares six-scope concurrency and forbids generic inbox mode before effects', () => { + const f = signed(), + s = setup(f.old.pubkey); + let effects = 0; + try { + for (let i = 0; i < 5; i++) + openPublicRequest( + s.run, + 'profile', + () => { + effects++; + return () => {}; + }, + () => {} + ); + expect(() => + openInboxRequest( + s.run, + f.old.pubkey, + () => { + effects++; + return () => {}; + }, + () => {} + ) + ).toThrow('public_request_concurrency_limit'); + expect(effects).toBe(5); + expect(publicSchedulerSnapshot(s.scheduler).activeRequests).toBe(6); + expect(() => + openPublicRequest( + s.run, + 'inbox', + () => { + effects++; + return () => {}; + }, + () => {} + ) + ).toThrow('inbox_author_invalid'); + } finally { + closePublicScheduler(s.scheduler); + } + }); +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -415,7 +415,7 @@ async function productPresentationAdmission(web) { 'src/lib/navigation-copy.ts': '1a17eac4b355d8a3fb2b55b3fe1bc856cc3b3bce07434836d708b68407686f20', 'src/lib/runtime/public-runtime.ts': - 'f1b1b7b58fdd33d844831e05f5ee84f7195b7ab097d6fdd3934847e697814f90', + '7098e5333fc25b6c6238676d177e2f38d7862c679f52b16926aace7cbff367b8', 'src/lib/catalog/publishers.ts': 'a6795a35ebbf97246e22235df1ca868432e2cccfb26a38f0ebdf4524911192e6', 'src/lib/catalog/resolve-head.ts':