app

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

commit 54f184735ff4c769d94945781a136a5f035bc08f
parent cfdddcfb578b2a71d928b3abeaf683fa0547464c
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 10:44:13 +0000

web: Add owned bounded request handles and teardown (HCP-032)

- Share approved request concurrency and absolute run deadlines
- Isolate stale generations and retry failed cleanup controls
- Admit exact root SDK output with bounded byte readers
- Verify regression and SDK behavior while preserving native inputs

Diffstat:
Mweb/src/lib/config/budgets.ts | 7+++++++
Aweb/src/lib/nostr/request-scope.ts | 393+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/src/lib/runtime/public-runtime.ts | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/routes/+layout.svelte | 15++++++++++++++-
Aweb/tests/integration/public-runtime.test.ts | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/output.test.mjs | 273++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aweb/tests/unit/public-runtime.test.ts | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tests/unit/request-scope.test.ts | 442+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/check-output.mjs | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
9 files changed, 1873 insertions(+), 20 deletions(-)

diff --git a/web/src/lib/config/budgets.ts b/web/src/lib/config/budgets.ts @@ -9,3 +9,10 @@ export const PUBLIC_INGRESS_BUDGETS = Object.freeze({ processedBytes: 8388608, eventBytes: 262144 }); + +// Shared by primary discovery and every auxiliary head/deletion/profile scope. +export const PUBLIC_REQUEST_BUDGETS = Object.freeze({ + parallelScopes: 6, + runMilliseconds: 15000, + requestMilliseconds: 10000 +}); diff --git a/web/src/lib/nostr/request-scope.ts b/web/src/lib/nostr/request-scope.ts @@ -0,0 +1,393 @@ +import { PUBLIC_REQUEST_BUDGETS } from '../config/budgets.ts'; +import type { RelayPolicy } from '../config/relays.ts'; +import { + createPublicIngress, + publicIngressStats, + type PublicIngress +} from './ingress.ts'; +import { + createObservationJournal, + closeObservationJournal, + publicObservations, + type ObservationJournal +} from '../catalog/observations.ts'; +import { + createPublicRequestResult, + handlePublicRequestMessage, + publicRequestSnapshot, + disposePublicRequestResult, + type PublicRequestResult +} from './request-result.ts'; +import type { PublicPoolMessage } from './exports.ts'; +import type { VerifiedEnvelope } from './verified-envelope.ts'; +declare const schedulerBrand: unique symbol; +declare const runBrand: unique symbol; +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 RequestState = + 'active' | 'eose' | 'partial' | 'cancelled' | 'deadline' | 'limit' | 'error'; +export interface RequestClock { + readonly now: () => number; + readonly schedule: (callback: () => void, delay: number) => () => void; +} +const browserClock: RequestClock = { + now: () => performance.now(), + schedule(callback, delay) { + const timer = setTimeout(() => callback(), delay); + return () => clearTimeout(timer); + } +}; +interface SchedulerOwner { + readonly now: () => number; + readonly schedule: RequestClock['schedule']; + readonly available: () => void; + readonly reserve: (token: PublicRequest, close: () => boolean) => void; + readonly release: (token: PublicRequest) => void; + readonly register: (token: PublicRun, dispose: () => boolean) => void; + readonly unregister: (token: PublicRun) => void; + readonly snapshot: () => Readonly<{ + activeRequests: number; + closed: boolean; + }>; + readonly close: () => void; +} +interface RunOwner { + readonly scheduler: SchedulerOwner; + readonly ingress: PublicIngress; + readonly journal: ObservationJournal; + readonly deadline: number; + readonly result: (request: PublicRequest) => PublicRequestResult; + readonly open: ( + kind: RequestKind, + open: (next: (message: PublicPoolMessage) => void) => () => void, + onVerified: (event: VerifiedEnvelope) => void + ) => PublicRequest; + readonly active: () => boolean; + readonly snapshot: () => Readonly<{ + deadline: number; + active: boolean; + activeRequests: number; + ingress: ReturnType<typeof publicIngressStats>; + }>; + readonly cancel: () => boolean; + readonly dispose: () => boolean; +} +interface RequestOwner { + readonly run: PublicRun; + readonly result: PublicRequestResult; + readonly snapshot: () => Readonly<{ + kind: RequestKind; + deadline: number; + state: RequestState; + result: ReturnType<typeof publicRequestSnapshot>; + }>; + readonly close: () => boolean; +} +const schedulers = new WeakMap<PublicScheduler, SchedulerOwner>(); +const runs = new WeakMap<PublicRun, RunOwner>(); +const requests = new WeakMap<PublicRequest, RequestOwner>(); +function schedulerOf(token: PublicScheduler): SchedulerOwner { + const owner = schedulers.get(token); + if (!owner) throw new Error('public_scheduler_invalid'); + return owner; +} +function runOf(token: PublicRun): RunOwner { + const owner = runs.get(token); + if (!owner) throw new Error('public_run_invalid'); + return owner; +} +function requestOf(token: PublicRequest): RequestOwner { + const owner = requests.get(token); + if (!owner) throw new Error('public_request_invalid'); + return owner; +} +export function createPublicScheduler( + clock: RequestClock = browserClock +): PublicScheduler { + const active = new Map<PublicRequest, () => boolean>(), + registered = new Map<PublicRun, () => boolean>(); + let closed = false, + last = 0; + const owner: SchedulerOwner = { + now() { + const value = clock.now(); + if (!Number.isFinite(value) || value < 0) + throw new Error('public_clock_invalid'); + last = Math.max(last, value); + return last; + }, + schedule: (callback, delay) => clock.schedule(callback, delay), + available() { + if (closed) throw new Error('public_scheduler_closed'); + }, + reserve(token, close) { + owner.available(); + if (active.size >= PUBLIC_REQUEST_BUDGETS.parallelScopes) + throw new Error('public_request_concurrency_limit'); + active.set(token, close); + }, + release(token) { + active.delete(token); + }, + register(token, dispose) { + owner.available(); + registered.set(token, dispose); + }, + unregister(token) { + registered.delete(token); + }, + snapshot() { + return { activeRequests: active.size, closed: closed }; + }, + close() { + closed = true; + let failed = false; + for (const dispose of registered.values()) if (!dispose()) failed = true; + for (const close of active.values()) if (!close()) failed = true; + if (failed) throw new Error('public_scheduler_close_failed'); + } + }; + const token = Object.freeze({}) as PublicScheduler; + schedulers.set(token, owner); + return token; +} +// One immutable run owns the aggregate event/byte budget and observation journal. +// All request kinds use the same admission owner; no per-auxiliary budget reset. +export function createPublicRun( + scheduler: PublicScheduler, + policy: RelayPolicy +): PublicRun { + const shared = schedulerOf(scheduler); + shared.available(); + const deadline = shared.now() + PUBLIC_REQUEST_BUDGETS.runMilliseconds; + const ingress = createPublicIngress(), + journal = createObservationJournal(policy), + active = new Map<PublicRequest, () => boolean>(); + let cancelled = false, + disposed = false; + const token = Object.freeze({}) as PublicRun; + function cancel(): boolean { + cancelled = true; + let failed = false; + for (const close of active.values()) if (!close()) failed = true; + return !failed; + } + function dispose(): boolean { + const settled = cancel(); + disposed = true; + closeObservationJournal(journal); + if (settled) shared.unregister(token); + return settled; + } + const owner: RunOwner = { + scheduler: shared, + ingress, + journal, + deadline, + result(request) { + const row = requestOf(request); + if (row.run !== token) throw new Error('public_request_run_changed'); + return row.result; + }, + active: () => + !cancelled && + !disposed && + !shared.snapshot().closed && + shared.now() < deadline && + !publicIngressStats(ingress).stopped, + snapshot: () => ({ + deadline: deadline, + active: owner.active(), + activeRequests: active.size, + ingress: publicIngressStats(ingress) + }), + cancel, + dispose, + open(kind, open, onVerified) { + shared.available(); + if (!owner.active()) throw new Error('public_run_inactive'); + if (!['search', 'head', 'deletion', 'profile'].includes(kind)) + throw new Error('public_request_kind_invalid'); + const request = Object.freeze({}) as PublicRequest; + const expires = Math.min( + deadline, + shared.now() + PUBLIC_REQUEST_BUDGETS.requestMilliseconds + ); + let state: RequestState = 'active', + opening = true, + cleanupComplete = false, + timerCancelled = false, + stopCompleted = false, + stop = () => {}, + cancelTimer = () => {}; + // Reserve before acquiring SDK subscriptions or scheduling their callbacks. + shared.reserve(request, () => finish('cancelled')); + let result: PublicRequestResult; + try { + result = createPublicRequestResult(policy, ingress, journal); + } catch { + shared.release(request); + throw new Error('public_request_prepare_failed'); + } + function finish(next: Exclude<RequestState, 'active'>): boolean { + if (cleanupComplete) return true; + if (state === 'active') state = next; + disposePublicRequestResult(result); + let failed = false; + if (!timerCancelled) { + try { + cancelTimer(); + timerCancelled = true; + } catch { + failed = true; + } + } + if (!opening) { + if (!stopCompleted) { + try { + stop(); + stopCompleted = true; + } catch { + failed = true; + } + } + if (!failed && timerCancelled && stopCompleted) { + cleanupComplete = true; + active.delete(request); + shared.release(request); + } + } + return !failed; + } + active.set(request, () => finish('cancelled')); + requests.set(request, { + run: token, + result, + snapshot: () => ({ + kind: kind, + deadline: expires, + state: state, + result: publicRequestSnapshot(result) + }), + close: () => finish('cancelled') + }); + function next(message: PublicPoolMessage): void { + if (state !== 'active') return; + try { + if (!owner.active()) { + finish(shared.now() >= deadline ? 'deadline' : 'cancelled'); + return; + } + if (shared.now() >= expires) { + finish('deadline'); + return; + } + } catch { + finish('error'); + return; + } + const outcome = handlePublicRequestMessage(result, message); + let callbackFailed = false; + if (outcome.status === 'accepted' || outcome.status === 'duplicate') { + try { + onVerified(outcome.value); + } catch { + finish('error'); + callbackFailed = true; + } + } + if (publicIngressStats(ingress).stopped || outcome.status === 'limit') { + finish('limit'); + cancel(); + return; + } + if (callbackFailed) return; + const sources = publicRequestSnapshot(result).sources; + if ( + sources.length > 0 && + sources.every((row) => row.state !== 'pending') + ) + finish( + sources.every((row) => row.state === 'eose' && row.rejected === 0) + ? 'eose' + : 'partial' + ); + } + function expire(): void { + if (state !== 'active') return; + try { + const remaining = expires - shared.now(); + if (remaining > 0) { + cancelTimer = shared.schedule(() => expire(), remaining); + timerCancelled = false; + return; + } + finish('deadline'); + } catch { + finish('error'); + } + } + try { + cancelTimer = shared.schedule( + () => expire(), + Math.max(0, expires - shared.now()) + ); + // A trusted test scheduler may invoke synchronously before returning its + // control. Ensure the returned control is still settled before release. + timerCancelled = false; + if (state === 'active') stop = open(next); + opening = false; + if (state !== 'active') finish(state); + } catch { + opening = false; + finish('error'); + throw new Error('public_request_open_failed'); + } + return request; + } + }; + runs.set(token, owner); + shared.register(token, dispose); + return token; +} +export function openPublicRequest( + run: PublicRun, + kind: RequestKind, + open: (next: (message: PublicPoolMessage) => void) => () => void, + onVerified: (event: VerifiedEnvelope) => void +): PublicRequest { + return runOf(run).open(kind, open, onVerified); +} +export function closePublicRequest(request: PublicRequest): void { + if (!requestOf(request).close()) + throw new Error('public_request_close_failed'); +} +export function cancelPublicRun(run: PublicRun): void { + if (!runOf(run).cancel()) throw new Error('public_run_close_failed'); +} +export function disposePublicRun(run: PublicRun): void { + if (!runOf(run).dispose()) throw new Error('public_run_close_failed'); +} +export function closePublicScheduler(scheduler: PublicScheduler): void { + schedulerOf(scheduler).close(); +} +export function publicSchedulerSnapshot(scheduler: PublicScheduler) { + return schedulerOf(scheduler).snapshot(); +} +export function publicRunSnapshot(run: PublicRun) { + return runOf(run).snapshot(); +} +export function publicRequestScopeSnapshot(request: PublicRequest) { + return requestOf(request).snapshot(); +} +export function publicRunObservations(run: PublicRun, request: PublicRequest) { + const owner = runOf(run); + const result = owner.result(request); + return publicObservations( + owner.journal, + publicRequestSnapshot(result).context + ); +} diff --git a/web/src/lib/runtime/public-runtime.ts b/web/src/lib/runtime/public-runtime.ts @@ -0,0 +1,254 @@ +import { deploymentRelayPolicy } from '../config/deployment-relays.ts'; +import type { RelayPolicy } from '../config/relays.ts'; +import { + getPublicPool, + subscribePublicPool, + closePublicPool, + type PublicPool +} from '../nostr/public-pool.ts'; +import { + getPublicStore, + insertPublicEnvelope, + closePublicStore, + type PublicStore +} from '../nostr/public-store.ts'; +import { + createPublicScheduler, + createPublicRun, + openPublicRequest, + disposePublicRun, + closePublicScheduler, + publicRunSnapshot, + type PublicScheduler, + type PublicRun, + type PublicRequest, + type RequestKind, + type RequestClock +} from '../nostr/request-scope.ts'; +import type { PublicFilter } from '../nostr/exports.ts'; +import type { VerifiedEnvelope } from '../nostr/verified-envelope.ts'; +declare const contextBrand: unique symbol; +declare const runtimeBrand: unique symbol; +declare const viewBrand: unique symbol; +export type PublicRuntimeContext = Readonly<{ readonly [contextBrand]: true }>; +export type PublicRuntime = Readonly<{ readonly [runtimeBrand]: true }>; +export type PublicView = Readonly<{ readonly [viewBrand]: true }>; +export const PUBLIC_RUNTIME_CONTEXT = 'harvestcircle_public_runtime'; +interface RuntimeOwner { + readonly pool: PublicPool; + readonly store: PublicStore; + readonly scheduler: PublicScheduler; + readonly policy: RelayPolicy; + readonly views: Map<PublicView, () => boolean>; + readonly closed: () => boolean; + readonly close: () => void; +} +interface ContextOwner { + readonly value: () => PublicRuntime | undefined; + readonly mount: ( + policy: RelayPolicy, + clock?: RequestClock + ) => PublicRuntime | undefined; + readonly ready: Promise<PublicRuntime | undefined>; + readonly close: () => void; +} +interface ViewOwner { + readonly runtime: RuntimeOwner; + readonly begin: () => PublicRun; + readonly current: (run: PublicRun) => boolean; + readonly dispose: () => boolean; +} +const contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(), + runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(), + views = new WeakMap<PublicView, ViewOwner>(); +let browserContext: PublicRuntimeContext | undefined; +function contextOf(token: PublicRuntimeContext): ContextOwner { + const owner = contexts.get(token); + if (!owner) throw new Error('public_runtime_context_invalid'); + return owner; +} +function runtimeOf(token: PublicRuntime): RuntimeOwner { + const owner = runtimes.get(token); + if (!owner) throw new Error('public_runtime_invalid'); + if (owner.closed()) throw new Error('public_runtime_closed'); + return owner; +} +function viewOf(token: PublicView): ViewOwner { + const owner = views.get(token); + if (!owner) throw new Error('public_view_invalid'); + return owner; +} +// Context construction is SSR-pure. Root onMount acquires the browser lifetime; +// children can await readiness even when their onMount runs before the root's. +export function createPublicRuntimeContext(): PublicRuntimeContext { + let value: PublicRuntime | undefined, + closed = false; + let ready: (value: PublicRuntime | undefined) => void = () => {}; + let selectedClock: RequestClock | undefined; + const promise = new Promise<PublicRuntime | undefined>((resolve) => { + ready = resolve; + }); + const owner: ContextOwner = { + value: () => (closed ? undefined : value), + ready: promise, + mount(policy, clock) { + if (closed) throw new Error('public_runtime_closed'); + if (typeof window === 'undefined') return undefined; + if (value) { + const prior = runtimes.get(value); + if (!prior || prior.policy !== policy) + throw new Error('public_runtime_policy_changed'); + if (clock !== selectedClock) + throw new Error('public_runtime_clock_changed'); + return value; + } + if (browserContext && browserContext !== contextToken) + throw new Error('public_runtime_owner_changed'); + const pool = getPublicPool(policy), + store = getPublicStore(); + if (!pool || !store) return undefined; + const scheduler = createPublicScheduler(clock), + registered = new Map<PublicView, () => boolean>(); + let terminal = false; + const token = Object.freeze({}) as PublicRuntime; + const runtime: RuntimeOwner = { + pool, + store, + scheduler, + policy, + views: registered, + closed: () => terminal, + close() { + terminal = true; + let failed = false; + for (const dispose of registered.values()) + if (!dispose()) failed = true; + try { + closePublicScheduler(scheduler); + } catch { + failed = true; + } + try { + closePublicPool(pool); + } catch { + failed = true; + } + try { + closePublicStore(store); + } catch { + failed = true; + } + if (failed) throw new Error('public_runtime_close_failed'); + } + }; + runtimes.set(token, runtime); + value = token; + browserContext = contextToken; + selectedClock = clock; + ready(token); + return token; + }, + close() { + closed = true; + ready(undefined); + if (value) { + const runtime = runtimes.get(value); + if (runtime) runtime.close(); + } + } + }; + const contextToken = Object.freeze({}) as PublicRuntimeContext; + contexts.set(contextToken, owner); + return contextToken; +} +export function publicRuntime( + context: PublicRuntimeContext +): PublicRuntime | undefined { + return contextOf(context).value(); +} +export function publicRuntimeReady( + context: PublicRuntimeContext +): Promise<PublicRuntime | undefined> { + return contextOf(context).ready; +} +export function mountPublicRuntime( + context: PublicRuntimeContext, + policy: RelayPolicy = deploymentRelayPolicy, + clock?: RequestClock +): PublicRuntime | undefined { + return contextOf(context).mount(policy, clock); +} +export function closePublicRuntime(context: PublicRuntimeContext): void { + contextOf(context).close(); +} +export function createPublicView(runtime: PublicRuntime): PublicView { + const shared = runtimeOf(runtime), + token = Object.freeze({}) as PublicView; + let run: PublicRun | undefined, + disposed = false; + const owner: ViewOwner = { + runtime: shared, + begin() { + if (disposed || shared.closed()) throw new Error('public_view_closed'); + if (run) disposePublicRun(run); + run = createPublicRun(shared.scheduler, shared.policy); + return run; + }, + current(candidate) { + return !disposed && !shared.closed() && run === candidate; + }, + dispose() { + disposed = true; + try { + if (run) disposePublicRun(run); + shared.views.delete(token); + return true; + } catch { + return false; + } + } + }; + views.set(token, owner); + shared.views.set(token, () => owner.dispose()); + return token; +} +export function beginPublicViewRun(view: PublicView): PublicRun { + return viewOf(view).begin(); +} +export function publicViewRunCurrent( + view: PublicView, + run: PublicRun +): boolean { + return viewOf(view).current(run) && publicRunSnapshot(run).active; +} +export function disposePublicView(view: PublicView): void { + if (!viewOf(view).dispose()) throw new Error('public_view_close_failed'); +} +export function subscribePublicView( + view: PublicView, + run: PublicRun, + kind: RequestKind, + filters: readonly PublicFilter[], + onVerified: (event: VerifiedEnvelope) => void +): PublicRequest { + const owner = viewOf(view); + if (!owner.current(run)) throw new Error('public_view_run_inactive'); + // Copy the request template once before SDK effects; caller mutations cannot + // retarget this request. Product filter builders remain HCP038 and later. + const frozen = JSON.stringify(filters); + return openPublicRequest( + run, + kind, + (next) => + subscribePublicPool( + owner.runtime.pool, + JSON.parse(frozen) as PublicFilter[], + next + ), + (event) => { + if (!owner.current(run)) return; + insertPublicEnvelope(owner.runtime.store, event); + if (owner.current(run)) onVerified(event); + } + ); +} diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte @@ -1,10 +1,23 @@ <script lang="ts"> import '../theme.css'; import '../app.css'; - import type { Snippet } from 'svelte'; + import { onMount, setContext, type Snippet } from 'svelte'; + import { + createPublicRuntimeContext, + mountPublicRuntime, + closePublicRuntime, + PUBLIC_RUNTIME_CONTEXT + } from '../lib/runtime/public-runtime.ts'; import { page } from '$app/state'; import AppShell from '../lib/components/AppShell.svelte'; + const publicContext = createPublicRuntimeContext(); + setContext(PUBLIC_RUNTIME_CONTEXT, publicContext); + onMount(() => { + mountPublicRuntime(publicContext); + return () => closePublicRuntime(publicContext); + }); + let { children }: { children: Snippet } = $props(); </script> diff --git a/web/tests/integration/public-runtime.test.ts b/web/tests/integration/public-runtime.test.ts @@ -0,0 +1,188 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { readFile } from 'node:fs/promises'; +import WebSocket, { WebSocketServer } from 'ws'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { + createPublicRuntimeContext, + mountPublicRuntime, + createPublicView, + beginPublicViewRun, + subscribePublicView, + publicViewRunCurrent, + closePublicRuntime +} from '../../src/lib/runtime/public-runtime.ts'; +import { + publicRunSnapshot, + publicRequestScopeSnapshot, + publicRunObservations, + type RequestClock +} from '../../src/lib/nostr/request-scope.ts'; +await test('actual SDK request ownership suppresses superseded results and preserves another view through its absolute deadline', async () => { + const corpus = JSON.parse( + await readFile( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) + ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; + const wires = corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires, + current = JSON.parse(wires.current) as { id: string }, + previous = JSON.parse(wires.previous) as { id: string }; + const origin = 'wss://one.example.org', + server = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 4096 + }); + const sockets: WebSocket[] = []; + const ids: string[] = []; + let socket: WebSocket | undefined; + let firstClose = () => {}; + const closedFirst = new Promise<void>((resolve) => { + firstClose = resolve; + }); + server.on('connection', (connection) => { + sockets.push(connection); + socket = connection; + connection.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 id = String(frame[1]); + ids.push(id); + connection.send( + JSON.stringify(['EVENT', id, ids.length === 1 ? current : previous]) + ); + } else if (frame[0] === 'CLOSE' && frame[1] === ids[0]) firstClose(); + }); + }); + await once(server, 'listening'); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + const port = address.port; + const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), + oldSocket = globalThis.WebSocket; + class FixtureSocket extends WebSocket { + constructor(url: string | URL) { + assert.equal(String(url).replace(/\/$/, ''), origin); + super(`ws://127.0.0.1:${port}`); + } + } + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + globalThis.WebSocket = + FixtureSocket as unknown as typeof globalThis.WebSocket; + let now = 0; + const timers = new Map<() => void, { at: number; callback: () => void }>(); + const clock: RequestClock = { + now: () => now, + schedule(callback, delay) { + const cancel = () => { + timers.delete(cancel); + }; + timers.set(cancel, { at: now + delay, callback }); + return cancel; + } + }; + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [{ origin, read: true, write: false, nip50: false }], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + const context = createPublicRuntimeContext(), + runtime = mountPublicRuntime(context, policy, clock)!; + const a = createPublicView(runtime), + b = createPublicView(runtime), + ra = beginPublicViewRun(a), + rb = beginPublicViewRun(b); + let writesA = 0, + writesB = 0; + let firstA = () => {}, + firstB = () => {}, + secondB = () => {}; + const initialA = new Promise<void>((resolve) => { + firstA = resolve; + }), + initialB = new Promise<void>((resolve) => { + firstB = resolve; + }), + continuedB = new Promise<void>((resolve) => { + secondB = resolve; + }); + try { + const ha = subscribePublicView( + a, + ra, + 'search', + [{ kinds: [30402], limit: 1 }], + () => { + writesA++; + firstA(); + } + ), + hb = subscribePublicView( + b, + rb, + 'profile', + [{ kinds: [30402], limit: 2 }], + () => { + writesB++; + if (writesB === 1) firstB(); + else secondB(); + } + ); + await Promise.all([initialA, initialB]); + assert.equal(ids.length, 2); + const next = beginPublicViewRun(a); + await closedFirst; + assert.equal(publicViewRunCurrent(a, ra), false); + assert.equal(publicViewRunCurrent(a, next), true); + assert.equal(publicRequestScopeSnapshot(ha).state, 'cancelled'); + assert.equal(publicRequestScopeSnapshot(hb).state, 'active'); + assert.ok(socket); + socket.send(JSON.stringify(['EVENT', ids[0], previous])); + socket.send(JSON.stringify(['EVENT', ids[1], previous])); + await continuedB; + assert.equal(writesA, 1); + assert.equal(writesB, 2); + assert.equal(publicRunSnapshot(ra).ingress.deliveries, 1); + assert.equal(publicRunSnapshot(rb).ingress.deliveries, 2); + assert.equal(publicRunObservations(rb, hb).length, 1); + now = 10000; + for (const [cancel, row] of [...timers]) + if (row.at <= now) { + cancel(); + row.callback(); + } + assert.equal(publicRequestScopeSnapshot(hb).state, 'deadline'); + assert.equal( + publicRequestScopeSnapshot(hb).result.definitiveAbsence, + false + ); + assert.equal(timers.size, 0); + } finally { + closePublicRuntime(context); + for (const connection of sockets) connection.terminate(); + await 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/provenance/output.test.mjs b/web/tests/provenance/output.test.mjs @@ -15,12 +15,11 @@ import { import os from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; -import { setInterval, clearInterval } from 'node:timers'; import { fileURLToPath } from 'node:url'; import { generateBuildInfo } from '../../tools/build-info.mjs'; import { auditOutput } from '../../tools/check-output.mjs'; -// Allow bounded setup/copy time for all 83 checks and two real compilations. +// Allow bounded setup/copy time for 123 checks and two real compilations. // Admission checks get 10 seconds; cold compiler work gets 60 seconds. await test('actual output qualification', { timeout: 180000 }, async (t) => { /** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */ @@ -115,7 +114,17 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { const f = await fixture(t); const files = await f.audit(); // Exact eleven-route module/page/static admission; CSS stays once-imported. - assert.equal(files.length, 41); + assert.equal(files.length, 44); + // The actual SDK payload crosses the reader scratch boundary; a reused + // scratch buffer must still preserve every compiler/static byte exactly. + const sizes = await Promise.all( + files + .filter((name) => name.endsWith('.js')) + .map( + async (name) => (await lstat(path.join(f.web, 'build', name))).size + ) + ); + assert.ok(sizes.some((bytes) => bytes > 64 * 1024)); assert.ok(files.includes('search.html')); assert.equal(files.filter((name) => name.endsWith('.css')).length, 1); assert.ok( @@ -135,6 +144,207 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { ); } ); + /** @param {{root: string, web: string}} f */ + async function refresh(f) { + git(f.root, 'add', '--', 'web/src'); + await generateBuildInfo(f.web); + const bytes = await readFile(path.join(f.web, 'static/build-info.json')); + for (const name of [ + 'build/build-info.json', + '.svelte-kit/output/client/build-info.json' + ]) + await writeFile(path.join(f.web, name), bytes); + } + await check( + 'owned root preserves its lifecycle across a 64 KiB read boundary', + async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/routes/+layout.svelte'); + const layout = await readFile(file, 'utf8'); + // A large harmless comment after the real lifecycle must not overwrite its + // first read chunk when the file reader reuses a scratch buffer. + const expanded = layout.replace( + '</script>', + '/*' + 'owned reader boundary '.repeat(4000) + '*/\n</script>' + ); + assert.ok(Buffer.byteLength(expanded) > 64 * 1024); + await writeFile(file, expanded); + await refresh(f); + assert.equal((await f.audit()).length, 44); + } + ); + const sdkKey = + 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; + for (const mutation of [ + 'unknown-name', + 'missing-public-key', + 'missing-dist', + 'missing-negentropy', + 'missing-root-edge', + 'random-key', + 'wrong-src', + 'wrong-version', + 'wrong-peer', + 'wrong-basename', + 'wrong-dynamic-flag', + 'entry-flag', + 'css', + 'wrong-import', + 'chunk-src', + 'chunk-entry' + ]) + await check( + 'owned root SDK compiler admission rejects ' + mutation, + async (t) => { + const f = await fixture(t); + const file = path.join( + f.web, + '.svelte-kit/output/client/.vite/manifest.json' + ); + const m = JSON.parse(await readFile(file, 'utf8')); + const root = Object.values(m).find((v) => v.name === 'nodes/0'); + const dist = Object.entries(m).find(([, v]) => v.name === 'dist'); + assert.ok(m[sdkKey] && root && dist, 'Actual successor SDK identities'); + if (mutation === 'unknown-name') m[sdkKey].name = 'unapproved-sdk'; + if ( + mutation.startsWith('missing-') && + mutation !== 'missing-root-edge' + ) { + const entry = Object.entries(m).find( + ([, v]) => v.name === mutation.slice(8) + ); + assert.ok(entry); + delete m[entry[0]]; + } + if (mutation === 'missing-root-edge') root.dynamicImports = []; + if ( + [ + 'random-key', + 'wrong-version', + 'wrong-peer', + 'wrong-basename' + ].includes(mutation) + ) { + const next = + mutation === 'random-key' + ? '_HCrandom.js' + : sdkKey.replace( + mutation === 'wrong-version' + ? '6.2.1' + : mutation === 'wrong-peer' + ? '6.0.3' + : 'negentropy.js', + mutation === 'wrong-basename' ? 'other.js' : '0.0.0' + ); + m[next] = m[sdkKey]; + delete m[sdkKey]; + m[next].src = next; + root.dynamicImports = root.dynamicImports.map( + (/** @type {string} */ k) => (k === sdkKey ? next : k) + ); + } + if (mutation === 'wrong-src') m[sdkKey].src = '_HCwrong.js'; + if (mutation === 'wrong-dynamic-flag') m[sdkKey].isDynamicEntry = false; + if (mutation === 'entry-flag') m[sdkKey].isEntry = false; + if (mutation === 'css') m[sdkKey].css = []; + if (mutation === 'wrong-import') + m[sdkKey].imports = [ + Object.keys(m).find((k) => m[k].name === 'public-key') + ]; + if (mutation === 'chunk-src') dist[1].src = dist[0]; + if (mutation === 'chunk-entry') dist[1].isEntry = false; + await writeFile(file, JSON.stringify(m)); + await assert.rejects(f.audit, /compiler|runtime/i); + } + ); + for (const mutation of [ + 'copied-files-only', + 'comment-only', + 'string-only', + 'shadowed', + 'rebound', + 'aliased', + 'missing-cleanup', + 'missing-context', + 'wrong-context' + ]) + await check('root runtime activation rejects ' + mutation, async (t) => { + const f = await fixture(t); + const file = path.join(f.web, 'src/routes/+layout.svelte'); + let layout = await readFile(file, 'utf8'); + if ( + ['copied-files-only', 'comment-only', 'string-only'].includes(mutation) + ) { + const script = layout.slice( + layout.indexOf('>') + 1, + layout.indexOf('</script>') + ); + layout = + '<script lang="ts">' + + (mutation === 'comment-only' + ? '/*' + script + '*/' + : mutation === 'string-only' + ? 'const text = ' + JSON.stringify(script) + ';' + : '') + + '</script><main>Controlled root</main>'; + } + if (mutation === 'shadowed') + layout = layout.replace( + 'onMount(() => {', + 'onMount((publicContext) => {' + ); + if (mutation === 'rebound') + layout = layout.replace('const publicContext', 'let publicContext'); + if (mutation === 'aliased') + layout = layout + .replace( + ' mountPublicRuntime,', + ' mountPublicRuntime as otherMount,' + ) + .replace( + 'mountPublicRuntime(publicContext)', + 'otherMount(publicContext)' + ); + if (mutation === 'missing-cleanup') + layout = layout.replace( + 'return () => closePublicRuntime(publicContext);', + 'return () => {};' + ); + if (mutation === 'missing-context') + layout = layout.replace( + 'setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);', + '' + ); + if (mutation === 'wrong-context') + layout = layout.replace( + 'closePublicRuntime(publicContext)', + 'closePublicRuntime({})' + ); + await writeFile(file, layout); + await refresh(f); + await assert.rejects(f.audit, /compiler|runtime/i); + }); + for (const name of [ + 'runtime/public-runtime.ts', + 'nostr/request-scope.ts', + 'nostr/public-pool.ts', + 'nostr/public-store.ts', + 'nostr/request-result.ts', + 'nostr/ingress.ts', + 'nostr/verified-envelope.ts', + 'nostr/envelope-bounds.ts', + 'nostr/exports.ts', + 'catalog/observations.ts', + 'config/budgets.ts', + 'config/relays.ts', + 'config/deployment-relays.ts' + ]) + await check('root runtime admission requires owned ' + name, async (t) => { + const f = await fixture(t); + await rm(path.join(f.web, 'src/lib', name)); + await refresh(f); + await assert.rejects(f.audit); + }); for (const routeSource of ['search/+page.svelte', 'messages/+page.svelte']) await check( routeSource + @@ -599,21 +809,52 @@ await test('actual output qualification', { timeout: 180000 }, async (t) => { const f = await fixture(t); for (let i = 0; i < 513; i++) await writeFile(path.join(f.web, 'build', `tiny-${i}.js`), 'x'); - const baseline = process.memoryUsage().arrayBuffers; - let peak = baseline; - const timer = setInterval(() => { - peak = Math.max(peak, process.memoryUsage().arrayBuffers); - }, 1); - try { - await assert.rejects(f.audit, /Unbounded output inventory/); - } finally { - clearInterval(timer); - } + // Confine the actual audit's allocation measurement to a fresh child; + // prior source/output fixture copies must not enter this baseline/peak. + const measurement = JSON.parse( + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + const { auditOutput } = await import(process.argv[2]); + const baseline = process.memoryUsage().arrayBuffers; + let peak = baseline, rejection; + const sample = () => { peak = Math.max(peak, process.memoryUsage().arrayBuffers); }; + const timer = setInterval(sample, 1); + try { await auditOutput(process.argv[1]); } + catch (error) { rejection = error instanceof Error ? error.message : 'unexpected'; } + finally { sample(); clearInterval(timer); } + if (rejection !== 'Unbounded output inventory') throw new Error('Unexpected inventory measurement rejection'); + process.stdout.write(JSON.stringify({ baseline, peak, growth: peak - baseline, rejection })); + `, + f.web, + new URL('../../tools/check-output.mjs', import.meta.url).href + ], + { cwd: f.web, encoding: 'utf8', timeout: 8000, maxBuffer: 4096 } + ) + ); + assert.deepEqual(Object.keys(measurement).sort(), [ + 'baseline', + 'growth', + 'peak', + 'rejection' + ]); + assert.equal(measurement.rejection, 'Unbounded output inventory'); + for (const name of ['baseline', 'peak', 'growth']) + assert.ok( + Number.isSafeInteger(measurement[name]) && measurement[name] >= 0 + ); + assert.equal(measurement.growth, measurement.peak - measurement.baseline); + t.diagnostic( + 'isolated actual inventory buffers: ' + JSON.stringify(measurement) + ); assert.ok( - peak - baseline < 64 * 1024 * 1024, - 'Tiny files must not retain a maximum-sized buffer per entry' + measurement.growth < 64 * 1024 * 1024, + 'Tiny files must not retain a maximum-sized buffer per entry: ' + + JSON.stringify(measurement) ); - t.diagnostic(`many-small-entry buffer growth: ${peak - baseline} bytes`); for (let i = 0; i < 513; i++) await rm(path.join(f.web, 'build', `tiny-${i}.js`)); for (let i = 0; i < 33; i++) diff --git a/web/tests/unit/public-runtime.test.ts b/web/tests/unit/public-runtime.test.ts @@ -0,0 +1,131 @@ +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +let runtime: typeof import('../../src/lib/runtime/public-runtime.ts'); +beforeEach(async () => { + vi.resetModules(); + runtime = await import('../../src/lib/runtime/public-runtime.ts'); +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); +describe('root public runtime context', () => { + it('creates an inert SSR context without acquiring browser capabilities', () => { + vi.stubGlobal('window', undefined); + const context = runtime.createPublicRuntimeContext(); + expect(Object.isFrozen(context)).toBe(true); + expect(Object.keys(context)).toEqual([]); + expect(runtime.publicRuntime(context)).toBeUndefined(); + expect(runtime.mountPublicRuntime(context)).toBeUndefined(); + runtime.closePublicRuntime(context); + expect(runtime.publicRuntime(context)).toBeUndefined(); + }); + it('owns one anonymous mounted browser lifetime and terminal teardown', () => { + vi.stubGlobal('window', {}); + const context = runtime.createPublicRuntimeContext(), + owner = runtime.mountPublicRuntime(context)!; + expect(owner).toBeDefined(); + expect(runtime.mountPublicRuntime(context)).toBe(owner); + expect(runtime.publicRuntime(context)).toBe(owner); + const a = runtime.createPublicView(owner), + b = runtime.createPublicView(owner); + const run = runtime.beginPublicViewRun(a); + runtime.beginPublicViewRun(b); + const next = runtime.beginPublicViewRun(a); + expect(runtime.publicViewRunCurrent(a, run)).toBe(false); + expect(runtime.publicViewRunCurrent(a, next)).toBe(true); + runtime.disposePublicView(a); + expect(runtime.publicViewRunCurrent(a, next)).toBe(false); + runtime.closePublicRuntime(context); + expect(() => runtime.createPublicView(owner)).toThrow( + 'public_runtime_closed' + ); + expect(() => runtime.mountPublicRuntime(context)).toThrow( + 'public_runtime_closed' + ); + runtime.closePublicRuntime(context); + }); + it('rejects forged context and view ownership', () => { + expect(() => + runtime.publicRuntime( + {} as ReturnType<typeof runtime.createPublicRuntimeContext> + ) + ).toThrow('public_runtime_context_invalid'); + vi.stubGlobal('window', {}); + const context = runtime.createPublicRuntimeContext(), + owner = runtime.mountPublicRuntime(context)!; + expect(owner).toBeDefined(); + expect(() => + runtime.beginPublicViewRun( + {} as ReturnType<typeof runtime.createPublicView> + ) + ).toThrow('public_view_invalid'); + runtime.closePublicRuntime(context); + expect(runtime.publicRuntime(context)).toBeUndefined(); + }); + it('settles readiness safely when an SSR context is disposed before hydration', async () => { + vi.stubGlobal('window', undefined); + const context = runtime.createPublicRuntimeContext(); + const ready = runtime.publicRuntimeReady(context); + runtime.closePublicRuntime(context); + expect(await ready).toBeUndefined(); + expect(() => runtime.mountPublicRuntime(context)).toThrow( + 'public_runtime_closed' + ); + }); + it('prevents a second root owner or changed manifest/clock from resetting admission', () => { + vi.stubGlobal('window', {}); + const context = runtime.createPublicRuntimeContext(), + owner = runtime.mountPublicRuntime(context)!; + expect(owner).toBeDefined(); + const other = runtime.createPublicRuntimeContext(); + expect(() => runtime.mountPublicRuntime(other)).toThrow( + 'public_runtime_owner_changed' + ); + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + )!; + expect(() => runtime.mountPublicRuntime(context, policy)).toThrow( + 'public_runtime_policy_changed' + ); + expect(() => + runtime.mountPublicRuntime(context, undefined, { + now: () => 0, + schedule: () => () => {} + }) + ).toThrow('public_runtime_clock_changed'); + runtime.closePublicRuntime(context); + runtime.closePublicRuntime(other); + }); + it('keeps root teardown terminal while a failed actual SDK close remains retryable', async () => { + const { RelayPool } = await import('applesauce-relay/pool'); // eslint-disable-next-line @typescript-eslint/unbound-method -- Explicit receiver is provided by original.call(this) below. + const original = RelayPool.prototype.close; + let calls = 0; + vi.spyOn(RelayPool.prototype, 'close').mockImplementation(function ( + this: InstanceType<typeof RelayPool> + ) { + calls++; + if (calls === 1) throw new Error('RAW_SDK_CLOSE_ERROR'); + original.call(this); + }); + vi.stubGlobal('window', {}); + const context = runtime.createPublicRuntimeContext(), + owner = runtime.mountPublicRuntime(context)!; + expect(() => runtime.closePublicRuntime(context)).toThrow( + 'public_runtime_close_failed' + ); + expect(runtime.publicRuntime(context)).toBeUndefined(); + expect(() => runtime.createPublicView(owner)).toThrow( + 'public_runtime_closed' + ); + runtime.closePublicRuntime(context); + expect(calls).toBe(2); + }); +}); diff --git a/web/tests/unit/request-scope.test.ts b/web/tests/unit/request-scope.test.ts @@ -0,0 +1,442 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts'; +import { + createPublicScheduler, + createPublicRun, + openPublicRequest, + closePublicRequest, + cancelPublicRun, + disposePublicRun, + closePublicScheduler, + publicRunSnapshot, + publicRequestScopeSnapshot, + publicSchedulerSnapshot, + publicRunObservations, + type RequestClock +} from '../../src/lib/nostr/request-scope.ts'; +const origin = 'wss://one.example.org'; +const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [{ origin, read: true, write: false, nip50: false }], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) +)!; +const corpus = JSON.parse( + readFileSync( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) +) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; +const wire = corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires + .current; +const event = () => + JSON.parse(wire) as Extract<PublicPoolMessage, { type: 'EVENT' }>['event']; +function fixture() { + let now = 0; + const timers = new Map<() => void, { at: number; callback: () => void }>(); + const clock: RequestClock = { + now: () => now, + schedule(callback, delay) { + const cancel = () => { + timers.delete(cancel); + }; + timers.set(cancel, { at: now + delay, callback }); + return cancel; + } + }; + const scheduler = createPublicScheduler(clock); + return { + scheduler, + advance(value: number, flush = true) { + now = value; + if (flush) + for (const [cancel, row] of [...timers]) + if (row.at <= now) { + cancel(); + row.callback(); + } + }, + timers + }; +} +function channel() { + let sink: (message: PublicPoolMessage) => void = () => {}; + let stopped = 0; + let opened = 0; + return { + open(this: void, next: (message: PublicPoolMessage) => void) { + opened++; + sink = next; + return () => { + stopped++; + }; + }, + emit(message: PublicPoolMessage) { + sink(message); + }, + counts: () => ({ opened, stopped }) + }; +} +describe('owned public request scopes', () => { + it('admits only six aggregate primary and auxiliary scopes before effects', () => { + const f = fixture(), + a = createPublicRun(f.scheduler, policy), + b = createPublicRun(f.scheduler, policy), + c = channel(); + const requests = Array.from({ length: 6 }, (_, i) => + openPublicRequest( + i < 3 ? a : b, + ['search', 'head', 'deletion', 'profile'][i % 4] as + 'search' | 'head' | 'deletion' | 'profile', + c.open, + () => {} + ) + ); + expect(() => openPublicRequest(b, 'profile', c.open, () => {})).toThrow( + 'public_request_concurrency_limit' + ); + expect(c.counts().opened).toBe(6); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(6); + closePublicRequest(requests[0]); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(5); + expect(publicRequestScopeSnapshot(requests[1]).state).toBe('active'); + openPublicRequest(b, 'head', c.open, () => {}); + closePublicScheduler(f.scheduler); + expect(f.timers.size).toBe(0); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + }); + it('caps each request at ten seconds and never extends the absolute run deadline', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + c = channel(); + const first = openPublicRequest(run, 'search', c.open, () => {}); + expect(publicRunSnapshot(run).deadline).toBe(15000); + expect(publicRequestScopeSnapshot(first).deadline).toBe(10000); + f.advance(10000); + expect(publicRequestScopeSnapshot(first).state).toBe('deadline'); + f.advance(14000); + const late = openPublicRequest(run, 'profile', c.open, () => {}); + expect(publicRequestScopeSnapshot(late).deadline).toBe(15000); + f.advance(15000); + expect(publicRequestScopeSnapshot(late).state).toBe('deadline'); + expect(() => openPublicRequest(run, 'head', c.open, () => {})).toThrow( + 'public_run_inactive' + ); + expect(c.counts().stopped).toBe(2); + }); + it('checks absolute time on callbacks even when timer dispatch is delayed', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + c = channel(); + let writes = 0; + const request = openPublicRequest(run, 'search', c.open, () => { + writes++; + }); + f.advance(10001, false); + c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(writes).toBe(0); + expect(publicRequestScopeSnapshot(request).state).toBe('deadline'); + expect(publicRunSnapshot(run).ingress.deliveries).toBe(0); + expect(f.timers.size).toBe(0); + }); + it('cancellation invalidates late writes and leaves another owner running', () => { + const f = fixture(), + a = createPublicRun(f.scheduler, policy), + b = createPublicRun(f.scheduler, policy), + ca = channel(), + cb = channel(); + let writes = 0; + const ra = openPublicRequest(a, 'search', ca.open, () => { + writes++; + }), + rb = openPublicRequest(b, 'profile', cb.open, () => { + writes++; + }); + cancelPublicRun(a); + ca.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + cb.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(writes).toBe(1); + expect(publicRequestScopeSnapshot(ra).state).toBe('cancelled'); + expect(publicRequestScopeSnapshot(rb).state).toBe('active'); + expect(cb.counts().stopped).toBe(0); + closePublicScheduler(f.scheduler); + }); + it('shares duplicate and rejected candidate charges across auxiliary scopes', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + a = channel(), + b = channel(); + let writes = 0; + const ra = openPublicRequest(run, 'search', a.open, () => { + writes++; + }), + rb = openPublicRequest(run, 'deletion', b.open, () => { + writes++; + }); + a.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + b.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + b.emit({ + type: 'EVENT', + id: 'fixture', + from: origin, + event: { ...event(), sig: '0'.repeat(128) } + }); + expect(publicRunSnapshot(run).ingress.deliveries).toBe(3); + expect(writes).toBe(2); + expect(publicRunObservations(run, ra)).toHaveLength(1); + expect(publicRunObservations(run, rb)).toHaveLength(1); + closePublicScheduler(f.scheduler); + }); + it('finishes a bounded source at EOSE while preserving exact evidence', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + c = channel(); + const request = openPublicRequest(run, 'head', c.open, () => {}); + c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + c.emit({ type: 'EOSE', id: 'fixture', from: origin }); + expect(publicRequestScopeSnapshot(request).state).toBe('eose'); + expect(publicRequestScopeSnapshot(request).result.definitiveAbsence).toBe( + false + ); + expect(publicRunObservations(run, request)).toHaveLength(1); + expect(c.counts().stopped).toBe(1); + cancelPublicRun(run); + expect(publicRunObservations(run, request)).toHaveLength(1); + disposePublicRun(run); + expect(publicRunObservations(run, request)).toEqual([]); + }); + it('cleans a synchronously completed open without orphaning its stop control', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy); + let stops = 0; + const request = openPublicRequest( + run, + 'search', + (next) => { + next({ type: 'EOSE', id: 'fixture', from: origin }); + return () => { + stops++; + }; + }, + () => {} + ); + expect(publicRequestScopeSnapshot(request).state).toBe('eose'); + expect(stops).toBe(1); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + expect(f.timers.size).toBe(0); + }); + it('cleans rejected open and callback failures with safe outcome text', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy); + expect(() => + openPublicRequest( + run, + 'search', + () => { + throw new Error('PRIVATE_RAW_ERROR'); + }, + () => {} + ) + ).toThrow('public_request_open_failed'); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + expect(f.timers.size).toBe(0); + const c = channel(); + const request = openPublicRequest(run, 'profile', c.open, () => { + throw new Error('PRIVATE_UI_ERROR'); + }); + c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(publicRequestScopeSnapshot(request).state).toBe('error'); + expect(JSON.stringify(publicRequestScopeSnapshot(request))).not.toMatch( + /PRIVATE/ + ); + }); + it('rejects forged handles and another run observation context', () => { + const f = fixture(), + a = createPublicRun(f.scheduler, policy), + b = createPublicRun(f.scheduler, policy), + c = channel(); + const request = openPublicRequest(a, 'search', c.open, () => {}); + expect(Object.keys(request)).toEqual([]); + expect(Object.isFrozen(request)).toBe(true); + expect(() => publicRunObservations(b, request)).toThrow( + 'public_request_run_changed' + ); + expect(() => closePublicRequest({} as typeof request)).toThrow( + 'public_request_invalid' + ); + closePublicScheduler(f.scheduler); + expect(() => createPublicRun(f.scheduler, policy)).toThrow( + 'public_scheduler_closed' + ); + }); + it('retains failed cleanup admission until explicit retry and stops successful controls once', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy); + let stops = 0; + const request = openPublicRequest( + run, + 'search', + () => () => { + stops++; + if (stops === 1) throw new Error('RAW_CLEANUP_ERROR'); + }, + () => {} + ); + expect(() => closePublicRequest(request)).toThrow( + 'public_request_close_failed' + ); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(1); + expect(publicRequestScopeSnapshot(request).state).toBe('cancelled'); + closePublicRequest(request); + closePublicRequest(request); + expect(stops).toBe(2); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + expect(f.timers.size).toBe(0); + closePublicScheduler(f.scheduler); + }); + it('lets the inclusive two-thousandth candidate finish then cancels every auxiliary scope', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + a = channel(), + b = channel(); + let writes = 0; + const ra = openPublicRequest(run, 'search', a.open, () => { + writes++; + }), + rb = openPublicRequest(run, 'profile', b.open, () => { + writes++; + }); + for (let i = 0; i < 2000; i++) + (i % 2 === 0 ? a : b).emit({ + type: 'EVENT', + id: 'fixture', + from: origin, + event: event() + }); + expect(writes).toBe(2000); + expect(publicRunSnapshot(run).ingress.deliveries).toBe(2000); + expect(publicRunSnapshot(run).ingress.stopped).toBe(true); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + expect(publicRequestScopeSnapshot(rb).state).toBe('limit'); + expect(publicRequestScopeSnapshot(ra).state).toBe('cancelled'); + expect(f.timers.size).toBe(0); + expect(publicRunObservations(run, ra)).toHaveLength(1); + expect(publicRunObservations(run, rb)).toHaveLength(1); + a.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(writes).toBe(2000); + disposePublicRun(run); + }); + it('does not extend captured deadlines when an injected clock moves backwards', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + c = channel(); + f.advance(5000); + const request = openPublicRequest(run, 'head', c.open, () => {}); + expect(publicRequestScopeSnapshot(request).deadline).toBe(15000); + f.advance(1000, false); + expect(publicRunSnapshot(run).deadline).toBe(15000); + c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(publicRequestScopeSnapshot(request).state).toBe('active'); + f.advance(15000); + expect(publicRequestScopeSnapshot(request).state).toBe('deadline'); + closePublicScheduler(f.scheduler); + }); + it('fails closed on invalid clock values and returns detached outcome snapshots', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + c = channel(); + let writes = 0; + const request = openPublicRequest(run, 'search', c.open, () => { + writes++; + }); + const snapshot = publicRequestScopeSnapshot(request); + (snapshot as unknown as { state: string }).state = 'eose'; + expect(publicRequestScopeSnapshot(request).state).toBe('active'); + f.advance(Number.NaN, false); + c.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(writes).toBe(0); + expect(publicRequestScopeSnapshot(request).state).toBe('error'); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + closePublicScheduler(f.scheduler); + }); + it('retries only a failed timer cancellation without repeating successful subscription cleanup', () => { + let timerCalls = 0, + stopCalls = 0; + const clock: RequestClock = { + now: () => 0, + schedule: () => () => { + timerCalls++; + if (timerCalls === 1) throw new Error('timer_failed'); + } + }; + const scheduler = createPublicScheduler(clock), + run = createPublicRun(scheduler, policy), + request = openPublicRequest( + run, + 'search', + () => () => { + stopCalls++; + }, + () => {} + ); + expect(() => closePublicRequest(request)).toThrow( + 'public_request_close_failed' + ); + expect(stopCalls).toBe(1); + expect(publicSchedulerSnapshot(scheduler).activeRequests).toBe(1); + closePublicRequest(request); + expect(timerCalls).toBe(2); + expect(stopCalls).toBe(1); + expect(publicSchedulerSnapshot(scheduler).activeRequests).toBe(0); + closePublicScheduler(scheduler); + }); + it('cancels auxiliary work even when the inclusive final candidate view callback throws', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + a = channel(), + b = channel(); + let calls = 0; + const ra = openPublicRequest(run, 'search', a.open, () => {}), + rb = openPublicRequest(run, 'profile', b.open, () => { + calls++; + throw new Error('final_callback_failed'); + }); + for (let i = 0; i < 1999; i++) + a.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + b.emit({ type: 'EVENT', id: 'fixture', from: origin, event: event() }); + expect(calls).toBe(1); + expect(publicRunSnapshot(run).ingress.deliveries).toBe(2000); + expect(publicRequestScopeSnapshot(rb).state).toBe('error'); + expect(publicRequestScopeSnapshot(ra).state).toBe('cancelled'); + expect(publicSchedulerSnapshot(f.scheduler).activeRequests).toBe(0); + expect(f.timers.size).toBe(0); + expect(publicRunObservations(run, ra)).toHaveLength(1); + expect(publicRunObservations(run, rb)).toHaveLength(1); + closePublicScheduler(f.scheduler); + }); + it('checks captured absolute time again when a deadline timer fires early', () => { + const f = fixture(), + run = createPublicRun(f.scheduler, policy), + c = channel(), + request = openPublicRequest(run, 'head', c.open, () => {}); + f.advance(9999, false); + const [cancel, row] = [...f.timers][0]; + cancel(); + row.callback(); + expect(publicRequestScopeSnapshot(request).state).toBe('active'); + expect(f.timers.size).toBe(1); + f.advance(10000); + expect(publicRequestScopeSnapshot(request).state).toBe('deadline'); + expect(f.timers.size).toBe(0); + closePublicScheduler(f.scheduler); + }); +}); diff --git a/web/tools/check-output.mjs b/web/tools/check-output.mjs @@ -5,6 +5,8 @@ import { lstat, open, opendir, realpath } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { deriveBuildInfo } from './build-info.mjs'; +import ts from 'typescript'; +import { parse as parseSvelte } from 'svelte/compiler'; /** @param {unknown} actual @param {unknown} expected @param {string} [message] */ function equal(actual, expected, message = 'Invalid public output shape') { @@ -67,13 +69,13 @@ async function readOwned(root, name) { throw new Error('Unsafe output entry'); const chunks = []; let size = 0; + const buffer = Buffer.alloc(64 * 1024); for (;;) { - const buffer = Buffer.alloc(64 * 1024); const { bytesRead } = await handle.read(buffer); if (!bytesRead) break; size += bytesRead; if (size > maxBytes) throw new Error('Oversized output entry'); - chunks.push(buffer.subarray(0, bytesRead)); + chunks.push(Buffer.from(buffer.subarray(0, bytesRead))); } return Buffer.concat(chunks); } finally { @@ -161,6 +163,139 @@ function objectKeys(value, keys) { if (Object.keys(value).some((key) => !keys.includes(key))) throw new Error('Unknown compiler field'); } +const sdkNegentropy = + 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; +// Compiler admission follows actual root bindings, never copied files or text +// matches. This is the deliberately fixed lifecycle shape owned by HCP032. +/** @param {string} web */ +async function hasOwnedPublicRuntime(web) { + const layout = publicText(await readOwned(web, 'src/routes/+layout.svelte')); + const component = parseSvelte(layout); + if (!component.instance) return false; + const script = layout.slice( + component.instance.content.start, + component.instance.content.end + ); + const source = ts.createSourceFile( + 'root.ts', + script, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS + ); + const runtimePath = '../lib/runtime/public-runtime.ts'; + const imports = source.statements.filter(ts.isImportDeclaration); + const runtimeImports = imports.filter( + (node) => + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text === runtimePath + ); + if (!runtimeImports.length) return false; + /** @returns {never} */ + function fail() { + throw new Error('Invalid owned root runtime activation'); + } + if (runtimeImports.length !== 1 || component.module) fail(); + const required = new Map([ + [ + runtimePath, + [ + 'createPublicRuntimeContext', + 'mountPublicRuntime', + 'closePublicRuntime', + 'PUBLIC_RUNTIME_CONTEXT' + ] + ], + ['svelte', ['onMount', 'setContext']] + ]); + const allowedImports = new Set(); + for (const [module, names] of required) { + const declarations = imports.filter( + (node) => + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text === module + ); + if (declarations.length !== 1) fail(); + const clause = declarations[0].importClause; + if ( + !clause || + clause.isTypeOnly || + clause.name || + !clause.namedBindings || + !ts.isNamedImports(clause.namedBindings) + ) + fail(); + const elements = clause.namedBindings.elements; + for (const name of names) { + const bindings = elements.filter((node) => node.name.text === name); + if ( + bindings.length !== 1 || + bindings[0].propertyName || + bindings[0].isTypeOnly + ) + fail(); + } + if (module === runtimePath && elements.length !== names.length) fail(); + allowedImports.add(declarations[0]); + } + const printer = ts.createPrinter({ removeComments: true }); + /** @param {import("typescript").Node} node @param {import("typescript").SourceFile} file */ + const print = (node, file) => + printer.printNode(ts.EmitHint.Unspecified, node, file); + const expected = ts.createSourceFile( + 'expected.ts', + ` + const publicContext = createPublicRuntimeContext(); + setContext(PUBLIC_RUNTIME_CONTEXT, publicContext); + onMount(() => { + mountPublicRuntime(publicContext); + return () => closePublicRuntime(publicContext); + });`, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS + ); + const shapes = expected.statements.map((node) => print(node, expected)); + const lifecycle = source.statements.filter((node) => + shapes.includes(print(node, source)) + ); + if ( + lifecycle.length !== shapes.length || + lifecycle.some((node, i) => print(node, source) !== shapes[i]) + ) + fail(); + // Reject duplicate, shadowed, reassigned, or extra uses of these bindings in + // any other statement, including nested closures. Canonical callbacks have + // no parameters and therefore cannot hide a second context binding. + const bindings = new Set(['publicContext', ...[...required.values()].flat()]); + for (const statement of source.statements) { + if (allowedImports.has(statement) || lifecycle.includes(statement)) + continue; + /** @param {import("typescript").Node} node */ + const visit = (node) => { + if (ts.isIdentifier(node) && bindings.has(node.text)) fail(); + ts.forEachChild(node, visit); + }; + visit(statement); + } + for (const name of [ + 'runtime/public-runtime.ts', + 'nostr/request-scope.ts', + 'nostr/public-pool.ts', + 'nostr/public-store.ts', + 'nostr/request-result.ts', + 'nostr/ingress.ts', + 'nostr/verified-envelope.ts', + 'nostr/envelope-bounds.ts', + 'nostr/exports.ts', + 'catalog/observations.ts', + 'config/budgets.ts', + 'config/relays.ts', + 'config/deployment-relays.ts' + ]) + publicText(await readOwned(web, 'src/lib/' + name)); + return true; +} /** @param {string} webDirectory */ export async function auditOutput(webDirectory) { const web = path.resolve(webDirectory); @@ -253,6 +388,9 @@ export async function auditOutput(webDirectory) { ]) await readOwned(web, name); } + const hasPublicRuntime = await hasOwnedPublicRuntime(web); + if (hasPublicRuntime && !hasFullRoutes) + throw new Error('Incomplete owned root runtime routes'); // Admit compiler-owned module identities, not arbitrary extensions/copy roots. const names = new Set([ 'entry/app', @@ -284,6 +422,8 @@ export async function auditOutput(webDirectory) { ]) names.add(name); } + if (hasPublicRuntime) + for (const name of ['public-key', 'dist', 'negentropy']) names.add(name); const admitted = new Map([['build-info.json', expectedMetadata]]); const seen = new Set(); for (const [key, record] of Object.entries(manifest)) { @@ -308,6 +448,7 @@ export async function auditOutput(webDirectory) { const frameworkModule = /^node_modules\/\.pnpm\/[^/]+\/node_modules\/@sveltejs\/kit\/src\/runtime\/client\/(?:client-entry|entry|payload)\.js$/; if (!( + (hasPublicRuntime && key === sdkNegentropy) || generatedModule.test(key) || frameworkModule.test(key) || /^_[A-Za-z0-9_-]+\.js$/.test(key) @@ -316,7 +457,11 @@ export async function auditOutput(webDirectory) { if ( record.src !== undefined && (record.src !== key || - !(generatedModule.test(key) || frameworkModule.test(key))) + !( + generatedModule.test(key) || + frameworkModule.test(key) || + (hasPublicRuntime && key === sdkNegentropy) + )) ) throw new Error('Invalid compiler source'); if ( @@ -362,6 +507,45 @@ export async function auditOutput(webDirectory) { } } equal([...seen].sort(), [...names].sort(), 'Incomplete compiler modules'); + if (hasPublicRuntime) { + const records = Object.entries(manifest); + /** @param {string} name */ + function requiredRecord(name) { + const entry = records.find(([, record]) => record.name === name); + if (!entry) throw new Error('Incomplete owned SDK compiler module'); + return entry; + } + const dist = requiredRecord('dist'); + const root = requiredRecord('nodes/0')[1]; + const sdk = manifest[sdkNegentropy]; + if ( + !sdk || + sdk.name !== 'negentropy' || + sdk.src !== sdkNegentropy || + sdk.isDynamicEntry !== true || + sdk.isEntry !== undefined || + sdk.css !== undefined || + sdk.dynamicImports !== undefined + ) + throw new Error('Invalid owned SDK compiler identity'); + equal(sdk.imports, [dist[0]], 'Invalid owned SDK compiler dependency'); + equal( + root.dynamicImports, + [sdkNegentropy], + 'Invalid owned root compiler edge' + ); + for (const name of ['dist', 'public-key']) { + const [key, record] = requiredRecord(name); + if ( + !/^_[A-Za-z0-9_-]+\.js$/.test(key) || + record.src !== undefined || + record.isEntry !== undefined || + record.isDynamicEntry !== undefined || + record.css !== undefined + ) + throw new Error('Invalid owned SDK compiler chunk'); + } + } if (hasFullRoutes) { const robots = await readOwned(web, 'static/robots.txt'); publicText(robots);