app

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

inbox-probe-recovery.spec.ts (43303B)


      1 import { test, expect, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { once } from 'node:events';
      4 import { fileURLToPath } from 'node:url';
      5 import { WebSocketServer, type WebSocket } from 'ws';
      6 import { createStaticHarness } from '../integration/harness/static.ts';
      7 import type * as Fixture from './harness/inbox-probe-recovery.ts';
      8 declare global {
      9   interface Window {
     10     pr: typeof Fixture;
     11     prFixture: Awaited<ReturnType<typeof Fixture.makeRecoveryFixture>>;
     12     prFresh: Awaited<ReturnType<typeof Fixture.openRecoveryContext>>;
     13     prPending?: Promise<unknown>;
     14     prRelease?: () => void;
     15     prRestore?: () => void;
     16     prHosted?: ReturnType<typeof Fixture.createHostedProvider>;
     17     prHostedContext?: Awaited<ReturnType<typeof Fixture.openRecoveryContext>>;
     18   }
     19 }
     20 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     21   sockets: WebSocketServer,
     22   endpoint: string,
     23   bundle: string,
     24   head = '';
     25 const physical = new Set<WebSocket>(),
     26   archived = new Map<string, Record<string, unknown>>(),
     27   frames: { origin: string; frame: unknown[] }[] = [];
     28 test.beforeAll(async () => {
     29   server = await createStaticHarness();
     30   sockets = new WebSocketServer({
     31     host: '127.0.0.1',
     32     port: 0,
     33     maxPayload: 65536
     34   });
     35   await once(sockets, 'listening');
     36   const address = sockets.address();
     37   if (!address || typeof address === 'string')
     38     throw Error('actual loopback fixture');
     39   endpoint = 'ws://127.0.0.1:' + address.port;
     40   sockets.on('connection', (socket, request) => {
     41     physical.add(socket);
     42     socket.on('close', () => physical.delete(socket));
     43     const origin = new URL(request.url!, 'http://127.0.0.1').searchParams.get(
     44       'origin'
     45     )!;
     46     socket.on('message', (bytes) => {
     47       const raw = Buffer.isBuffer(bytes)
     48         ? bytes
     49         : Array.isArray(bytes)
     50           ? Buffer.concat(bytes)
     51           : Buffer.from(bytes);
     52       const frame = JSON.parse(raw.toString()) as unknown[];
     53       frames.push({ origin, frame });
     54       if (frame[0] === 'REQ') {
     55         const filter = frame[2] as { kinds?: number[]; ids?: string[] };
     56         if (filter.kinds?.includes(10050) && head)
     57           socket.send(JSON.stringify(['EVENT', frame[1], JSON.parse(head)]));
     58         if (filter.kinds?.includes(1059)) {
     59           const event = archived.get(filter.ids?.[0] ?? '');
     60           if (event) socket.send(JSON.stringify(['EVENT', frame[1], event]));
     61         }
     62         socket.send(JSON.stringify(['EOSE', frame[1]]));
     63       } else if (frame[0] === 'EVENT') {
     64         const event = frame[1] as { id: string };
     65         archived.set(event.id, event);
     66         socket.send(JSON.stringify(['OK', event.id, true, '']));
     67       }
     68     });
     69   });
     70   const result = await build({
     71     configFile: false,
     72     logLevel: 'silent',
     73     build: {
     74       write: false,
     75       minify: false,
     76       lib: {
     77         entry: fileURLToPath(
     78           new URL('./harness/inbox-probe-recovery.ts', import.meta.url)
     79         ),
     80         name: 'pr',
     81         formats: ['iife']
     82       }
     83     }
     84   });
     85   const output = Array.isArray(result) ? result[0] : result;
     86   if (!('output' in output)) throw Error('compiled actual source fixture');
     87   const chunks = output.output.filter((x) => x.type === 'chunk');
     88   expect(chunks).toHaveLength(1);
     89   bundle = chunks[0].code;
     90 });
     91 test.afterAll(async () => {
     92   for (const socket of sockets.clients) socket.terminate();
     93   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     94   await server.close();
     95 });
     96 test.beforeEach(async ({ page }) => {
     97   await expect.poll(() => physical.size).toBe(0);
     98   head = '';
     99   frames.length = 0;
    100   archived.clear();
    101   await page.addInitScript(
    102     ({ endpoint }) => {
    103       const Native = window.WebSocket;
    104       window.WebSocket = class extends Native {
    105         constructor(url: string | URL, protocols?: string | string[]) {
    106           const origin = new URL(String(url)).origin;
    107           if (
    108             ![
    109               'wss://discovery.example.org',
    110               'wss://inbox.example.org',
    111               'wss://peer.example.org',
    112               'wss://archive.example.org'
    113             ].includes(origin)
    114           )
    115             throw Error('unapproved fixture origin');
    116           super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols);
    117         }
    118       };
    119     },
    120     { endpoint }
    121   );
    122   await page.goto(server.url + '/search');
    123   await page.addScriptTag({ content: bundle });
    124   head = await page.evaluate(async () => {
    125     window.prFixture = await window.pr.makeRecoveryFixture();
    126     return window.prFixture.preferenceWire(['wss://inbox.example.org']);
    127   });
    128   await page.evaluate(async () => {
    129     const f = window.prFixture;
    130     await f.capture();
    131     if (
    132       (await f.reserve()).status !== 'reserved' ||
    133       (await f.prepare()) !== 'wrapped' ||
    134       (await f.commitOriginal()).status !== 'prepared'
    135     )
    136       throw Error('actual cold stored original');
    137   });
    138 });
    139 test.afterEach(async ({ page }) => {
    140   if (!page.isClosed())
    141     await page.evaluate(() => {
    142       window.prRestore?.();
    143       window.prRelease?.();
    144       window.prHostedContext?.close();
    145       window.prHosted?.close();
    146       window.prFixture.close();
    147     });
    148 });
    149 async function fresh(page: Page) {
    150   await page.evaluate(async () => {
    151     window.prFresh = await window.prFixture.fresh();
    152   });
    153 }
    154 function privateFrames() {
    155   return frames.filter((x) => x.origin !== 'wss://discovery.example.org');
    156 }
    157 async function originalReadback(page: Page) {
    158   await page.evaluate(async () => {
    159     const f = window.prFixture,
    160       publication = await f.publish();
    161     if (
    162       publication.status !== 'accepted' ||
    163       (await f.append(publication)).status !== 'saved'
    164     )
    165       throw Error('actual original B1');
    166     const readback = await f.read();
    167     if (
    168       readback.status !== 'readback' ||
    169       (await f.appendRead(readback)).status !== 'saved'
    170     )
    171       throw Error('actual original B2');
    172   });
    173 }
    174 test('genuine ordinary and C1 readers/proofs cannot cross into recovered-probe families', async ({
    175   page
    176 }) => {
    177   await originalReadback(page);
    178   const result = await page.evaluate(async () => {
    179     const f = window.prFixture,
    180       nonce = await f.nonce();
    181     if (!('proof' in nonce)) throw Error('genuine current C1 proof');
    182     const id = f.snapshot()!.record.id;
    183     const ordinary = window.pr.captureSelfRecoveryReader(
    184       f.repository,
    185       f.identity,
    186       id,
    187       'reviewed_self_decryption'
    188     )!;
    189     const recovery = window.pr.captureInboxProbeRecoveryReader(
    190       f.repository,
    191       f.identity,
    192       f.session,
    193       f.policy,
    194       f.controller()!,
    195       f.qualification,
    196       id,
    197       'reviewed_inbox_probe_recovery'
    198     )!;
    199     const before = f.counts();
    200     const c1Reader = await window.pr.recoverInboxProbe(
    201       f.nonceReader()! as unknown as Parameters<
    202         typeof window.pr.recoverInboxProbe
    203       >[0]
    204     );
    205     const ordinaryReader = await window.pr.recoverInboxProbe(
    206       ordinary as unknown as Parameters<typeof window.pr.recoverInboxProbe>[0]
    207     );
    208     const c1Proof = window.pr.recoveredInboxProbeBinding(
    209       nonce.proof as unknown as Parameters<
    210         typeof window.pr.recoveredInboxProbeBinding
    211       >[0],
    212       f.repository,
    213       f.session,
    214       f.controller()!,
    215       f.policy,
    216       f.qualification
    217     );
    218     const noEffects = JSON.stringify(before) === JSON.stringify(f.counts());
    219     const recovered = await window.pr.recoverInboxProbe(recovery);
    220     const wrongC1 = await window.pr.readInboxProbeNonce(
    221       recovery as unknown as Parameters<typeof window.pr.readInboxProbeNonce>[0]
    222     );
    223     return {
    224       ordinaryGenuine: !!ordinary,
    225       c1Reader,
    226       ordinaryReader,
    227       c1Proof: !!c1Proof,
    228       noEffects,
    229       recovery: recovered.status,
    230       wrongC1
    231     };
    232   });
    233   expect(result).toEqual({
    234     ordinaryGenuine: true,
    235     c1Reader: { status: 'invalid' },
    236     ordinaryReader: { status: 'invalid' },
    237     c1Proof: false,
    238     noEffects: true,
    239     recovery: 'recovered',
    240     wrongC1: { status: 'invalid' }
    241   });
    242 });
    243 test('genuine current C1 memory proof cannot replace actual original stored ciphertext decryption', async ({
    244   page
    245 }) => {
    246   await originalReadback(page);
    247   const result = await page.evaluate(async () => {
    248     const f = window.prFixture,
    249       nonce = await f.nonce();
    250     if (!('proof' in nonce)) throw Error('genuine current C1 proof');
    251     const reader = window.pr.captureInboxProbeRecoveryReader(
    252       f.repository,
    253       f.identity,
    254       f.session,
    255       f.policy,
    256       f.controller()!,
    257       f.qualification,
    258       f.snapshot()!.record.id,
    259       'reviewed_inbox_probe_recovery'
    260     )!;
    261     f.mode('wrong_decrypt');
    262     const before = await f.stored(),
    263       result = await window.pr.recoverInboxProbe(reader);
    264     return {
    265       status: result.status,
    266       same: JSON.stringify(before) === JSON.stringify(await f.stored())
    267     };
    268   });
    269   expect(result).toEqual({ status: 'mismatch', same: true });
    270 });
    271 for (const alias of ['whitespace', 'key-order'])
    272   for (const phase of ['before', 'final-key'])
    273     test(`physical ${alias} alias at ${phase} cannot pass canonical-only native comparison`, async ({
    274       page
    275     }) => {
    276       await fresh(page);
    277       const result = await page.evaluate(
    278         async ({ alias, phase }) => {
    279           const f = window.prFixture,
    280             r = window.prFresh,
    281             row = (await f.stored()).find((x) => x.id === r.localId)!;
    282           const decoded = window.pr.decodePrivateRecord(
    283             row.wire,
    284             row.owner,
    285             row.id
    286           );
    287           if (!decoded.ok) throw Error('original strict native row');
    288           const record = JSON.parse(row.wire) as Record<string, unknown>;
    289           const wire =
    290             alias === 'whitespace'
    291               ? JSON.stringify(record, null, 1)
    292               : JSON.stringify(
    293                   Object.fromEntries(Object.entries(record).reverse())
    294                 );
    295           const alternate = window.pr.decodePrivateRecord(
    296             wire,
    297             row.owner,
    298             row.id
    299           );
    300           if (
    301             !alternate.ok ||
    302             window.pr.privateRecordWire(alternate.value, row.owner, row.id) !==
    303               window.pr.privateRecordWire(decoded.value, row.owner, row.id)
    304           )
    305             throw Error('actual canonical-equivalent physical alias');
    306           if (phase === 'before') await f.inject([{ ...row, wire }]);
    307           else
    308             window.prRestore = f.keyCallback(3, () =>
    309               f.inject([{ ...row, wire }])
    310             );
    311           const result = await r.recover();
    312           return {
    313             status: result.status,
    314             proof: !!r.binding(),
    315             aliasRetained:
    316               (await f.stored()).find((x) => x.id === r.localId)?.wire === wire
    317           };
    318         },
    319         { alias, phase }
    320       );
    321       expect(result.status).not.toBe('recovered');
    322       expect(result.proof).toBe(false);
    323       expect(result.aliasRetained).toBe(true);
    324     });
    325 test('actual B1/B2 then memory teardown recovers the immutable original with no ordinary send, new artifact, native growth or traffic', async ({
    326   page
    327 }) => {
    328   await page.evaluate(async () => {
    329     const f = window.prFixture;
    330     const pub = await f.publish();
    331     if (pub.status !== 'accepted' || (await f.append(pub)).status !== 'saved')
    332       throw Error('actual B1');
    333     const read = await f.read();
    334     if (
    335       read.status !== 'readback' ||
    336       (await f.appendRead(read)).status !== 'saved'
    337     )
    338       throw Error('actual B2');
    339   });
    340   await fresh(page);
    341   const traffic = privateFrames().length;
    342   const result = await page.evaluate(async () => {
    343     const f = window.prFixture,
    344       r = window.prFresh,
    345       before = f.counts(),
    346       rows = await f.stored(),
    347       reader = r.capture()!,
    348       repeat = r.capture();
    349     const inert = f.counts(),
    350       receiver = f.decryptCallback(0, (wire) => wire);
    351     const originalRandom = crypto.getRandomValues.bind(crypto),
    352       originalUuid = crypto.randomUUID.bind(crypto);
    353     let randomness = 0;
    354     crypto.getRandomValues = () => {
    355       randomness++;
    356       throw Error('new recovery randomness');
    357     };
    358     crypto.randomUUID = () => {
    359       randomness++;
    360       throw Error('new recovery command');
    361     };
    362     let recovered: Awaited<ReturnType<typeof r.recover>>;
    363     try {
    364       recovered = await r.recover(reader);
    365     } finally {
    366       crypto.getRandomValues = originalRandom;
    367       crypto.randomUUID = originalUuid;
    368     }
    369     const again = await r.recover(reader),
    370       binding = r.binding(),
    371       after = f.counts();
    372     return {
    373       status: recovered.status,
    374       again: again.status,
    375       sameProof:
    376         'proof' in recovered &&
    377         'proof' in again &&
    378         recovered.proof === again.proof,
    379       sameReader: reader === repeat,
    380       before,
    381       inert,
    382       after,
    383       rowsSame: JSON.stringify(rows) === JSON.stringify(await f.stored()),
    384       receivers: receiver.receivers(),
    385       randomness,
    386       binding: binding && {
    387         command: binding.command,
    388         rumorHash: binding.rumorHash,
    389         eventId: binding.eventId,
    390         keys: Object.keys(binding)
    391       },
    392       oldNonceGone: !window.pr.inboxProbeRumorWire(
    393         f.probeIdentity()!,
    394         f.session
    395       ),
    396       readiness: window.pr.inboxAccessControllerSnapshot(r.access)?.readiness
    397     };
    398   });
    399   expect(result.status).toBe('recovered');
    400   expect(result.again).toBe('recovered');
    401   expect(result.sameProof).toBe(true);
    402   expect(result.sameReader).toBe(true);
    403   expect(result.inert).toEqual(result.before);
    404   expect(result.after.decrypts - result.before.decrypts).toBe(2);
    405   expect(result.after.keys - result.before.keys).toBe(3);
    406   expect(result.after.signs).toBe(result.before.signs);
    407   expect(result.after.encrypts).toBe(result.before.encrypts);
    408   expect(result.randomness).toBe(0);
    409   expect(result.receivers).toBe(2);
    410   expect(result.rowsSame).toBe(true);
    411   expect(result.oldNonceGone).toBe(true);
    412   expect(result.readiness).toBe('unavailable');
    413   expect(result.binding?.keys).not.toContain('rumorWire');
    414   expect(privateFrames()).toHaveLength(traffic);
    415 });
    416 for (const bad of [
    417   'review',
    418   'id',
    419   'repository',
    420   'identity',
    421   'session',
    422   'policy',
    423   'controller',
    424   'operator',
    425   'unconfigured',
    426   'unsupported',
    427   'copy'
    428 ])
    429   test(`inert recovery capture rejects ${bad} before provider or native work`, async ({
    430     page
    431   }) => {
    432     await fresh(page);
    433     const result = await page.evaluate((bad) => {
    434       const f = window.prFixture,
    435         r = window.prFresh,
    436         before = f.counts();
    437       let native = 0;
    438       const original = Object.getOwnPropertyDescriptor(
    439         IDBDatabase.prototype,
    440         'transaction'
    441       )!.value as IDBDatabase['transaction'];
    442       IDBDatabase.prototype.transaction = function (
    443         ...args: Parameters<IDBDatabase['transaction']>
    444       ) {
    445         native++;
    446         return original.apply(this, args);
    447       };
    448       let reader;
    449       try {
    450         reader = window.pr.captureInboxProbeRecoveryReader(
    451           bad === 'repository' ? f.foreignRepository() : r.repository,
    452           bad === 'identity' ? f.identity : r.identity,
    453           bad === 'session' ? f.session : r.session,
    454           bad === 'policy' ? f.copiedPolicy() : r.policy,
    455           bad === 'controller'
    456             ? f.controller()!
    457             : bad === 'copy'
    458               ? { ...r.access }
    459               : r.access,
    460           bad === 'operator'
    461             ? ({} as typeof r.operator)
    462             : bad === 'unconfigured'
    463               ? f.operator(false, true)
    464               : bad === 'unsupported'
    465                 ? f.operator(true)
    466                 : r.operator,
    467           bad === 'id' ? 'not-original' : r.localId,
    468           bad === 'review' ? true : 'reviewed_inbox_probe_recovery'
    469         );
    470       } finally {
    471         IDBDatabase.prototype.transaction = original;
    472       }
    473       return { admitted: !!reader, before, after: f.counts(), native };
    474     }, bad);
    475     expect(result.admitted).toBe(false);
    476     expect(result.after).toEqual(result.before);
    477     expect(result.native).toBe(0);
    478   });
    479 test('invalid controller/session/policy associations never retry actual retained failed private cleanup', async ({
    480   page
    481 }) => {
    482   const result = await page.evaluate(() => {
    483     const f = window.prFixture;
    484     let retries = 0;
    485     const off = window.pr.subscribePrivateSessionClose(f.session, () => {
    486       retries++;
    487       throw Error('retained original cleanup');
    488     });
    489     window.pr.closePrivateSession(f.session);
    490     const before = retries;
    491     const fake = {} as Parameters<
    492       typeof window.pr.inboxAccessConstructionBinding
    493     >[0];
    494     const absent = window.pr.inboxAccessConstructionBinding(
    495         fake,
    496         f.session,
    497         f.policy
    498       ),
    499       wrongPolicy = window.pr.inboxAccessConstructionBinding(
    500         f.controller()!,
    501         f.session,
    502         f.copiedPolicy()
    503       ),
    504       wrongSession = window.pr.inboxAccessConstructionBinding(
    505         f.controller()!,
    506         fake as unknown as Parameters<
    507           typeof window.pr.inboxAccessConstructionBinding
    508         >[1],
    509         f.policy
    510       );
    511     const matching = window.pr.inboxAccessConstructionBinding(
    512       f.controller()!,
    513       f.session,
    514       f.policy
    515     );
    516     const wrongIdentity = {} as typeof f.identity;
    517     const refused = window.pr.captureInboxProbeRecoveryReader(
    518       f.repository,
    519       wrongIdentity,
    520       f.session,
    521       f.policy,
    522       f.controller()!,
    523       f.qualification,
    524       '11111111-1111-4111-8111-111111111111',
    525       'reviewed_inbox_probe_recovery'
    526     );
    527     const correctIdentity = window.pr.captureInboxProbeRecoveryReader(
    528       f.repository,
    529       f.identity,
    530       f.session,
    531       f.policy,
    532       f.controller()!,
    533       f.qualification,
    534       '11111111-1111-4111-8111-111111111111',
    535       'reviewed_inbox_probe_recovery'
    536     );
    537     const after = retries,
    538       retained = window.pr.privateSessionCleanupRequired(f.session);
    539     off();
    540     window.pr.closePrivateSession(f.session);
    541     return {
    542       before,
    543       after,
    544       retained,
    545       admitted: !!(
    546         absent ||
    547         wrongPolicy ||
    548         wrongSession ||
    549         matching ||
    550         refused ||
    551         correctIdentity
    552       )
    553     };
    554   });
    555   expect(result.before).toBeGreaterThan(0);
    556   expect(result.after).toBe(result.before);
    557   expect(result.retained).toBe(true);
    558   expect(result.admitted).toBe(false);
    559 });
    560 test('one selected original reader prevents second-command/reset and copied/cross-family capability admission', async ({
    561   page
    562 }) => {
    563   await fresh(page);
    564   const result = await page.evaluate(async () => {
    565     const r = window.prFresh,
    566       reader = r.capture()!,
    567       other = r.capture('reviewed_inbox_probe_recovery', crypto.randomUUID());
    568     const recovered = await r.recover(reader);
    569     if (!('proof' in recovered)) throw Error('genuine recovered family');
    570     const copies = await window.pr.recoverInboxProbe({ ...reader }),
    571       ordinary = window.pr.recoveredSelfEnvelopeSnapshot(
    572         recovered.proof as unknown as Parameters<
    573           typeof window.pr.recoveredSelfEnvelopeSnapshot
    574         >[0]
    575       ),
    576       nonce = window.pr.inboxProbeNonceProofBinding(
    577         recovered.proof as unknown as Parameters<
    578           typeof window.pr.inboxProbeNonceProofBinding
    579         >[0],
    580         r.repository,
    581         r.session,
    582         r.policy
    583       ),
    584       copied = window.pr.recoveredInboxProbeBinding(
    585         { ...recovered.proof },
    586         r.repository,
    587         r.session,
    588         r.access,
    589         r.policy,
    590         r.operator
    591       );
    592     return {
    593       other: !!other,
    594       copies,
    595       ordinary: !!ordinary,
    596       nonce: !!nonce,
    597       copied: !!copied
    598     };
    599   });
    600   expect(result).toEqual({
    601     other: false,
    602     copies: { status: 'invalid' },
    603     ordinary: false,
    604     nonce: false,
    605     copied: false
    606   });
    607 });
    608 for (const mutation of [
    609   'r0',
    610   'missing-self',
    611   'ordinary',
    612   'corrupt',
    613   'alias',
    614   'tail',
    615   'binding',
    616   'hash',
    617   'time',
    618   'disappeared'
    619 ])
    620   test(`actual native ${mutation} cannot substitute original recovery custody`, async ({
    621     page
    622   }) => {
    623     await fresh(page);
    624     const result = await page.evaluate(async (mutation) => {
    625       const f = window.prFixture,
    626         r = window.prFresh,
    627         row = (await f.stored()).find((x) => x.id === r.localId)!,
    628         record = JSON.parse(row.wire) as Record<string, unknown>,
    629         before = f.counts();
    630       if (mutation === 'r0') {
    631         record.revision = 0;
    632         record.self = null;
    633         record.receipts = [];
    634       }
    635       if (mutation === 'missing-self') record.self = null;
    636       if (mutation === 'ordinary') {
    637         record.family = 'private_send_reservation';
    638         delete record.binding;
    639         delete record.self;
    640         delete record.receipts;
    641         record.revision = 0;
    642         record.peer = f.owner;
    643       }
    644       if (mutation === 'binding')
    645         (record.binding as { preferenceId: string }).preferenceId = 'f'.repeat(
    646           64
    647         );
    648       if (mutation === 'hash') record.rumorHash = 'f'.repeat(64);
    649       if (mutation === 'time') record.createdAt = Number(record.createdAt) + 1;
    650       if (mutation === 'alias')
    651         await f.inject([{ ...row, id: crypto.randomUUID() }]);
    652       else if (mutation === 'tail')
    653         await f.inject([
    654           { owner: row.owner, id: crypto.randomUUID(), wire: '{' }
    655         ]);
    656       else if (mutation === 'disappeared') await f.removeOriginal();
    657       else
    658         await f.inject([
    659           {
    660             ...row,
    661             wire: mutation === 'corrupt' ? '{' : JSON.stringify(record)
    662           }
    663         ]);
    664       const rows = await f.stored(),
    665         recovered = await r.recover();
    666       return {
    667         status: recovered.status,
    668         before,
    669         after: f.counts(),
    670         rowsSame: JSON.stringify(rows) === JSON.stringify(await f.stored()),
    671         proof: !!r.binding()
    672       };
    673     }, mutation);
    674     expect(result.status).not.toBe('recovered');
    675     expect(result.rowsSame).toBe(true);
    676     expect(result.proof).toBe(false);
    677     expect(result.after.signs).toBe(result.before.signs);
    678     expect(result.after.encrypts).toBe(result.before.encrypts);
    679     if (!['hash', 'time'].includes(mutation))
    680       expect(result.after.decrypts).toBe(result.before.decrypts);
    681   });
    682 test('valid handwritten prior unknown/network labels permit only local decryption and confer no remote readiness', async ({
    683   page
    684 }) => {
    685   await page.evaluate(async () => {
    686     const f = window.prFixture;
    687     const result = await f.publish();
    688     await f.append(result);
    689   });
    690   await fresh(page);
    691   const result = await page.evaluate(async () => {
    692     const f = window.prFixture,
    693       r = window.prFresh,
    694       row = (await f.stored()).find((x) => x.id === r.localId)!,
    695       record = JSON.parse(row.wire) as { receipts: { status: string }[] };
    696     record.receipts[0].status = 'unknown';
    697     await f.inject([{ ...row, wire: JSON.stringify(record) }]);
    698     const rows = await f.stored(),
    699       result = await r.recover();
    700     return {
    701       status: result.status,
    702       same: JSON.stringify(rows) === JSON.stringify(await f.stored()),
    703       readiness: window.pr.inboxAccessControllerSnapshot(r.access)?.readiness
    704     };
    705   });
    706   expect(result).toEqual({
    707     status: 'recovered',
    708     same: true,
    709     readiness: 'unavailable'
    710   });
    711 });
    712 for (const mode of ['wrong_key', 'refuse_decrypt', 'wrong_decrypt'] as const)
    713   test(`actual provider ${mode} consumes the original action without a repeated prompt`, async ({
    714     page
    715   }) => {
    716     await fresh(page);
    717     const result = await page.evaluate(async (mode) => {
    718       const f = window.prFixture,
    719         r = window.prFresh;
    720       f.mode(mode);
    721       const before = f.counts(),
    722         first = await r.recover(),
    723         after = f.counts();
    724       f.mode('normal');
    725       const again = await r.recover();
    726       return {
    727         first: first.status,
    728         again: again.status,
    729         before,
    730         after,
    731         final: f.counts()
    732       };
    733     }, mode);
    734     expect(result.first).not.toBe('recovered');
    735     expect(result.again).not.toBe('recovered');
    736     expect(result.final).toEqual(result.after);
    737     if (mode === 'wrong_key')
    738       expect(result.after.decrypts).toBe(result.before.decrypts);
    739   });
    740 for (const stage of ['key', 'decrypt'] as const)
    741   for (const loss of [
    742     'stop',
    743     'expire',
    744     'head',
    745     'controller',
    746     'private',
    747     'identity'
    748   ] as const)
    749     test(`pending real ${stage} ${loss} hides recovery and retains the actual shared occupied slot until settlement`, async ({
    750       page
    751     }) => {
    752       await fresh(page);
    753       await page.evaluate((stage) => {
    754         window.prFixture.mode(stage === 'key' ? 'hold_key' : 'hold_decrypt');
    755         window.prPending = window.prFresh.recover();
    756       }, stage);
    757       await expect
    758         .poll(() => page.evaluate(() => window.prFixture.waiting()))
    759         .toBe(stage);
    760       const result = await page.evaluate(async (loss) => {
    761         const f = window.prFixture,
    762           r = window.prFresh,
    763           reader = r.reader()!;
    764         if (loss === 'stop') window.pr.stopInboxProbeRecoveryReader(reader);
    765         if (loss === 'expire')
    766           window.pr.expireInboxProbeRecoveryReaderWait(reader);
    767         if (loss === 'head') r.churnHead();
    768         if (loss === 'controller')
    769           window.pr.closeInboxAccessController(r.access);
    770         if (loss === 'private') window.pr.closePrivateSession(r.session);
    771         if (loss === 'identity') window.pr.disconnectIdentity(r.identity);
    772         const occupied = window.pr.extensionSchedulerSnapshot(
    773           window.pr.browserExtensionScheduler()!
    774         )?.state;
    775         const busy = await window.pr.runExtensionAction(
    776           window.pr.browserExtensionScheduler()!,
    777           { owner: r.owner, session: Symbol(), operation: Symbol() },
    778           () => true,
    779           () => Promise.resolve('foreign')
    780         );
    781         f.mode('normal');
    782         f.settle();
    783         const result = await window.prPending;
    784         const after = f.counts();
    785         const repeated = await r.recover(reader);
    786         return {
    787           occupied,
    788           busy: busy.status,
    789           result,
    790           repeated: repeated.status,
    791           unchanged: JSON.stringify(after) === JSON.stringify(f.counts()),
    792           proof: !!r.binding(),
    793           final: window.pr.extensionSchedulerSnapshot(
    794             window.pr.browserExtensionScheduler()!
    795           )?.state
    796         };
    797       }, loss);
    798       expect(result.occupied).toBe('active');
    799       expect(result.busy).toBe('busy');
    800       expect(result.result).not.toMatchObject({ status: 'recovered' });
    801       expect(result.repeated).not.toBe('recovered');
    802       expect(result.proof).toBe(false);
    803       expect(result.unchanged).toBe(true);
    804       expect(result.final).toBe('idle');
    805     });
    806 test('actual owner lock busy admits zero SDK calls and explicit same-reader execution recovers after release', async ({
    807   page
    808 }) => {
    809   await fresh(page);
    810   await page.evaluate(() => {
    811     const r = window.prFresh;
    812     window.prPending = navigator.locks.request(
    813       'harvestcircle:owner:' + r.owner,
    814       () =>
    815         new Promise<void>((resolve) => {
    816           window.prRelease = resolve;
    817         })
    818     );
    819   });
    820   await expect.poll(() => page.evaluate(() => !!window.prRelease)).toBe(true);
    821   const first = await page.evaluate(async () => {
    822     const f = window.prFixture,
    823       r = window.prFresh,
    824       reader = r.capture()!,
    825       before = f.counts(),
    826       result = await r.recover(reader);
    827     return {
    828       result,
    829       equal: JSON.stringify(before) === JSON.stringify(f.counts()),
    830       same: reader === r.capture()
    831     };
    832   });
    833   expect(first).toEqual({
    834     result: { status: 'busy' },
    835     equal: true,
    836     same: true
    837   });
    838   await page.evaluate(async () => {
    839     window.prRelease!();
    840     await window.prPending;
    841   });
    842   expect(
    843     await page.evaluate(async () => (await window.prFresh.recover()).status)
    844   ).toBe('recovered');
    845 });
    846 test('actual shared scheduler busy permits one explicit original-operation run after release', async ({
    847   page
    848 }) => {
    849   await fresh(page);
    850   await page.evaluate(() => {
    851     window.prPending = window.pr.runExtensionAction(
    852       window.pr.browserExtensionScheduler()!,
    853       { owner: window.prFresh.owner, session: Symbol(), operation: Symbol() },
    854       () => true,
    855       () =>
    856         new Promise<void>((resolve) => {
    857           window.prRelease = resolve;
    858         })
    859     );
    860   });
    861   await expect.poll(() => page.evaluate(() => !!window.prRelease)).toBe(true);
    862   const result = await page.evaluate(async () => {
    863     const f = window.prFixture,
    864       r = window.prFresh,
    865       before = f.counts(),
    866       first = await r.recover();
    867     return {
    868       first: first.status,
    869       same: r.reader() === r.capture(),
    870       equal: JSON.stringify(before) === JSON.stringify(f.counts())
    871     };
    872   });
    873   expect(result).toEqual({ first: 'busy', same: true, equal: true });
    874   await page.evaluate(async () => {
    875     window.prRelease!();
    876     await window.prPending;
    877   });
    878   expect(
    879     await page.evaluate(async () => (await window.prFresh.recover()).status)
    880   ).toBe('recovered');
    881 });
    882 for (const hit of [1, 2, 3])
    883   for (const loss of ['native', 'head', 'controller', 'private', 'identity'])
    884     test(`actual fresh-key${hit} ${loss} mutation cannot precede a stale recovered proof`, async ({
    885       page
    886     }) => {
    887       await fresh(page);
    888       const result = await page.evaluate(
    889         async ({ hit, loss }) => {
    890           const f = window.prFixture,
    891             r = window.prFresh;
    892           window.prRestore = f.keyCallback(hit, async () => {
    893             if (loss === 'native') {
    894               const row = (await f.stored()).find((x) => x.id === r.localId)!,
    895                 record = JSON.parse(row.wire) as {
    896                   binding: { preferenceId: string };
    897                 };
    898               record.binding.preferenceId = 'f'.repeat(64);
    899               await f.inject([{ ...row, wire: JSON.stringify(record) }]);
    900             }
    901             if (loss === 'head') r.churnHead();
    902             if (loss === 'controller')
    903               window.pr.closeInboxAccessController(r.access);
    904             if (loss === 'private') window.pr.closePrivateSession(r.session);
    905             if (loss === 'identity') window.pr.disconnectIdentity(r.identity);
    906           });
    907           const result = await r.recover();
    908           return { status: result.status, proof: !!r.binding() };
    909         },
    910         { hit, loss }
    911       );
    912       expect(result.status).not.toBe('recovered');
    913       expect(result.proof).toBe(false);
    914     });
    915 test('cipher getter scope loss preserves current identity and independent private session', async ({
    916   page
    917 }) => {
    918   await fresh(page);
    919   const result = await page.evaluate(async () => {
    920     const f = window.prFixture,
    921       r = window.prFresh;
    922     window.prRestore = f.cipherGetter(() =>
    923       window.pr.closeInboxAccessController(r.access)
    924     );
    925     const before = f.counts(),
    926       result = await r.recover();
    927     return {
    928       status: result.status,
    929       noDecrypt: before.decrypts === f.counts().decrypts,
    930       identity:
    931         window.pr.identityMessagingOwnership(r.identity)?.current() ?? false,
    932       session: window.pr.privateSessionSnapshot(r.session)?.current ?? false
    933     };
    934   });
    935   expect(result.status).not.toBe('recovered');
    936   expect(result.noDecrypt).toBe(true);
    937   expect(result.identity).toBe(true);
    938   expect(result.session).toBe(true);
    939 });
    940 test('invalid fresh key never acquires the cipher getter', async ({ page }) => {
    941   await fresh(page);
    942   const result = await page.evaluate(async () => {
    943     const f = window.prFixture,
    944       r = window.prFresh;
    945     let getters = 0;
    946     window.prRestore = f.cipherGetter(() => {
    947       getters++;
    948     });
    949     f.mode('wrong_key');
    950     const before = f.counts(),
    951       result = await r.recover();
    952     return {
    953       status: result.status,
    954       getters,
    955       decrypts: f.counts().decrypts - before.decrypts
    956     };
    957   });
    958   expect(result.status).not.toBe('recovered');
    959   expect(result.getters).toBe(0);
    960   expect(result.decrypts).toBe(0);
    961 });
    962 test('pending duplicate/reentrant capture keeps the same reader and admits no second SDK action', async ({
    963   page
    964 }) => {
    965   await fresh(page);
    966   await page.evaluate(() => {
    967     window.prFixture.mode('hold_decrypt');
    968     window.prPending = window.prFresh.recover();
    969   });
    970   await expect
    971     .poll(() => page.evaluate(() => window.prFixture.waiting()))
    972     .toBe('decrypt');
    973   const result = await page.evaluate(async () => {
    974     const f = window.prFixture,
    975       r = window.prFresh,
    976       before = f.counts(),
    977       reader = r.reader(),
    978       duplicate = await r.recover();
    979     const same = reader === r.capture(),
    980       inert = JSON.stringify(before) === JSON.stringify(f.counts());
    981     f.mode('normal');
    982     f.settle();
    983     const original = await window.prPending;
    984     return {
    985       duplicate: duplicate.status,
    986       same,
    987       inert,
    988       original,
    989       decrypts: f.counts().decrypts - before.decrypts
    990     };
    991   });
    992   expect(result.duplicate).toBe('busy');
    993   expect(result.same).toBe(true);
    994   expect(result.inert).toBe(true);
    995   expect(result.original).toMatchObject({ status: 'recovered' });
    996   expect(result.decrypts).toBe(1);
    997 });
    998 for (const loss of [
    999   'stop',
   1000   'expire',
   1001   'head',
   1002   'controller',
   1003   'private',
   1004   'identity'
   1005 ])
   1006   test(`genuine recovered proof revokes all original rumor visibility on ${loss}`, async ({
   1007     page
   1008   }) => {
   1009     await fresh(page);
   1010     const result = await page.evaluate(async (loss) => {
   1011       const r = window.prFresh,
   1012         result = await r.recover();
   1013       if (!('proof' in result)) throw Error('actual recovered proof');
   1014       const visible = !!window.pr.recoveredInboxProbeRumorWire(
   1015         result.proof,
   1016         r.repository,
   1017         r.session,
   1018         r.access,
   1019         r.policy,
   1020         r.operator
   1021       );
   1022       if (loss === 'stop') window.pr.stopInboxProbeRecoveryReader(r.reader()!);
   1023       if (loss === 'expire')
   1024         window.pr.expireInboxProbeRecoveryReaderWait(r.reader()!);
   1025       if (loss === 'head') r.churnHead();
   1026       if (loss === 'controller') window.pr.closeInboxAccessController(r.access);
   1027       if (loss === 'private') window.pr.closePrivateSession(r.session);
   1028       if (loss === 'identity') window.pr.disconnectIdentity(r.identity);
   1029       return {
   1030         visible,
   1031         binding: !!r.binding(),
   1032         rumor: !!window.pr.recoveredInboxProbeRumorWire(
   1033           result.proof,
   1034           r.repository,
   1035           r.session,
   1036           r.access,
   1037           r.policy,
   1038           r.operator
   1039         )
   1040       };
   1041     }, loss);
   1042     expect(result).toEqual({ visible: true, binding: false, rumor: false });
   1043   });
   1044 for (const malformed of [
   1045   'id',
   1046   'author',
   1047   'time',
   1048   'kind',
   1049   'recipient',
   1050   'prefix',
   1051   'nonce',
   1052   'extra',
   1053   'duplicate',
   1054   'numeric',
   1055   'oversized'
   1056 ])
   1057   test(`actual SDK recovered diagnostic ${malformed} cannot mint original proof`, async ({
   1058     page
   1059   }) => {
   1060     await fresh(page);
   1061     const result = await page.evaluate(async (malformed) => {
   1062       const f = window.prFixture,
   1063         r = window.prFresh;
   1064       const control = f.decryptCallback(2, (wire) => {
   1065         const rumor = JSON.parse(wire) as Record<string, unknown>;
   1066         if (malformed === 'id') rumor.id = 'f'.repeat(64);
   1067         if (malformed === 'author') rumor.pubkey = 'f'.repeat(64);
   1068         if (malformed === 'time')
   1069           rumor.created_at = Number(rumor.created_at) + 1;
   1070         if (malformed === 'kind') rumor.kind = 1;
   1071         if (malformed === 'recipient') rumor.tags = [['p', 'f'.repeat(64)]];
   1072         if (malformed === 'prefix')
   1073           rumor.content = String(rumor.content).replace(
   1074             'Harvestcircle',
   1075             'Other'
   1076           );
   1077         if (malformed === 'nonce')
   1078           rumor.content = String(rumor.content).slice(0, -1) + 'Z';
   1079         if (malformed === 'extra') rumor.extra = true;
   1080         if (malformed === 'oversized') rumor.content = 'x'.repeat(8193);
   1081         const changed = JSON.stringify(rumor);
   1082         return malformed === 'duplicate'
   1083           ? changed.replace('"kind":14', '"kind":14,"kind":14')
   1084           : malformed === 'numeric'
   1085             ? changed.replace('"kind":14', '"kind":1.4e1')
   1086             : changed;
   1087       });
   1088       window.prRestore = control.restore;
   1089       const before = await f.stored(),
   1090         result = await r.recover();
   1091       return {
   1092         status: result.status,
   1093         proof: !!r.binding(),
   1094         same: JSON.stringify(before) === JSON.stringify(await f.stored()),
   1095         receivers: control.receivers()
   1096       };
   1097     }, malformed);
   1098     expect(result.status).toBe('mismatch');
   1099     expect(result.proof).toBe(false);
   1100     expect(result.same).toBe(true);
   1101     expect(result.receivers).toBe(2);
   1102   });
   1103 for (const malformed of ['tags', 'kind', 'ciphertext'])
   1104   test(`actual independently signed inner seal ${malformed} is rejected`, async ({
   1105     page
   1106   }) => {
   1107     await fresh(page);
   1108     const result = await page.evaluate(async (malformed) => {
   1109       const f = window.prFixture,
   1110         r = window.prFresh;
   1111       const control = f.decryptCallback(1, (wire) =>
   1112         f.signSeal(
   1113           wire,
   1114           malformed === 'tags'
   1115             ? { tags: [['p', f.owner]] }
   1116             : malformed === 'kind'
   1117               ? { kind: 1 }
   1118               : { content: 'unsupported ciphertext' }
   1119         )
   1120       );
   1121       window.prRestore = control.restore;
   1122       const result = await r.recover();
   1123       return {
   1124         status: result.status,
   1125         proof: !!r.binding(),
   1126         receivers: control.receivers()
   1127       };
   1128     }, malformed);
   1129     expect(result.status).toBe('mismatch');
   1130     expect(result.proof).toBe(false);
   1131     expect(result.receivers).toBe(1);
   1132   });
   1133 for (const hit of [1, 2])
   1134   for (const fault of ['before', 'after'])
   1135     test(`actual native readonly${hit} ${fault} abort refuses recovered authority`, async ({
   1136       page
   1137     }) => {
   1138       await fresh(page);
   1139       const result = await page.evaluate(
   1140         async ({ hit, fault }) => {
   1141           const original = Object.getOwnPropertyDescriptor(
   1142             IDBIndex.prototype,
   1143             'openCursor'
   1144           )!.value as IDBIndex['openCursor'];
   1145           let selected = 0,
   1146             aborts = 0;
   1147           IDBIndex.prototype.openCursor = function (
   1148             ...args: Parameters<IDBIndex['openCursor']>
   1149           ) {
   1150             const request = original.apply(this, args);
   1151             if (
   1152               this.objectStore.name === 'private_sends' &&
   1153               this.objectStore.transaction.mode === 'readonly' &&
   1154               ++selected === hit
   1155             ) {
   1156               const tx = this.objectStore.transaction;
   1157               if (fault === 'before') {
   1158                 aborts++;
   1159                 tx.abort();
   1160               } else
   1161                 request.addEventListener(
   1162                   'success',
   1163                   () => {
   1164                     aborts++;
   1165                     tx.abort();
   1166                   },
   1167                   { once: true }
   1168                 );
   1169             }
   1170             return request;
   1171           };
   1172           window.prRestore = () => {
   1173             IDBIndex.prototype.openCursor = original;
   1174           };
   1175           const result = await window.prFresh.recover();
   1176           return {
   1177             status: result.status,
   1178             aborts,
   1179             proof: !!window.prFresh.binding()
   1180           };
   1181         },
   1182         { hit, fault }
   1183       );
   1184       expect(result.status).not.toBe('recovered');
   1185       expect(result.aborts).toBe(1);
   1186       expect(result.proof).toBe(false);
   1187     });
   1188 test('actual same-origin child reload recovers stored ciphertext through a fresh source realm and extension-host closure', async ({
   1189   page
   1190 }) => {
   1191   await page.evaluate(() => window.prFixture.close());
   1192   head = await page.evaluate(() => {
   1193     window.prHosted = window.pr.createHostedProvider();
   1194     return window.prHosted.head();
   1195   });
   1196   const setup = await page.evaluate(() => {
   1197     const policyWire = JSON.stringify({
   1198       schemaVersion: 1,
   1199       public: [
   1200         {
   1201           origin: 'wss://discovery.example.org',
   1202           read: true,
   1203           write: true,
   1204           nip50: false
   1205         }
   1206       ],
   1207       inbox: [{ origin: 'wss://inbox.example.org', read: true, write: true }],
   1208       postingEnabled: true,
   1209       messagingEnabled: true,
   1210       operatorDenylist: []
   1211     });
   1212     const operatorWire = JSON.stringify({
   1213       schemaVersion: 1,
   1214       revision: 1,
   1215       authority: 'source_fixture',
   1216       policyWire,
   1217       evidenceSha256: 'a'.repeat(64),
   1218       relays: [
   1219         {
   1220           origin: 'wss://inbox.example.org',
   1221           auth: 'not_required',
   1222           recipientRead: 'supported',
   1223           namedArchiveAck: 'supported',
   1224           exactReadback: 'supported',
   1225           retention: 'operator_defined'
   1226         }
   1227       ]
   1228     });
   1229     return { owner: window.prHosted!.owner, policyWire, operatorWire };
   1230   });
   1231   await page.evaluate((url) => {
   1232     const iframe = document.createElement('iframe');
   1233     iframe.id = 'recovery-realm';
   1234     iframe.src = url;
   1235     document.body.append(iframe);
   1236   }, server.url + '/search');
   1237   const frame = await (
   1238     await page.locator('#recovery-realm').elementHandle()
   1239   ).contentFrame();
   1240   if (!frame) throw Error('actual same-origin child');
   1241   await frame.waitForLoadState();
   1242   await frame.addScriptTag({ content: bundle });
   1243   const original = await frame.evaluate(async (setup) => {
   1244     window.pr.installHostedProvider();
   1245     const policy = window.pr.validateRelayPolicy(setup.policyWire)!,
   1246       operator = window.pr.validateInboxOperatorQualification(
   1247         setup.operatorWire
   1248       )!;
   1249     window.prHostedContext = await window.pr.openRecoveryContext(
   1250       setup.owner,
   1251       policy,
   1252       operator,
   1253       crypto.randomUUID()
   1254     );
   1255     const record = await window.pr.prepareHostedOriginal(
   1256       window.prHostedContext
   1257     );
   1258     window.prHostedContext.close();
   1259     return {
   1260       owner: record.owner,
   1261       id: record.id,
   1262       hash: record.rumorHash,
   1263       eventId: record.self!.eventId,
   1264       policyWire: setup.policyWire,
   1265       operatorWire: setup.operatorWire
   1266     };
   1267   }, setup);
   1268   for (let cycle = 0; cycle < 2; cycle++) {
   1269     await frame.goto(server.url + '/search');
   1270     await frame.addScriptTag({ content: bundle });
   1271     const before = await page.evaluate(() => window.prHosted!.counts());
   1272     const result = await frame.evaluate(async (setup) => {
   1273       window.pr.installHostedProvider();
   1274       const policy = window.pr.validateRelayPolicy(setup.policyWire)!,
   1275         operator = window.pr.validateInboxOperatorQualification(
   1276           setup.operatorWire
   1277         )!;
   1278       window.prFresh = await window.pr.openRecoveryContext(
   1279         setup.owner,
   1280         policy,
   1281         operator,
   1282         setup.id
   1283       );
   1284       const result = await window.prFresh.recover(),
   1285         binding = window.prFresh.binding();
   1286       const output = {
   1287         status: result.status,
   1288         command: binding?.command,
   1289         hash: binding?.rumorHash,
   1290         eventId: binding?.eventId
   1291       };
   1292       window.prFresh.close();
   1293       return output;
   1294     }, original);
   1295     expect(result).toEqual({
   1296       status: 'recovered',
   1297       command: original.id,
   1298       hash: original.hash,
   1299       eventId: original.eventId
   1300     });
   1301     const after = await page.evaluate(() => window.prHosted!.counts());
   1302     expect(after.signs).toBe(before.signs);
   1303     expect(after.encrypts - before.encrypts).toBe(1); // Actual fresh capability probe; recovery creates no artifact.
   1304     expect(after.decrypts - before.decrypts).toBe(3); // Fresh capability probe plus original two-layer recovery.
   1305   }
   1306 });