commit af032995af12f4b3e575224514abb2288fa19499
parent ec67c7988d0745af37183f65a6a786aa819d5caa
Author: triesap <tyson@radroots.org>
Date: Fri, 9 Oct 2026 01:22:41 +0000
messages: retain separate recipient and archive delivery facts (HCP-086)
- Bind named role/target outcomes and separate exact readback to stored1059 artifacts
- Preserve prior facts with idempotent lateACK, full-wire CAS and actual readback
- Renew genuine paired custody only after a verified receipt successor
- Derive cautious recipient/archive status with unit and real browser coverage
Diffstat:
8 files changed, 1269 insertions(+), 3 deletions(-)
diff --git a/web/src/lib/messaging/send-status.ts b/web/src/lib/messaging/send-status.ts
@@ -0,0 +1,75 @@
+import {
+ privateRecordSnapshot,
+ type PrivateRecordHandle,
+ type PrivateTargetReceipt
+} from '../persistence/private-records.ts';
+// Pure detached status from strict local evidence, never EventStore seen-relay
+// metadata, a remote read receipt, effect permission or a person-delivery claim.
+export function privateSendStatus(
+ record: PrivateRecordHandle,
+ owner: unknown,
+ id: unknown
+) {
+ const row = privateRecordSnapshot(record, owner, id);
+ if (!row || row.family !== 'private_send_operation') return undefined;
+ const facts = row.receipts ?? [];
+ function role(role: 'peer' | 'self_archive', targets: readonly string[]) {
+ const matching = facts.filter((f) => f.role === role);
+ function origins(status: PrivateTargetReceipt['status']) {
+ return targets.filter((origin) =>
+ matching.some((f) => f.origin === origin && f.status === status)
+ );
+ }
+ const acceptedTargets = origins('accepted'),
+ readbackTargets = origins('readback');
+ return {
+ acceptedTargets,
+ readbackTargets,
+ pendingTargets: targets.filter(
+ (origin) => !acceptedTargets.includes(origin)
+ ),
+ refusedTargets: origins('refused'),
+ timeoutTargets: origins('timed_out'),
+ unknownTargets: origins('unknown'),
+ stoppedTargets: origins('stopped')
+ };
+ }
+ const recipientFacts = role(
+ 'peer',
+ row.deliveryPlan?.routes.peer.targets ?? []
+ ),
+ archiveFacts = role(
+ 'self_archive',
+ row.deliveryPlan?.routes.archive.targets ?? []
+ );
+ const recipient = {
+ ...recipientFacts,
+ state: recipientFacts.acceptedTargets.length
+ ? ('accepted_by_inbox_relay' as const)
+ : ('unknown' as const)
+ },
+ archive = {
+ ...archiveFacts,
+ state:
+ archiveFacts.acceptedTargets.length &&
+ !archiveFacts.pendingTargets.length
+ ? ('accepted_by_inbox_relay' as const)
+ : ('pending' as const)
+ };
+ const anyAccepted =
+ recipient.acceptedTargets.length + archive.acceptedTargets.length > 0,
+ partial =
+ anyAccepted &&
+ (recipient.state === 'unknown' ||
+ archive.state === 'pending' ||
+ recipient.pendingTargets.length > 0);
+ const labels: string[] = [
+ 'Saved encrypted locally',
+ recipient.state === 'accepted_by_inbox_relay'
+ ? 'Accepted by recipient inbox relay'
+ : 'Recipient delivery unknown',
+ ...(partial ? ['Partial delivery'] : []),
+ ...(archive.state === 'pending' ? ['Sender archive pending'] : [])
+ ];
+ return { recipient, archive, partial, labels };
+}
diff --git a/web/src/lib/persistence/private-receipts.ts b/web/src/lib/persistence/private-receipts.ts
@@ -0,0 +1,180 @@
+import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import { exactLocalFields } from '../contracts/local-records.ts';
+import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
+import {
+ decodePrivateRecord,
+ privateRecordSnapshot,
+ privateRecordWire,
+ type PrivateRecordHandle,
+ type PrivateTargetReceipt
+} from './private-records.ts';
+import {
+ commitPrivateRecord,
+ loadPrivateRecord,
+ type PrivateStorageRepository,
+ type PrivateStorageFailure
+} from './private-storage.ts';
+declare const transitionBrand: unique symbol;
+export type PrivateReceiptTransition = Readonly<{ [transitionBrand]: true }>;
+type Transition = Readonly<{
+ owner: string;
+ id: string;
+ base: PrivateRecordHandle;
+ next: PrivateRecordHandle;
+ baseWire: string;
+ nextWire: string;
+}>;
+const transitions = new WeakMap<PrivateReceiptTransition, Transition>();
+type Result =
+ | Readonly<{ ok: true; value: PrivateReceiptTransition }>
+ | Readonly<{
+ ok: false;
+ reason: 'invalid_record' | 'conflict' | 'revision_exhausted';
+ }>;
+function sameFact(a: PrivateTargetReceipt, b: PrivateTargetReceipt) {
+ return (
+ a.actionId === b.actionId &&
+ a.origin === b.origin &&
+ a.role === b.role &&
+ a.attempt === b.attempt &&
+ a.eventId === b.eventId &&
+ a.status === b.status
+ );
+}
+// Primitive canonical JSON only. Strict complete private codec binds the named
+// role/destination to the persisted outer ID and verifies exact readback bytes.
+// This is observed local bookkeeping, not network provenance/effect authority.
+export function preparePrivateReceiptTransition(
+ record: PrivateRecordHandle,
+ owner: unknown,
+ id: unknown,
+ receiptWire: unknown
+): Result {
+ const row = privateRecordSnapshot(record, owner, id),
+ baseWire = privateRecordWire(record, owner, id);
+ if (
+ !row ||
+ row.family !== 'private_send_operation' ||
+ !row.peerArtifact ||
+ !row.deliveryPlan ||
+ !baseWire ||
+ typeof receiptWire !== 'string' ||
+ !boundedUtf8(receiptWire, LOCAL_PERSISTENCE_BUDGETS.privateSendBytes)
+ )
+ return { ok: false, reason: 'invalid_record' };
+ try {
+ const fact: unknown = JSON.parse(receiptWire);
+ if (
+ JSON.stringify(fact) !== receiptWire ||
+ !exactLocalFields(fact, [
+ 'actionId',
+ 'origin',
+ 'role',
+ 'attempt',
+ 'eventId',
+ 'status',
+ 'observedAtMilliseconds',
+ 'readbackWire'
+ ])
+ )
+ return { ok: false, reason: 'invalid_record' };
+ const checked = decodePrivateRecord(
+ JSON.stringify({ ...row, receipts: [fact] }),
+ row.owner,
+ row.id
+ );
+ if (!checked.ok) return { ok: false, reason: 'invalid_record' };
+ const admitted = privateRecordSnapshot(checked.value, row.owner, row.id);
+ if (
+ !admitted ||
+ admitted.family !== 'private_send_operation' ||
+ !admitted.receipts
+ )
+ return { ok: false, reason: 'invalid_record' };
+ const nextFact = admitted.receipts[0],
+ existing = row.receipts?.find((r) => sameFact(r, nextFact));
+ let next = record,
+ nextWire = baseWire;
+ if (existing) {
+ if (existing.readbackWire !== nextFact.readbackWire)
+ return { ok: false, reason: 'conflict' };
+ } else {
+ if (row.revision === Number.MAX_SAFE_INTEGER)
+ return { ok: false, reason: 'revision_exhausted' };
+ const decoded = decodePrivateRecord(
+ JSON.stringify({
+ ...row,
+ revision: row.revision + 1,
+ receipts: [...(row.receipts ?? []), nextFact]
+ }),
+ row.owner,
+ row.id
+ );
+ if (!decoded.ok) return { ok: false, reason: 'invalid_record' };
+ next = decoded.value;
+ const wire = privateRecordWire(next, row.owner, row.id);
+ if (!wire) return { ok: false, reason: 'invalid_record' };
+ nextWire = wire;
+ }
+ const token = Object.freeze({}) as PrivateReceiptTransition;
+ transitions.set(token, {
+ owner: row.owner,
+ id: row.id,
+ base: record,
+ next,
+ baseWire,
+ nextWire
+ });
+ return { ok: true, value: token };
+ } catch {
+ return { ok: false, reason: 'invalid_record' };
+ }
+}
+export function privateReceiptTransitionSnapshot(
+ token: PrivateReceiptTransition,
+ owner: unknown,
+ id: unknown
+) {
+ const saved = transitions.get(token);
+ return saved && saved.owner === owner && saved.id === id
+ ? { ...saved }
+ : undefined;
+}
+export type PrivateReceiptCommitResult =
+ | Readonly<{ status: 'saved' | 'existing'; record: PrivateRecordHandle }>
+ | Readonly<{ status: PrivateStorageFailure | 'invalid' }>;
+// No SDK work in IDB. Request success is insufficient: actual exact full-wire
+// readback must acknowledge the CAS append. Unknown commits stay uncertain.
+export async function commitPrivateReceiptTransition(
+ repository: PrivateStorageRepository,
+ token: PrivateReceiptTransition
+): Promise<PrivateReceiptCommitResult> {
+ const saved = transitions.get(token);
+ if (!saved) return { status: 'invalid' };
+ try {
+ let status: 'saved' | 'existing' = 'existing';
+ if (saved.baseWire !== saved.nextWire) {
+ const committed = await commitPrivateRecord(
+ repository,
+ saved.next,
+ saved.base
+ );
+ if (!committed.ok) return { status: committed.reason };
+ status = committed.value.state === 'existing' ? 'existing' : 'saved';
+ }
+ const readback = await loadPrivateRecord(
+ repository,
+ 'private_sends',
+ saved.id
+ );
+ if (!readback.ok) return { status: 'unknown_completion' };
+ if (
+ privateRecordWire(readback.value, saved.owner, saved.id) !==
+ saved.nextWire
+ )
+ return { status: 'conflict' };
+ return { status, record: readback.value };
+ } catch {
+ return { status: 'unknown_completion' };
+ }
+}
diff --git a/web/src/lib/persistence/private-records.ts b/web/src/lib/persistence/private-records.ts
@@ -12,6 +12,7 @@ import type { InboxRouteSnapshot } from '../messaging/inbox-routing.ts';
import {
LOCAL_PERSISTENCE_BUDGETS,
PRIVATE_TRANSPORT_BUDGETS,
+ PRIVATE_PUBLICATION_BUDGETS,
RELAY_BUDGETS
} from '../config/budgets.ts';
export type PrivateSendReservation = Readonly<{
@@ -42,6 +43,20 @@ export type PrivateSendOperation = Readonly<{
// Absent in original self-only records; never an implicit migration or an
// effect capability. Both ciphertext roles are required for a paired plan.
deliveryPlan?: PrivateDeliveryPlan;
+ // Optional compatibility metadata; local observations are never a sender
+ // factory proof, effect permission, person delivery or remote read receipt.
+ receipts?: readonly PrivateTargetReceipt[];
+}>;
+export type PrivateTargetReceipt = Readonly<{
+ actionId: string;
+ origin: string;
+ role: 'peer' | 'self_archive';
+ attempt: number;
+ eventId: string;
+ status:
+ 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped' | 'readback';
+ observedAtMilliseconds: number;
+ readbackWire: string | null;
}>;
export type PrivateDeliveryPlan = Readonly<{
state: 'prepared';
@@ -346,6 +361,52 @@ function artifact(
outer(value.wire, destination) === value.eventId
);
}
+function receipt(
+ value: unknown,
+ self: PrivateCiphertextArtifact,
+ peer: PrivateCiphertextArtifact,
+ plan: PrivateDeliveryPlan
+): boolean {
+ if (
+ !exactLocalFields(value, [
+ 'actionId',
+ 'origin',
+ 'role',
+ 'attempt',
+ 'eventId',
+ 'status',
+ 'observedAtMilliseconds',
+ 'readbackWire'
+ ]) ||
+ !canonicalLocalId(value.actionId) ||
+ (value.role !== 'peer' && value.role !== 'self_archive') ||
+ typeof value.origin !== 'string' ||
+ canonicalRelayOrigin(value.origin) !== value.origin ||
+ !unsigned(value.attempt) ||
+ value.attempt < 1 ||
+ value.attempt > PRIVATE_PUBLICATION_BUDGETS.attemptsPerTargetAction ||
+ !unsigned(value.observedAtMilliseconds) ||
+ typeof value.status !== 'string' ||
+ ![
+ 'accepted',
+ 'refused',
+ 'timed_out',
+ 'unknown',
+ 'stopped',
+ 'readback'
+ ].includes(value.status)
+ )
+ return false;
+ const route = value.role === 'peer' ? plan.routes.peer : plan.routes.archive,
+ outer = value.role === 'peer' ? peer : self;
+ return (
+ route.targets.includes(value.origin) &&
+ value.eventId === outer.eventId &&
+ (value.status === 'readback'
+ ? value.readbackWire === outer.wire
+ : value.readbackWire === null)
+ );
+}
// Strict local storage codec only, never installed-account/effect authorization,
// genuine sender factory proof, nested authenticity, read receipt or Send.
export function decodePrivateRecord(
@@ -382,7 +443,8 @@ export function decodePrivateRecord(
...reservationFields,
'self',
'peerArtifact',
- ...(fields.deliveryPlan === undefined ? [] : ['deliveryPlan'])
+ ...(fields.deliveryPlan === undefined ? [] : ['deliveryPlan']),
+ ...(fields.receipts === undefined ? [] : ['receipts'])
]) ||
!sendMetadata(fields, owner, id) ||
!unsigned(fields.revision) ||
@@ -392,7 +454,24 @@ export function decodePrivateRecord(
!artifact(fields.peerArtifact, fields.peer as string)) ||
(fields.deliveryPlan !== undefined &&
(fields.peerArtifact === null ||
- !deliveryPlan(fields.deliveryPlan, owner, fields.peer as string)))
+ !deliveryPlan(
+ fields.deliveryPlan,
+ owner,
+ fields.peer as string
+ ))) ||
+ (fields.receipts !== undefined &&
+ (!Array.isArray(fields.receipts) ||
+ fields.peerArtifact === null ||
+ fields.deliveryPlan === undefined ||
+ !deliveryPlan(fields.deliveryPlan, owner, fields.peer as string) ||
+ !fields.receipts.every((value) =>
+ receipt(
+ value,
+ fields.self as PrivateCiphertextArtifact,
+ fields.peerArtifact as PrivateCiphertextArtifact,
+ fields.deliveryPlan as PrivateDeliveryPlan
+ )
+ )))
)
return failed('malformed');
record = {
@@ -414,7 +493,10 @@ export function decodePrivateRecord(
},
...(fields.deliveryPlan === undefined
? {}
- : { deliveryPlan: fields.deliveryPlan })
+ : { deliveryPlan: fields.deliveryPlan }),
+ ...(fields.receipts === undefined
+ ? {}
+ : { receipts: fields.receipts as PrivateTargetReceipt[] })
};
} else if (fields.family === 'received_envelope') {
if (
diff --git a/web/src/lib/persistence/private-sends.ts b/web/src/lib/persistence/private-sends.ts
@@ -34,6 +34,11 @@ import {
type PrivateStorageFailure,
type PrivateStorageResult
} from './private-storage.ts';
+import {
+ preparePrivateReceiptTransition,
+ commitPrivateReceiptTransition,
+ type PrivateReceiptCommitResult
+} from './private-receipts.ts';
declare const acknowledgementBrand: unique symbol;
export type SelfRecoveryAcknowledgement = Readonly<{
@@ -520,3 +525,67 @@ export async function verifyPairedDeliveryAcknowledgement(
saved.wire
);
}
+// Only the already genuine current pair can renew its exact custody after a
+// controlled append of named receipt metadata. A decoded namespace row alone
+// cannot mint this acknowledgment. Earlier permissions invalidate on revision.
+export async function commitPairedDeliveryReceipt(
+ repository: PrivateStorageRepository,
+ receipt: PairedDeliveryAcknowledgement,
+ receiptWire: unknown
+): Promise<PrivateReceiptCommitResult> {
+ const saved = pairedAcknowledgements.get(receipt);
+ if (!saved?.current()) return { status: 'invalid' };
+ try {
+ const loaded = await loadPrivateRecord(
+ repository,
+ 'private_sends',
+ saved.record.id
+ );
+ if (!loaded.ok) return { status: loaded.reason };
+ if (
+ !saved.current() ||
+ privateRecordWire(loaded.value, saved.record.owner, saved.record.id) !==
+ saved.wire
+ )
+ return { status: 'conflict' };
+ const transition = preparePrivateReceiptTransition(
+ loaded.value,
+ saved.record.owner,
+ saved.record.id,
+ receiptWire
+ );
+ if (!transition.ok) return { status: 'invalid' };
+ const committed = await commitPrivateReceiptTransition(
+ repository,
+ transition.value
+ );
+ if (!('record' in committed)) return committed;
+ const row = privateRecordSnapshot(
+ committed.record,
+ saved.record.owner,
+ saved.record.id
+ ),
+ wire = privateRecordWire(
+ committed.record,
+ saved.record.owner,
+ saved.record.id
+ );
+ if (!saved.current()) return { status: 'unknown_completion' };
+ if (
+ !row ||
+ row.family !== 'private_send_operation' ||
+ !wire ||
+ !row.peerArtifact ||
+ !row.deliveryPlan
+ )
+ return { status: 'conflict' };
+ pairedAcknowledgements.set(receipt, {
+ record: row,
+ wire,
+ current: saved.current
+ });
+ return committed;
+ } catch {
+ return { status: 'unknown_completion' };
+ }
+}
diff --git a/web/src/lib/persistence/private-storage.ts b/web/src/lib/persistence/private-storage.ts
@@ -210,6 +210,13 @@ function validTransition(
return (
base.family === 'private_send_reservation' ||
(JSON.stringify(base.self) === JSON.stringify(next.self) &&
+ (base.deliveryPlan === undefined ||
+ JSON.stringify(base.deliveryPlan) ===
+ JSON.stringify(next.deliveryPlan)) &&
+ (base.receipts ?? []).every(
+ (fact, index) =>
+ JSON.stringify(fact) === JSON.stringify(next.receipts?.[index])
+ ) &&
(base.peerArtifact === null ||
JSON.stringify(base.peerArtifact) ===
JSON.stringify(next.peerArtifact)))
diff --git a/web/tests/e2e/harness/private-receipts.ts b/web/tests/e2e/harness/private-receipts.ts
@@ -0,0 +1,207 @@
+import { makeFixture as makeDeliveryFixture } from './private-publisher.ts';
+import { preparedPairedDelivery } from '../../../src/lib/messaging/prepare-send.ts';
+import {
+ commitPairedDeliveryReceipt,
+ verifyPairedDeliveryAcknowledgement,
+ type PairedDeliveryAcknowledgement
+} from '../../../src/lib/persistence/private-sends.ts';
+import {
+ loadPrivateRecord,
+ createPrivateStorageRepository
+} from '../../../src/lib/persistence/private-storage.ts';
+import {
+ privateRecordSnapshot,
+ privateRecordWire
+} from '../../../src/lib/persistence/private-records.ts';
+import {
+ preparePrivateReceiptTransition,
+ commitPrivateReceiptTransition
+} from '../../../src/lib/persistence/private-receipts.ts';
+import { privateSendStatus } from '../../../src/lib/messaging/send-status.ts';
+import { reservedSendSnapshot } from '../../../src/lib/messaging/send-identity.ts';
+import {
+ openBrowserDatabase,
+ closeBrowserDatabase
+} from '../../../src/lib/persistence/database.ts';
+export { commitPairedDeliveryReceipt };
+const action = '12345678-1234-4234-8234-123456789abd';
+export async function readExisting(owner: string, id: string) {
+ const opened = await openBrowserDatabase();
+ if (opened.state !== 'ready') throw Error('storage unavailable');
+ try {
+ const repository = createPrivateStorageRepository(opened.owner, owner);
+ if (!repository) throw Error('namespace unavailable');
+ const loaded = await loadPrivateRecord(repository, 'private_sends', id);
+ if (!loaded.ok) throw Error('record unavailable');
+ return {
+ row: privateRecordSnapshot(loaded.value, owner, id),
+ status: privateSendStatus(loaded.value, owner, id)
+ };
+ } finally {
+ closeBrowserDatabase(opened.owner);
+ }
+}
+export async function makeFixture() {
+ const f = await makeDeliveryFixture();
+ let restore = () => {},
+ faults = 0;
+ const command = reservedSendSnapshot(f.reserved);
+ if (!command) throw Error('missing actual command');
+ const id = command.id;
+ async function handle() {
+ const loaded = await loadPrivateRecord(f.repository, 'private_sends', id);
+ if (!loaded.ok) throw Error('missing private record: ' + loaded.reason);
+ return loaded.value;
+ }
+ async function state() {
+ const h = await handle();
+ return {
+ row: privateRecordSnapshot(h, f.owner, id),
+ wire: privateRecordWire(h, f.owner, id),
+ status: privateSendStatus(h, f.owner, id)
+ };
+ }
+ async function fact(
+ role: 'peer' | 'self_archive',
+ status: string,
+ time = 100,
+ readbackWire: string | null = null
+ ) {
+ const row = await f.storedPair();
+ if (!row?.peerArtifact) throw Error('missing actual pair');
+ return {
+ actionId: action,
+ role,
+ origin: role === 'peer' ? f.peerOrigin : f.archiveOrigin,
+ attempt: 1,
+ eventId: role === 'peer' ? row.peerArtifact.eventId : row.self.eventId,
+ status,
+ observedAtMilliseconds: time,
+ readbackWire
+ };
+ }
+ async function observe(
+ role: 'peer' | 'self_archive',
+ status: string,
+ time = 100,
+ readbackWire: string | null = null
+ ) {
+ const receipt = preparedPairedDelivery(f.preparation);
+ if (!receipt) throw Error('missing genuine pair acknowledgment');
+ const wire = JSON.stringify(await fact(role, status, time, readbackWire));
+ return commitPairedDeliveryReceipt(f.repository, receipt, wire);
+ }
+ async function race() {
+ const base = await handle(),
+ a = preparePrivateReceiptTransition(
+ base,
+ f.owner,
+ id,
+ JSON.stringify(await fact('peer', 'accepted'))
+ ),
+ b = preparePrivateReceiptTransition(
+ base,
+ f.owner,
+ id,
+ JSON.stringify(await fact('self_archive', 'accepted'))
+ );
+ if (!a.ok || !b.ok) throw Error('missing receipt transitions');
+ return Promise.all([
+ commitPrivateReceiptTransition(f.repository, a.value),
+ commitPrivateReceiptTransition(f.repository, b.value)
+ ]);
+ }
+ async function genuineRace() {
+ const peer = await fact('peer', 'accepted'),
+ archive = await fact('self_archive', 'accepted');
+ const receipt = preparedPairedDelivery(f.preparation);
+ if (!receipt) throw Error('missing genuine paired receipt');
+ const results = await Promise.all([
+ commitPairedDeliveryReceipt(f.repository, receipt, JSON.stringify(peer)),
+ commitPairedDeliveryReceipt(
+ f.repository,
+ receipt,
+ JSON.stringify(archive)
+ )
+ ]);
+ const observed = await state();
+ const winner =
+ observed.row?.family === 'private_send_operation'
+ ? observed.row.receipts?.[0].role
+ : undefined;
+ if (!winner) throw Error('missing winning receipt');
+ return {
+ results,
+ observed,
+ verified: await verified(),
+ remaining: await f.deliver(winner === 'peer' ? 'self_archive' : 'peer')
+ };
+ }
+ function failAfterPut(mode: 'abort' | 'readback') {
+ const put = Reflect.get<IDBObjectStore, 'put'>(
+ IDBObjectStore.prototype,
+ 'put'
+ ),
+ cursor = Reflect.get<IDBIndex, 'openCursor'>(
+ IDBIndex.prototype,
+ 'openCursor'
+ );
+ IDBObjectStore.prototype.put = function (
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const request = put.apply(this, args);
+ if (this.name === 'private_sends') {
+ faults++;
+ if (mode === 'abort') this.transaction.abort();
+ else
+ IDBIndex.prototype.openCursor = function (
+ ...args: Parameters<IDBIndex['openCursor']>
+ ) {
+ if (this.objectStore.name === 'private_sends')
+ throw Error('controlled actual receipt readback failure');
+ return cursor.apply(this, args);
+ };
+ }
+ return request;
+ };
+ restore = () => {
+ IDBObjectStore.prototype.put = put;
+ IDBIndex.prototype.openCursor = cursor;
+ };
+ }
+ async function forged() {
+ return commitPairedDeliveryReceipt(
+ f.repository,
+ {} as PairedDeliveryAcknowledgement,
+ JSON.stringify(await fact('peer', 'accepted'))
+ );
+ }
+ async function verified() {
+ const receipt = preparedPairedDelivery(f.preparation);
+ return receipt
+ ? verifyPairedDeliveryAcknowledgement(f.repository, receipt)
+ : false;
+ }
+ return {
+ ...f,
+ id,
+ handle,
+ state,
+ fact,
+ observe,
+ race,
+ genuineRace,
+ failAfterPut,
+ forged,
+ verified,
+ faults: () => faults,
+ clearFault() {
+ restore();
+ restore = () => {};
+ },
+ close() {
+ restore();
+ f.close();
+ }
+ };
+}
diff --git a/web/tests/e2e/private-receipts.spec.ts b/web/tests/e2e/private-receipts.spec.ts
@@ -0,0 +1,353 @@
+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/private-receipts.ts';
+declare global {
+ interface Window {
+ hcp086: typeof Fixture;
+ hcp086Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>,
+ sockets: WebSocketServer,
+ endpoint: string,
+ bundle: string;
+let frames: unknown[][] = [],
+ response = true;
+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[];
+ frames.push(frame);
+ if (frame[0] === 'EVENT')
+ socket.send(
+ JSON.stringify([
+ 'OK',
+ (frame[1] as { id: string }).id,
+ response,
+ response ? '' : 'blocked: fixture refusal'
+ ])
+ );
+ })
+ );
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: fileURLToPath(
+ new URL('./harness/private-receipts.ts', import.meta.url)
+ ),
+ name: 'hcp086',
+ 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();
+});
+async function load(page: import('@playwright/test').Page) {
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+}
+test.beforeEach(async ({ page }) => {
+ frames = [];
+ response = true;
+ 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 (
+ !['wss://peer.example.org', 'wss://archive.example.org'].includes(
+ origin
+ )
+ )
+ throw Error('unapproved fixture destination');
+ super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols);
+ }
+ };
+ },
+ { endpoint }
+ );
+ await load(page);
+ await page.evaluate(async () => {
+ window.hcp086Fixture = await window.hcp086.makeFixture();
+ await window.hcp086Fixture.prepare();
+ });
+});
+test.afterEach(async ({ page }) => {
+ if (!page.isClosed())
+ await page.evaluate(() => window.hcp086Fixture?.close());
+});
+test('actual archive ACK persists without claiming recipient receipt', async ({
+ page
+}) => {
+ const result = await page.evaluate(async () => {
+ const f = window.hcp086Fixture,
+ attempt = await f.deliver('self_archive'),
+ saved = await f.observe('self_archive', attempt.status);
+ return { attempt, saved, state: await f.state() };
+ });
+ expect(result.attempt.status).toBe('accepted');
+ expect(result.saved.status).toBe('saved');
+ expect(result.state.status?.recipient.state).toBe('unknown');
+ expect(result.state.status?.archive.state).toBe('accepted_by_inbox_relay');
+ expect(frames.filter((f) => f[0] === 'EVENT')).toHaveLength(1);
+});
+test('canonical receipt successor retains genuine custody for the remaining exact archive artifact', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture,
+ original = await f.storedPair(),
+ peer = await f.deliver('peer'),
+ saved = await f.observe('peer', peer.status),
+ verified = await f.verified(),
+ archive = await f.deliver('self_archive'),
+ savedArchive = await f.observe('self_archive', archive.status);
+ return {
+ original,
+ peer,
+ saved,
+ verified,
+ archive,
+ savedArchive,
+ state: await f.state()
+ };
+ });
+ expect(r.saved.status).toBe('saved');
+ expect(r.verified).toBe(true);
+ expect(r.archive.status).toBe('accepted');
+ expect(r.savedArchive.status).toBe('saved');
+ expect(r.state.status?.partial).toBe(false);
+ expect(
+ r.state.row?.family === 'private_send_operation' && r.state.row.self
+ ).toEqual(r.original!.self);
+ expect(
+ frames.filter((f) => f[0] === 'EVENT').map((f) => JSON.stringify(f[1]))
+ ).toEqual([r.original!.peerArtifact!.wire, r.original!.self.wire]);
+});
+test('late duplicate actual ACK is idempotent without changing the retained first observation', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture,
+ a = await f.deliver('peer');
+ await f.observe('peer', a.status, 100);
+ const before = await f.state(),
+ again = await f.observe('peer', a.status, 200);
+ return { before, again, after: await f.state() };
+ });
+ expect(r.again.status).toBe('existing');
+ expect(r.after.wire).toBe(r.before.wire);
+ expect(frames.filter((f) => f[0] === 'EVENT')).toHaveLength(1);
+});
+test('actual named refusal stays distinct from recipient success and archive pending', async ({
+ page
+}) => {
+ response = false;
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture,
+ a = await f.deliver('peer');
+ return {
+ attempt: a,
+ saved: await f.observe('peer', a.status),
+ state: await f.state()
+ };
+ });
+ expect(r.attempt.status).toBe('refused');
+ expect(r.saved.status).toBe('saved');
+ expect(r.state.status?.recipient.state).toBe('unknown');
+ expect(r.state.status?.archive.state).toBe('pending');
+});
+test('exact observed ciphertext readback is retained separately from acceptance', async ({
+ page
+}) => {
+ await page.evaluate(async () => {
+ await window.hcp086Fixture.deliver('peer');
+ });
+ const event = frames.find((f) => f[0] === 'EVENT')?.[1];
+ expect(event).toBeDefined();
+ const r = await page.evaluate(async (wire) => {
+ const f = window.hcp086Fixture;
+ return {
+ saved: await f.observe('peer', 'readback', 100, wire),
+ state: await f.state()
+ };
+ }, JSON.stringify(event));
+ expect(r.saved.status).toBe('saved');
+ expect(r.state.status?.recipient.readbackTargets).toEqual([
+ 'wss://peer.example.org'
+ ]);
+ expect(r.state.status?.recipient.acceptedTargets).toEqual([]);
+});
+test('real full-wire CAS races preserve the winning role and reject stale receipt append', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture;
+ return { results: await f.race(), state: await f.state() };
+ });
+ expect(r.results.map((x) => x.status).sort()).toEqual(['conflict', 'saved']);
+ expect(
+ r.state.row?.family === 'private_send_operation' && r.state.row.receipts
+ ).toHaveLength(1);
+ expect(frames).toEqual([]);
+});
+test('concurrent genuine receipt renewal keeps one exact winner and admits only its remaining stored artifact', async ({
+ page
+}) => {
+ const r = await page.evaluate(() => window.hcp086Fixture.genuineRace());
+ expect(r.results.map((x) => x.status).sort()).toEqual(['conflict', 'saved']);
+ expect(r.verified).toBe(true);
+ expect(
+ r.observed.row?.family === 'private_send_operation' &&
+ r.observed.row.receipts
+ ).toHaveLength(1);
+ expect(r.remaining.status).toBe('accepted');
+ const events = frames.filter((f) => f[0] === 'EVENT');
+ expect(events).toHaveLength(1);
+ const row = r.observed.row;
+ if (!row || row.family !== 'private_send_operation')
+ throw Error('missing winning row');
+ const winner = row.receipts![0].role;
+ expect(JSON.stringify(events[0][1])).toBe(
+ winner === 'peer' ? row.self.wire : row.peerArtifact!.wire
+ );
+});
+test('native put request followed by actual abort never acknowledges a receipt', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture,
+ before = await f.state();
+ f.failAfterPut('abort');
+ const saved = await f.observe('peer', 'accepted');
+ const faults = f.faults();
+ f.clearFault();
+ return { before, saved, faults, after: await f.state() };
+ });
+ expect(r.faults).toBe(1);
+ expect(r.saved.status).toBe('aborted');
+ expect(r.after.wire).toBe(r.before.wire);
+});
+test('failed actual post-put readback preserves uncertainty and cannot renew effect custody', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture;
+ f.failAfterPut('readback');
+ const saved = await f.observe('peer', 'accepted'),
+ faults = f.faults();
+ f.clearFault();
+ return {
+ saved,
+ faults,
+ verified: await f.verified(),
+ state: await f.state(),
+ attempt: await f.deliver('self_archive')
+ };
+ });
+ expect(r.faults).toBe(1);
+ expect(r.saved.status).toBe('unknown_completion');
+ expect(r.verified).toBe(false);
+ expect(
+ r.state.row?.family === 'private_send_operation' && r.state.row.receipts
+ ).toHaveLength(1);
+ expect(r.attempt.status).toBe('stopped');
+ expect(frames).toEqual([]);
+});
+test('reload retains named receipt uncertainty as local evidence without sender presence', async ({
+ page
+}) => {
+ const identity = await page.evaluate(async () => {
+ const f = window.hcp086Fixture;
+ await f.observe('peer', 'unknown');
+ return { owner: f.owner, id: f.id };
+ });
+ await load(page);
+ const state = await page.evaluate(
+ ({ owner, id }) => window.hcp086.readExisting(owner, id),
+ identity
+ );
+ expect(state.status?.recipient.state).toBe('unknown');
+ expect(
+ state.row?.family === 'private_send_operation' &&
+ state.row.receipts?.[0].status
+ ).toBe('unknown');
+ expect(frames).toEqual([]);
+});
+test('forged pair acknowledgment cannot append a fact or mint a successor', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture,
+ before = await f.state();
+ return { before, saved: await f.forged(), after: await f.state() };
+ });
+ expect(r.saved.status).toBe('invalid');
+ expect(r.after.wire).toBe(r.before.wire);
+ expect(frames).toEqual([]);
+});
+test('private receipt storage never contains the composer marker or plaintext fields', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture;
+ await f.observe('self_archive', 'unknown');
+ return { marker: f.marker, state: await f.state() };
+ });
+ expect(r.state.wire).not.toContain(r.marker);
+ expect(Object.keys(r.state.row ?? {})).not.toContain('body');
+ expect(JSON.stringify(r.state.status)).not.toMatch(
+ /Delivered|Seen|Order accepted|Reserved/
+ );
+ expect(frames).toEqual([]);
+});
+test('unrecognized record revision remains fenced after a genuine receipt successor', async ({
+ page
+}) => {
+ const r = await page.evaluate(async () => {
+ const f = window.hcp086Fixture;
+ await f.observe('peer', 'accepted');
+ await f.changePairRevision();
+ return {
+ verified: await f.verified(),
+ attempt: await f.deliver('self_archive')
+ };
+ });
+ expect(r.verified).toBe(false);
+ expect(r.attempt.status).toBe('stopped');
+ expect(frames).toEqual([]);
+});
diff --git a/web/tests/unit/private-receipts.test.ts b/web/tests/unit/private-receipts.test.ts
@@ -0,0 +1,293 @@
+import { describe, it, expect } from 'vitest';
+import {
+ generateSecretKey,
+ getPublicKey,
+ finalizeEvent
+} from 'applesauce-core/helpers';
+import { nip44 } from 'applesauce-core/helpers/encryption';
+import {
+ decodePrivateRecord,
+ privateRecordSnapshot,
+ privateRecordWire,
+ type PrivateRecordHandle
+} from '../../src/lib/persistence/private-records.ts';
+import {
+ preparePrivateReceiptTransition,
+ privateReceiptTransitionSnapshot
+} from '../../src/lib/persistence/private-receipts.ts';
+import { privateSendStatus } from '../../src/lib/messaging/send-status.ts';
+const command = '12345678-1234-4234-8234-123456789abc',
+ action = '12345678-1234-4234-8234-123456789abd';
+function fixture() {
+ const key = generateSecretKey(),
+ other = generateSecretKey();
+ let conversation: Uint8Array | undefined;
+ try {
+ const owner = getPublicKey(key),
+ peer = getPublicKey(other);
+ function artifact(destination: string) {
+ conversation = nip44.v2.utils.getConversationKey(key, destination);
+ try {
+ const event = finalizeEvent(
+ {
+ kind: 1059,
+ created_at: 1700000000,
+ tags: [['p', destination]],
+ content: nip44.v2.encrypt(
+ 'Structural codec fixture only',
+ conversation
+ )
+ },
+ key
+ );
+ return { eventId: event.id, wire: JSON.stringify(event) };
+ } finally {
+ conversation.fill(0);
+ }
+ }
+ function route(
+ author: string,
+ role: 'peer' | 'self_archive',
+ origin: string
+ ) {
+ return {
+ author,
+ role,
+ targets: [origin],
+ knownBase: { author, id: 'b'.repeat(64), createdAt: 1 },
+ sources: [{ source: 'wss://discovery.example.org', state: 'eose' }]
+ };
+ }
+ const row = {
+ schema: 1,
+ family: 'private_send_operation',
+ owner,
+ id: command,
+ revision: 2,
+ peer,
+ rumorHash: 'a'.repeat(64),
+ createdAt: 1700000000,
+ self: artifact(owner),
+ peerArtifact: artifact(peer),
+ deliveryPlan: {
+ state: 'prepared',
+ routes: {
+ peer: route(peer, 'peer', 'wss://peer.example.org'),
+ archive: route(owner, 'self_archive', 'wss://archive.example.org')
+ }
+ }
+ };
+ function handle(value: unknown = row) {
+ const result = decodePrivateRecord(JSON.stringify(value), owner, command);
+ if (!result.ok) throw Error('invalid structural fixture');
+ return result.value;
+ }
+ function fact(role: 'peer' | 'self_archive' = 'peer', status = 'accepted') {
+ return {
+ actionId: action,
+ role,
+ origin:
+ role === 'peer'
+ ? 'wss://peer.example.org'
+ : 'wss://archive.example.org',
+ attempt: 1,
+ eventId: role === 'peer' ? row.peerArtifact.eventId : row.self.eventId,
+ status,
+ observedAtMilliseconds: 100,
+ readbackWire: null
+ };
+ }
+ function transition(base: PrivateRecordHandle, f: unknown) {
+ return preparePrivateReceiptTransition(
+ base,
+ owner,
+ command,
+ JSON.stringify(f)
+ );
+ }
+ function next(base: PrivateRecordHandle, f: unknown) {
+ const result = transition(base, f);
+ if (!result.ok) throw Error('transition refused');
+ const saved = privateReceiptTransitionSnapshot(
+ result.value,
+ owner,
+ command
+ );
+ if (!saved) throw Error('missing transition');
+ return saved.next;
+ }
+ return { row, owner, handle, fact, transition, next };
+ } finally {
+ conversation?.fill(0);
+ key.fill(0);
+ other.fill(0);
+ }
+}
+describe('private named relay observations are separate local evidence', () => {
+ it('legacy paired ciphertext without receipt metadata stays readable and uncertain', () => {
+ const f = fixture(),
+ h = f.handle();
+ expect(privateRecordSnapshot(h, f.owner, command)).toEqual(f.row);
+ const s = privateSendStatus(h, f.owner, command)!;
+ expect(s.recipient.state).toBe('unknown');
+ expect(s.archive.state).toBe('pending');
+ });
+ it('forged record and transition handles cannot supply status or receipt custody', () => {
+ expect(
+ privateSendStatus({} as PrivateRecordHandle, 'a'.repeat(64), command)
+ ).toBeUndefined();
+ expect(
+ preparePrivateReceiptTransition(
+ {} as PrivateRecordHandle,
+ 'a'.repeat(64),
+ command,
+ '{}'
+ ).ok
+ ).toBe(false);
+ });
+ it('archive acceptance alone never means recipient acceptance', () => {
+ const f = fixture(),
+ h = f.next(f.handle(), f.fact('self_archive'));
+ const s = privateSendStatus(h, f.owner, command)!;
+ expect(s.recipient.state).toBe('unknown');
+ expect(s.archive.state).toBe('accepted_by_inbox_relay');
+ expect(s.labels).toContain('Recipient delivery unknown');
+ expect(s.partial).toBe(true);
+ });
+ it('recipient acceptance preserves the separate sender archive pending fact', () => {
+ const f = fixture(),
+ h = f.next(f.handle(), f.fact());
+ const s = privateSendStatus(h, f.owner, command)!;
+ expect(s.recipient.state).toBe('accepted_by_inbox_relay');
+ expect(s.archive.state).toBe('pending');
+ expect(s.labels).toContain('Sender archive pending');
+ });
+ it('late duplicate ACK is idempotent even when sampled later', () => {
+ const f = fixture(),
+ a = f.fact(),
+ base = f.next(f.handle(), a),
+ again = f.next(base, { ...a, observedAtMilliseconds: 200 });
+ expect(privateRecordWire(again, f.owner, command)).toBe(
+ privateRecordWire(base, f.owner, command)
+ );
+ });
+ it('distinct refusal and later acceptance observations are both retained', () => {
+ const f = fixture(),
+ a = f.next(f.handle(), f.fact('peer', 'refused')),
+ b = f.next(a, f.fact());
+ const row = privateRecordSnapshot(b, f.owner, command);
+ expect(
+ row?.family === 'private_send_operation' &&
+ row.receipts?.map((r) => r.status)
+ ).toEqual(['refused', 'accepted']);
+ expect(privateSendStatus(b, f.owner, command)?.recipient.state).toBe(
+ 'accepted_by_inbox_relay'
+ );
+ });
+ it('exact peer ciphertext readback is separate from a relay ACK', () => {
+ const f = fixture(),
+ fact = {
+ ...f.fact('peer', 'readback'),
+ readbackWire: f.row.peerArtifact.wire
+ },
+ h = f.next(f.handle(), fact),
+ s = privateSendStatus(h, f.owner, command)!;
+ expect(s.recipient.readbackTargets).toEqual(['wss://peer.example.org']);
+ expect(s.recipient.acceptedTargets).toEqual([]);
+ expect(s.recipient.state).toBe('unknown');
+ });
+ it('archive ciphertext cannot serve as peer readback', () => {
+ const f = fixture();
+ expect(
+ f.transition(f.handle(), {
+ ...f.fact('peer', 'readback'),
+ readbackWire: f.row.self.wire
+ }).ok
+ ).toBe(false);
+ });
+ it('wrong role destination event and unsupported plaintext fields refuse', () => {
+ const f = fixture(),
+ base = f.fact();
+ for (const bad of [
+ { ...base, role: 'publication' },
+ { ...base, origin: 'wss://other.example.org' },
+ { ...base, eventId: f.row.self.eventId },
+ { ...base, body: 'PRIVATE_TEXT' },
+ { ...base, readbackWire: f.row.peerArtifact.wire }
+ ])
+ expect(f.transition(f.handle(), bad).ok).toBe(false);
+ });
+ it('unsafe times attempts and arbitrary outcome strings refuse', () => {
+ const f = fixture(),
+ base = f.fact();
+ for (const bad of [
+ { ...base, attempt: 0 },
+ { ...base, attempt: 4 },
+ { ...base, observedAtMilliseconds: -1 },
+ { ...base, observedAtMilliseconds: Number.MAX_SAFE_INTEGER + 1 },
+ { ...base, status: 'delivered' }
+ ])
+ expect(f.transition(f.handle(), bad).ok).toBe(false);
+ });
+ it('unknown stopped timeout and refusal never imply recipient success', () => {
+ const f = fixture();
+ for (const status of ['unknown', 'stopped', 'timed_out', 'refused'])
+ expect(
+ privateSendStatus(
+ f.next(f.handle(), f.fact('peer', status)),
+ f.owner,
+ command
+ )?.recipient.state
+ ).toBe('unknown');
+ });
+ it('receipt transitions preserve exact original ciphertext and frozen routes', () => {
+ const f = fixture(),
+ base = f.handle(),
+ next = f.next(base, f.fact()),
+ row = privateRecordSnapshot(next, f.owner, command);
+ expect(row?.family === 'private_send_operation' && row.self).toEqual(
+ f.row.self
+ );
+ expect(
+ row?.family === 'private_send_operation' && row.peerArtifact
+ ).toEqual(f.row.peerArtifact);
+ expect(
+ row?.family === 'private_send_operation' && row.deliveryPlan
+ ).toEqual(f.row.deliveryPlan);
+ expect(privateRecordWire(base, f.owner, command)).toBe(
+ JSON.stringify(f.row)
+ );
+ });
+ it('revision exhaustion refuses a new fact', () => {
+ const f = fixture();
+ expect(
+ f.transition(
+ f.handle({ ...f.row, revision: Number.MAX_SAFE_INTEGER }),
+ f.fact()
+ ).ok
+ ).toBe(false);
+ });
+ it('receipt acquisition never coerces caller objects or noncanonical duplicate JSON', () => {
+ const f = fixture();
+ let calls = 0;
+ const input = {
+ toString() {
+ calls++;
+ return JSON.stringify(f.fact());
+ }
+ };
+ expect(
+ preparePrivateReceiptTransition(f.handle(), f.owner, command, input).ok
+ ).toBe(false);
+ expect(calls).toBe(0);
+ const raw = JSON.stringify(f.fact());
+ expect(
+ preparePrivateReceiptTransition(
+ f.handle(),
+ f.owner,
+ command,
+ '{"status":"accepted",' + raw.slice(1)
+ ).ok
+ ).toBe(false);
+ });
+});