commit 2904a994d5ba6199c444586089720244c8d1eed8
parent 0d8e6df503f96547fc137f52698c2f5aee06a811
Author: triesap <tyson@radroots.org>
Date: Fri, 9 Oct 2026 04:41:25 +0000
messages: admit and retain bounded outer inbox ciphertext (HCP-090)
Diffstat:
5 files changed, 1082 insertions(+), 0 deletions(-)
diff --git a/web/src/lib/nostr/inbox-ingress.ts b/web/src/lib/nostr/inbox-ingress.ts
@@ -0,0 +1,317 @@
+import {
+ readRelayPolicy,
+ inboxRelayTargets,
+ publicRelayTargets,
+ type RelayPolicy
+} from '../config/relays.ts';
+import { PRIVATE_TRANSPORT_BUDGETS } from '../config/budgets.ts';
+import { inboxPreferenceSnapshot } from './inbox-preferences.ts';
+import {
+ inboxResolutionSnapshot,
+ inboxResolverCurrentAfterSample,
+ type InboxResolver
+} from '../messaging/resolve-inbox.ts';
+import type { ObserveInboxAccess } from '../messaging/readiness.ts';
+import {
+ privateSessionOwnership,
+ subscribePrivateSessionClose,
+ type PrivateSession
+} from '../runtime/private-session.ts';
+import {
+ getPrivatePool,
+ subscribePrivatePage,
+ closePrivatePool
+} from './private-pool.ts';
+import {
+ admitInboxEnvelope,
+ retainInboxEnvelope
+} from '../persistence/inbox-envelope-repository.ts';
+import type { PrivateStorageRepository } from '../persistence/private-storage.ts';
+declare const ingressBrand: unique symbol;
+export type InboxIngress = Readonly<{ [ingressBrand]: true }>;
+type State =
+ 'ready' | 'running' | 'finite_page_ended' | 'stopped' | 'needs_action';
+type Snapshot = Readonly<{
+ owner: string;
+ state: State;
+ candidates: number;
+ bytes: number;
+ retained: number;
+ duplicates: number;
+ rejected: number;
+ reason: string | null;
+ pending: number;
+ cleanupRequired: boolean;
+}>;
+type Controller = {
+ start(review: unknown): boolean;
+ stop(): void;
+ snapshot(): Snapshot;
+};
+const ingress = new WeakMap<InboxIngress, Controller>();
+// Explicit finite receive admission. A remembered key, allowlist or EOSE alone
+// is not exercised own inbox access. No production observation port is supplied
+// here; controlled fixtures do not qualify real operator relay/AUTH access.
+export function captureInboxIngress(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ policy: RelayPolicy,
+ own: InboxResolver,
+ observeAccess: ObserveInboxAccess | undefined,
+ review: unknown
+): InboxIngress | undefined {
+ if (
+ typeof window === 'undefined' ||
+ review !== 'reviewed_private_inbox_receive' ||
+ !observeAccess
+ )
+ return undefined;
+ try {
+ const ownership = privateSessionOwnership(session),
+ manifest = readRelayPolicy(policy),
+ resolution = inboxResolutionSnapshot(own);
+ if (
+ !ownership?.current() ||
+ !manifest.messagingEnabled ||
+ resolution.author !== ownership.owner ||
+ resolution.status !== 'ready' ||
+ resolution.coverage !== 'bounded-eose' ||
+ !resolution.head ||
+ !resolution.knownBase
+ )
+ return undefined;
+ const preference = inboxPreferenceSnapshot(resolution.head),
+ discovery = publicRelayTargets(policy, 'read');
+ if (
+ !preference ||
+ preference.status !== 'supported' ||
+ preference.author !== ownership.owner ||
+ preference.id !== resolution.knownBase.id ||
+ !discovery.length ||
+ discovery.length !== resolution.sources.length ||
+ !discovery.every((origin) =>
+ resolution.sources.some(
+ (source) => source.source === origin && source.state === 'eose'
+ )
+ )
+ )
+ return undefined;
+ const targets = inboxRelayTargets(policy, preference.relays, 'read'),
+ archive = inboxRelayTargets(policy, preference.relays, 'write');
+ if (!targets.length || !archive.length) return undefined;
+ const access = observeAccess({
+ owner: ownership.owner,
+ session: ownership.session,
+ preferenceId: preference.id,
+ readTargets: targets.slice(),
+ archiveTargets: archive.slice()
+ });
+ if (
+ !access ||
+ access.owner !== ownership.owner ||
+ access.session !== ownership.session ||
+ access.preferenceId !== preference.id ||
+ access.receive !== 'qualified_exercised' ||
+ access.archive !== 'qualified_exercised' ||
+ JSON.stringify(access.readTargets) !== JSON.stringify(targets) ||
+ JSON.stringify(access.archiveTargets) !== JSON.stringify(archive)
+ )
+ return undefined;
+ const current = () => {
+ const latest = inboxResolutionSnapshot(own);
+ return (
+ latest.status === 'ready' &&
+ latest.coverage === 'bounded-eose' &&
+ latest.author === ownership.owner &&
+ latest.knownBase?.id === preference.id &&
+ access.current() &&
+ ownership.current() &&
+ inboxResolverCurrentAfterSample(own)
+ );
+ };
+ if (!current()) return undefined;
+ const pool = getPrivatePool(session, policy, targets);
+ if (!pool) return undefined;
+ const token = Object.freeze({}) as InboxIngress;
+ let state: State = 'ready',
+ candidates = 0,
+ bytes = 0,
+ retained = 0,
+ duplicates = 0,
+ rejected = 0,
+ pending = 0,
+ reason: string | null = null,
+ consumed = false,
+ stopped = false,
+ ended = false,
+ failed = false,
+ cleaned = false,
+ cleanupRequired = false;
+ let release = () => {},
+ off = () => {};
+ let queue = Promise.resolve();
+ function stop() {
+ if (cleaned) return;
+ stopped = true;
+ state = 'stopped';
+ let failure = false;
+ try {
+ release();
+ } catch {
+ failure = true;
+ }
+ try {
+ closePrivatePool(pool!);
+ } catch {
+ failure = true;
+ }
+ cleanupRequired = failure;
+ if (!failure) {
+ cleaned = true;
+ off();
+ } else throw new Error('private_inbox_cleanup_required');
+ }
+ function settled() {
+ if (ended && pending === 0 && !stopped && state === 'running')
+ state = 'finite_page_ended';
+ }
+ ingress.set(token, {
+ snapshot: () => ({
+ owner: ownership.owner,
+ state,
+ candidates,
+ bytes,
+ retained,
+ duplicates,
+ rejected,
+ reason,
+ pending,
+ cleanupRequired
+ }),
+ stop,
+ start(reviewed) {
+ if (
+ reviewed !== 'reviewed_private_inbox_receive' ||
+ consumed ||
+ stopped ||
+ !current()
+ )
+ return false;
+ consumed = true;
+ state = 'running';
+ release = subscribePrivatePage(
+ pool,
+ PRIVATE_TRANSPORT_BUDGETS.requestedPerRelay,
+ (message) => {
+ if (stopped) return;
+ if (!current()) {
+ stop();
+ return;
+ }
+ if (message.type === 'end') {
+ ended = true;
+ if (state !== 'needs_action') reason = message.reason;
+ settled();
+ return;
+ }
+ if (failed) return;
+ candidates++;
+ const size = new TextEncoder().encode(message.wire).length;
+ bytes += size;
+ // Existing private SDK page also charges every candidate BEFORE
+ // crypto/dedup and enforces finite deliveries/bytes/network elapsed.
+ if (
+ candidates > PRIVATE_TRANSPORT_BUDGETS.deliveries ||
+ bytes > PRIVATE_TRANSPORT_BUDGETS.processedBytes
+ ) {
+ state = 'needs_action';
+ reason = 'budget';
+ release();
+ return;
+ }
+ const origin = message.from.endsWith('/')
+ ? message.from.slice(0, -1)
+ : message.from;
+ if (!targets.includes(origin)) {
+ rejected++;
+ return;
+ }
+ const envelope = admitInboxEnvelope(
+ message.wire,
+ ownership.owner,
+ origin,
+ Date.now()
+ );
+ if (!envelope) {
+ rejected++;
+ return;
+ }
+ pending++;
+ queue = queue
+ .then(async () => {
+ if (failed || stopped) return;
+ if (!current()) {
+ stop();
+ return;
+ }
+ const result = await retainInboxEnvelope(
+ repository,
+ session,
+ envelope
+ );
+ if (stopped || !current()) {
+ if (!stopped) stop();
+ return;
+ }
+ if (result.status === 'retained') retained++;
+ else if (result.status === 'duplicate') duplicates++;
+ else {
+ failed = true;
+ state = 'needs_action';
+ reason = result.status;
+ release();
+ }
+ })
+ .catch(() => {
+ failed = true;
+ state = stopped ? 'stopped' : 'needs_action';
+ reason = 'unknown_completion';
+ try {
+ release();
+ } catch {
+ cleanupRequired = true;
+ }
+ })
+ .finally(() => {
+ pending--;
+ settled();
+ });
+ }
+ );
+ return true;
+ }
+ });
+ off = subscribePrivateSessionClose(session, stop);
+ if (!current()) {
+ stop();
+ return undefined;
+ }
+ return token;
+ } catch {
+ return undefined;
+ }
+}
+export function startInboxIngress(
+ token: InboxIngress,
+ review: unknown
+): boolean {
+ return ingress.get(token)?.start(review) ?? false;
+}
+export function stopInboxIngress(token: InboxIngress): void {
+ ingress.get(token)?.stop();
+}
+export function inboxIngressSnapshot(
+ token: InboxIngress
+): Snapshot | undefined {
+ return ingress.get(token)?.snapshot();
+}
diff --git a/web/src/lib/persistence/inbox-envelope-repository.ts b/web/src/lib/persistence/inbox-envelope-repository.ts
@@ -0,0 +1,176 @@
+import { canonicalPublicKey } from '../contracts/public-key.ts';
+import { canonicalRelayOrigin } from '../config/relays.ts';
+import { PRIVATE_TRANSPORT_BUDGETS, RELAY_BUDGETS } from '../config/budgets.ts';
+import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts';
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from '../nostr/verified-envelope.ts';
+import {
+ privateSessionOwnership,
+ type PrivateSession
+} from '../runtime/private-session.ts';
+import {
+ decodePrivateRecord,
+ privateRecordSnapshot,
+ privateRecordWire,
+ type PrivateRecordHandle
+} from './private-records.ts';
+import {
+ loadPrivateRecord,
+ commitPrivateRecord,
+ type PrivateStorageRepository,
+ type PrivateStorageFailure
+} from './private-storage.ts';
+declare const envelopeBrand: unique symbol;
+export type InboxEnvelope = Readonly<{ [envelopeBrand]: true }>;
+type Admitted = Readonly<{
+ owner: string;
+ id: string;
+ source: string;
+ record: PrivateRecordHandle;
+}>;
+const envelopes = new WeakMap<InboxEnvelope, Admitted>();
+// Outer authentication only. Ciphertext is untrusted until later nested seal,
+// rumor and sender/participant admission; this proof never grants decryption.
+export function admitInboxEnvelope(
+ raw: unknown,
+ expectedOwner: unknown,
+ observedSource: unknown,
+ observedAt: unknown
+): InboxEnvelope | undefined {
+ const owner = canonicalPublicKey(expectedOwner),
+ source = canonicalRelayOrigin(observedSource),
+ at = safeUnsignedInteger(observedAt);
+ if (
+ !owner ||
+ !source ||
+ at === undefined ||
+ typeof raw !== 'string' ||
+ !boundedUtf8(raw, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes)
+ )
+ return undefined;
+ const verified = verifyEnvelope(raw),
+ event = verified.ok && verifiedEnvelopeSnapshot(verified.value);
+ if (!event || event.kind !== 1059) return undefined;
+ const record = decodePrivateRecord(
+ JSON.stringify({
+ schema: 1,
+ family: 'received_envelope',
+ owner,
+ id: event.id,
+ revision: 0,
+ outer: raw,
+ observedAtMilliseconds: at,
+ sources: [source],
+ read: null
+ }),
+ owner,
+ event.id
+ );
+ if (!record.ok) return undefined;
+ const token = Object.freeze({}) as InboxEnvelope;
+ envelopes.set(token, { owner, id: event.id, source, record: record.value });
+ return token;
+}
+export function inboxEnvelopeSnapshot(token: InboxEnvelope) {
+ const row = envelopes.get(token);
+ return row && privateRecordSnapshot(row.record, row.owner, row.id);
+}
+export type InboxRetentionResult = Readonly<{
+ status:
+ | 'retained'
+ | 'duplicate'
+ | 'invalid'
+ | 'stopped'
+ | 'busy'
+ | PrivateStorageFailure;
+}>;
+// Ciphertext-only bookkeeping in the original owner namespace. No SDK work in
+// IDB; request success is insufficient without actual whole-wire readback.
+export async function retainInboxEnvelope(
+ repository: PrivateStorageRepository,
+ session: PrivateSession,
+ envelope: InboxEnvelope
+): Promise<InboxRetentionResult> {
+ const admitted = envelopes.get(envelope),
+ ownership = privateSessionOwnership(session);
+ if (
+ !admitted ||
+ !ownership?.current() ||
+ ownership.owner !== admitted.owner ||
+ typeof window === 'undefined' ||
+ !navigator.locks?.request
+ )
+ return { status: 'invalid' };
+ try {
+ return await navigator.locks.request(
+ 'harvestcircle:owner:' + admitted.owner,
+ { mode: 'exclusive', ifAvailable: true },
+ async (lock) => {
+ if (!lock) return { status: 'busy' };
+ if (!ownership.current()) return { status: 'stopped' };
+ const loaded = await loadPrivateRecord(
+ repository,
+ 'received_envelopes',
+ admitted.id
+ );
+ if (!ownership.current()) return { status: 'stopped' };
+ let next = admitted.record,
+ base: PrivateRecordHandle | null = null,
+ duplicate = false;
+ if (loaded.ok) {
+ const row = privateRecordSnapshot(
+ loaded.value,
+ admitted.owner,
+ admitted.id
+ );
+ if (!row || row.family !== 'received_envelope')
+ return { status: 'conflict' };
+ // Keep the first valid signed outer and first observation. Equal outer
+ // IDs are deduplication, not trusted inner-message identity/display.
+ duplicate = true;
+ base = loaded.value;
+ if (row.sources.includes(admitted.source))
+ return { status: 'duplicate' };
+ if (
+ row.sources.length >= RELAY_BUDGETS.inbox ||
+ row.revision === Number.MAX_SAFE_INTEGER
+ )
+ return { status: 'capacity' };
+ const decoded = decodePrivateRecord(
+ JSON.stringify({
+ ...row,
+ revision: row.revision + 1,
+ sources: [...row.sources, admitted.source]
+ }),
+ admitted.owner,
+ admitted.id
+ );
+ if (!decoded.ok) return { status: 'invalid' };
+ next = decoded.value;
+ } else if (loaded.reason !== 'invalid_record')
+ return { status: loaded.reason };
+ if (!ownership.current()) return { status: 'stopped' };
+ const committed = await commitPrivateRecord(repository, next, base);
+ if (!committed.ok) return { status: committed.reason };
+ const readback = await loadPrivateRecord(
+ repository,
+ 'received_envelopes',
+ admitted.id
+ );
+ if (!ownership.current()) return { status: 'stopped' };
+ if (!readback.ok) return { status: 'unknown_completion' };
+ if (
+ privateRecordWire(readback.value, admitted.owner, admitted.id) !==
+ privateRecordWire(next, admitted.owner, admitted.id)
+ )
+ return { status: 'conflict' };
+ return { status: duplicate ? 'duplicate' : 'retained' };
+ }
+ );
+ } catch {
+ return { status: 'unknown_completion' };
+ }
+}
diff --git a/web/tests/e2e/harness/inbox-ingress.ts b/web/tests/e2e/harness/inbox-ingress.ts
@@ -0,0 +1,138 @@
+import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts';
+import {
+ validateRelayPolicy,
+ readRelayPolicy
+} from '../../../src/lib/config/relays.ts';
+import {
+ createPrivateSession,
+ closePrivateSession,
+ privateSessionOwnership
+} from '../../../src/lib/runtime/private-session.ts';
+import {
+ captureInboxIngress,
+ startInboxIngress,
+ stopInboxIngress,
+ inboxIngressSnapshot,
+ type InboxIngress
+} from '../../../src/lib/nostr/inbox-ingress.ts';
+import { loadPrivateRecord } from '../../../src/lib/persistence/private-storage.ts';
+import { privateRecordSnapshot } from '../../../src/lib/persistence/private-records.ts';
+import {
+ getPublicStore,
+ publicStoreEnvelope
+} from '../../../src/lib/nostr/public-store.ts';
+export async function makeFixture() {
+ const f = await makeRecoveryFixture();
+ const policy = validateRelayPolicy(
+ JSON.stringify({
+ ...readRelayPolicy(f.context.policy),
+ messagingEnabled: true
+ })
+ );
+ if (!policy) throw Error('fixture policy unavailable');
+ const session = await createPrivateSession(
+ f.identity,
+ 'reviewed_private_session'
+ );
+ if (!session) throw Error('missing genuine session');
+ const capture = privateSessionOwnership(session)!;
+ const publicStore = getPublicStore()!;
+ const self = (await f.row())!.record.self;
+ let ingress: InboxIngress | undefined;
+ let authorized = true;
+ let restoreFault = () => {};
+ return {
+ ...f,
+ outer: self.wire,
+ outerId: self.eventId,
+ capture(access = true, review: unknown = 'reviewed_private_inbox_receive') {
+ ingress = captureInboxIngress(
+ f.repository,
+ session,
+ policy,
+ f.context.own,
+ access
+ ? (context) => ({
+ ...context,
+ receive: 'qualified_exercised',
+ archive: 'qualified_exercised',
+ current: () => authorized && capture.current()
+ })
+ : undefined,
+ review
+ );
+ return !!ingress;
+ },
+ start(review: unknown = 'reviewed_private_inbox_receive') {
+ if (!ingress) return false;
+ return startInboxIngress(ingress, review);
+ },
+ stop() {
+ if (ingress) stopInboxIngress(ingress);
+ },
+ snapshot: () => ingress && inboxIngressSnapshot(ingress),
+ async stored(id = self.eventId) {
+ const row = await loadPrivateRecord(
+ f.repository,
+ 'received_envelopes',
+ id
+ );
+ return row.ok ? privateRecordSnapshot(row.value, f.owner, id) : undefined;
+ },
+ publicContains: (id = self.eventId) =>
+ !!publicStoreEnvelope(publicStore, id),
+ countsValue: () => f.counts(),
+ revokeAccess() {
+ authorized = false;
+ },
+ logout() {
+ closePrivateSession(session);
+ },
+ restoreFault() {
+ restoreFault();
+ },
+ faultRetention(kind: 'abort' | 'readback') {
+ const put = Reflect.get<IDBObjectStore, 'put'>(
+ IDBObjectStore.prototype,
+ 'put'
+ );
+ const cursor = Reflect.get<IDBIndex, 'openCursor'>(
+ IDBIndex.prototype,
+ 'openCursor'
+ );
+ let written = false;
+ IDBObjectStore.prototype.put = function (
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const request = put.apply(this, args);
+ if (this.name === 'received_envelopes') {
+ written = true;
+ if (kind === 'abort') this.transaction.abort();
+ }
+ return request;
+ };
+ IDBIndex.prototype.openCursor = function (
+ ...args: Parameters<IDBIndex['openCursor']>
+ ) {
+ if (
+ kind === 'readback' &&
+ written &&
+ this.objectStore.name === 'received_envelopes' &&
+ this.objectStore.transaction.mode === 'readonly'
+ )
+ throw Error('actual post-put inbox readback failure');
+ return cursor.apply(this, args);
+ };
+ restoreFault = () => {
+ IDBObjectStore.prototype.put = put;
+ IDBIndex.prototype.openCursor = cursor;
+ };
+ },
+ close() {
+ restoreFault();
+ if (ingress) stopInboxIngress(ingress);
+ closePrivateSession(session);
+ f.close();
+ }
+ };
+}
diff --git a/web/tests/e2e/inbox-ingress.spec.ts b/web/tests/e2e/inbox-ingress.spec.ts
@@ -0,0 +1,313 @@
+import { test, expect } from '@playwright/test';
+import { build } from 'vite';
+import { fileURLToPath } from 'node:url';
+import { once } from 'node:events';
+import { WebSocketServer } from 'ws';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Fixture from './harness/inbox-ingress.ts';
+declare global {
+ interface Window {
+ hcp090: typeof Fixture;
+ hcp090Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let requests: unknown[][] = [],
+ frames: Record<string, unknown>[] = [];
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ sockets = new WebSocketServer({
+ host: '127.0.0.1',
+ port: 0,
+ maxPayload: 65536
+ });
+ await once(sockets, 'listening');
+ const address = sockets.address();
+ if (!address || typeof address === 'string')
+ throw Error('loopback unavailable');
+ endpoint = 'ws://127.0.0.1:' + address.port;
+ sockets.on('connection', (socket) =>
+ socket.on('message', (bytes) => {
+ const raw = Buffer.isBuffer(bytes)
+ ? bytes
+ : Array.isArray(bytes)
+ ? Buffer.concat(bytes)
+ : Buffer.from(bytes),
+ frame = JSON.parse(raw.toString()) as unknown[];
+ if (frame[0] !== 'REQ') return;
+ requests.push(frame);
+ for (const event of frames)
+ socket.send(JSON.stringify(['EVENT', frame[1], event]));
+ socket.send(JSON.stringify(['EOSE', frame[1]]));
+ })
+ );
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/inbox-ingress.ts', import.meta.url)
+ ),
+ name: 'hcp090',
+ formats: ['iife']
+ }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw Error('bundle unavailable');
+ const chunks = output.output.filter((x) => x.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+});
+test.afterAll(async () => {
+ for (const socket of sockets.clients) socket.terminate();
+ await new Promise<void>((resolve) => sockets.close(() => resolve()));
+ await server.close();
+});
+test.beforeEach(async ({ page }) => {
+ requests = [];
+ frames = [];
+ await page.addInitScript(
+ ({ endpoint }) => {
+ const Native = window.WebSocket;
+ window.WebSocket = class extends Native {
+ constructor(url: string | URL, protocols?: string | string[]) {
+ const origin = new URL(String(url)).origin;
+ if (origin !== 'wss://archive.example.org')
+ throw Error('unapproved receive destination');
+ super(endpoint, protocols);
+ }
+ };
+ },
+ { endpoint }
+ );
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async () => {
+ window.hcp090Fixture = await window.hcp090.makeFixture();
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => window.hcp090Fixture?.close());
+});
+test('explicit own inbox receive persists signed outer before decrypt and keeps it out of catalog', async ({
+ page
+}) => {
+ const before = await page.evaluate(() => ({
+ wire: window.hcp090Fixture.outer,
+ owner: window.hcp090Fixture.owner,
+ counts: window.hcp090Fixture.countsValue()
+ }));
+ frames = [JSON.parse(before.wire) as Record<string, unknown>];
+ const capture = await page.evaluate(() => window.hcp090Fixture.capture());
+ expect(capture).toBe(true);
+ expect(requests).toEqual([]);
+ expect(await page.evaluate(() => window.hcp090Fixture.start())).toBe(true);
+ await expect
+ .poll(() =>
+ page.evaluate(async () => !!(await window.hcp090Fixture.stored()))
+ )
+ .toBe(true);
+ const r = await page.evaluate(async () => ({
+ row: await window.hcp090Fixture.stored(),
+ counts: window.hcp090Fixture.countsValue(),
+ catalog: window.hcp090Fixture.publicContains(),
+ snapshot: window.hcp090Fixture.snapshot()
+ }));
+ expect(r.row).toMatchObject({
+ family: 'received_envelope',
+ owner: before.owner,
+ outer: before.wire,
+ read: null
+ });
+ expect(r.catalog).toBe(false);
+ expect(r.counts.encrypts).toBe(before.counts.encrypts);
+ expect(r.counts.decrypts).toBe(before.counts.decrypts);
+ expect(r.counts.signs).toBe(before.counts.signs);
+ expect(requests).toHaveLength(1);
+ expect(requests[0][2]).toMatchObject({
+ kinds: [1059],
+ '#p': [before.owner],
+ limit: 200
+ });
+});
+test('a bad signature is isolated and the following valid outer remains retainable', async ({
+ page
+}) => {
+ const wire = await page.evaluate(() => window.hcp090Fixture.outer);
+ const valid = JSON.parse(wire) as Record<string, unknown>;
+ frames = [{ ...valid, sig: '0'.repeat(128) }, valid];
+ expect(await page.evaluate(() => window.hcp090Fixture.capture())).toBe(true);
+ await page.evaluate(() => window.hcp090Fixture.start());
+ await expect
+ .poll(() =>
+ page.evaluate(async () => !!(await window.hcp090Fixture.stored()))
+ )
+ .toBe(true);
+ expect(await page.evaluate(() => window.hcp090Fixture.publicContains())).toBe(
+ false
+ );
+});
+test('duplicate candidates charge ingress before ciphertext retention dedup', async ({
+ page
+}) => {
+ const wire = await page.evaluate(() => window.hcp090Fixture.outer);
+ const event = JSON.parse(wire) as Record<string, unknown>;
+ frames = [event, event, event];
+ await page.evaluate(() => {
+ window.hcp090Fixture.capture();
+ window.hcp090Fixture.start();
+ });
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.hcp090Fixture.snapshot()?.candidates)
+ )
+ .toBe(3);
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.hcp090Fixture.snapshot()?.duplicates)
+ )
+ .toBe(2);
+ expect(await page.evaluate(() => window.hcp090Fixture.publicContains())).toBe(
+ false
+ );
+});
+test('absent exercised access or wrong review cannot start private receive', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => ({
+ without: window.hcp090Fixture.capture(false),
+ wrong: window.hcp090Fixture.capture(true, 'unreviewed'),
+ started: window.hcp090Fixture.start()
+ }));
+ expect(r).toEqual({ without: false, wrong: false, started: false });
+ expect(requests).toEqual([]);
+});
+test('Stop before start prevents REQ and retention', async ({ page }) => {
+ const result = await page.evaluate(() => {
+ const f = window.hcp090Fixture;
+ f.capture();
+ f.stop();
+ return { start: f.start(), snapshot: f.snapshot() };
+ });
+ expect(result.start).toBe(false);
+ expect(result.snapshot).toMatchObject({
+ state: 'stopped',
+ retained: 0,
+ candidates: 0
+ });
+ expect(requests).toEqual([]);
+});
+test('revoked actual access between capture and start prevents REQ', async ({
+ page
+}) => {
+ expect(
+ await page.evaluate(() => {
+ const f = window.hcp090Fixture;
+ f.capture();
+ f.revokeAccess();
+ return f.start();
+ })
+ ).toBe(false);
+ expect(requests).toEqual([]);
+});
+test('logout after capture fences start and closes the admitted private lifecycle', async ({
+ page
+}) => {
+ const result = await page.evaluate(() => {
+ const f = window.hcp090Fixture;
+ f.capture();
+ f.logout();
+ return { start: f.start(), snapshot: f.snapshot() };
+ });
+ expect(result.start).toBe(false);
+ expect(result.snapshot?.state).toBe('stopped');
+ expect(requests).toEqual([]);
+});
+test('duplicate flood is charged before dedup and stops at the fixed 500-candidate budget', async ({
+ page
+}) => {
+ const wire = await page.evaluate(() => window.hcp090Fixture.outer);
+ frames = Array.from(
+ { length: 501 },
+ () => JSON.parse(wire) as Record<string, unknown>
+ );
+ await page.evaluate(() => {
+ window.hcp090Fixture.capture();
+ window.hcp090Fixture.start();
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.pending))
+ .toBe(0);
+ await expect
+ .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.reason))
+ .toBe('budget');
+ const snapshot = await page.evaluate(() => window.hcp090Fixture.snapshot());
+ expect(snapshot?.candidates).toBe(500);
+ expect(requests).toHaveLength(1);
+ expect(await page.evaluate(() => window.hcp090Fixture.publicContains())).toBe(
+ false
+ );
+});
+test('actual received-envelope transaction abort cannot report retained ciphertext', async ({
+ page
+}) => {
+ frames = [
+ JSON.parse(await page.evaluate(() => window.hcp090Fixture.outer)) as Record<
+ string,
+ unknown
+ >
+ ];
+ await page.evaluate(() => {
+ const f = window.hcp090Fixture;
+ f.faultRetention('abort');
+ f.capture();
+ f.start();
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.state))
+ .toBe('needs_action');
+ const result = await page.evaluate(async () => {
+ const f = window.hcp090Fixture;
+ f.restoreFault();
+ return { snapshot: f.snapshot(), row: await f.stored() };
+ });
+ expect(result.snapshot).toMatchObject({ retained: 0, reason: 'aborted' });
+ expect(result.row).toBeUndefined();
+});
+test('actual post-put readback failure stays uncertain despite durable ciphertext', async ({
+ page
+}) => {
+ frames = [
+ JSON.parse(await page.evaluate(() => window.hcp090Fixture.outer)) as Record<
+ string,
+ unknown
+ >
+ ];
+ await page.evaluate(() => {
+ const f = window.hcp090Fixture;
+ f.faultRetention('readback');
+ f.capture();
+ f.start();
+ });
+ await expect
+ .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.state))
+ .toBe('needs_action');
+ const result = await page.evaluate(async () => {
+ const f = window.hcp090Fixture;
+ f.restoreFault();
+ return { snapshot: f.snapshot(), row: await f.stored() };
+ });
+ expect(result.snapshot).toMatchObject({
+ retained: 0,
+ reason: 'unknown_completion'
+ });
+ expect(result.row).toMatchObject({ family: 'received_envelope', read: null });
+});
diff --git a/web/tests/unit/inbox-ingress.test.ts b/web/tests/unit/inbox-ingress.test.ts
@@ -0,0 +1,138 @@
+import { describe, it, expect } from 'vitest';
+import {
+ generateSecretKey,
+ getPublicKey,
+ finalizeEvent
+} from 'applesauce-core/helpers';
+import { nip44 } from 'applesauce-core/helpers/encryption';
+import {
+ admitInboxEnvelope,
+ inboxEnvelopeSnapshot
+} from '../../src/lib/persistence/inbox-envelope-repository.ts';
+import {
+ inboxIngressSnapshot,
+ type InboxIngress
+} from '../../src/lib/nostr/inbox-ingress.ts';
+function fixture(kind = 1059, target?: string, content?: string) {
+ const key = generateSecretKey(),
+ other = generateSecretKey();
+ try {
+ const owner = getPublicKey(other),
+ destination = target ?? owner,
+ conversation = nip44.v2.utils.getConversationKey(key, destination);
+ try {
+ const event = finalizeEvent(
+ {
+ kind,
+ created_at: 1700000000,
+ tags: [['p', destination]],
+ content:
+ content ??
+ nip44.v2.encrypt(
+ 'Encrypted structural outer fixture only',
+ conversation
+ )
+ },
+ key
+ );
+ return { owner, event, wire: JSON.stringify(event) };
+ } finally {
+ conversation.fill(0);
+ }
+ } finally {
+ key.fill(0);
+ other.fill(0);
+ }
+}
+describe('bounded untrusted owner-addressed inbox outer', () => {
+ it('admits actual signed1059 as ciphertext only, not a trusted nested message', () => {
+ const f = fixture(),
+ token = admitInboxEnvelope(
+ f.wire,
+ f.owner,
+ 'wss://archive.example.org',
+ 100
+ );
+ expect(token).toBeDefined();
+ const view = inboxEnvelopeSnapshot(token!);
+ expect(view).toMatchObject({
+ owner: f.owner,
+ id: f.event.id,
+ outer: f.wire,
+ read: null
+ });
+ expect(view).not.toHaveProperty('body');
+ expect(view).not.toHaveProperty('sender');
+ });
+ it('wrong destination cannot enter this owner namespace', () => {
+ const f = fixture();
+ expect(
+ admitInboxEnvelope(
+ f.wire,
+ 'b'.repeat(64),
+ 'wss://archive.example.org',
+ 100
+ )
+ ).toBeUndefined();
+ });
+ it('bad signature is rejected before retention', () => {
+ const f = fixture();
+ expect(
+ admitInboxEnvelope(
+ JSON.stringify({ ...f.event, sig: '0'.repeat(128) }),
+ f.owner,
+ 'wss://archive.example.org',
+ 100
+ )
+ ).toBeUndefined();
+ });
+ it('non1059 never becomes a private inbox outer', () => {
+ const f = fixture(14);
+ expect(
+ admitInboxEnvelope(f.wire, f.owner, 'wss://archive.example.org', 100)
+ ).toBeUndefined();
+ });
+ it('unsupported outer ciphertext version is isolated despite valid outer signature', () => {
+ const f = fixture(
+ 1059,
+ undefined,
+ btoa(String.fromCharCode(1) + 'a'.repeat(100))
+ );
+ expect(
+ admitInboxEnvelope(f.wire, f.owner, 'wss://archive.example.org', 100)
+ ).toBeUndefined();
+ });
+ it('32KiB outer bound is enforced before retained credit', () => {
+ const f = fixture(
+ 1059,
+ undefined,
+ btoa(String.fromCharCode(2) + 'a'.repeat(30000))
+ );
+ expect(
+ admitInboxEnvelope(f.wire, f.owner, 'wss://archive.example.org', 100)
+ ).toBeUndefined();
+ });
+ it('malformed scope and observer metadata do not coerce caller values', () => {
+ const f = fixture();
+ let calls = 0;
+ const object = {
+ toString() {
+ calls++;
+ return f.wire;
+ }
+ };
+ expect(
+ admitInboxEnvelope(object, f.owner, 'wss://archive.example.org', 100)
+ ).toBeUndefined();
+ expect(
+ admitInboxEnvelope(f.wire, f.owner, 'ws://127.0.0.1', 100)
+ ).toBeUndefined();
+ expect(
+ admitInboxEnvelope(f.wire, f.owner, 'wss://archive.example.org', -1)
+ ).toBeUndefined();
+ expect(calls).toBe(0);
+ });
+ it('forged ingress handle cannot acquire a private receive workflow', () => {
+ expect(inboxIngressSnapshot({} as InboxIngress)).toBeUndefined();
+ });
+});