app

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

inbox-probe.spec.ts (39480B)


      1 import { test, expect } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { once } from 'node:events';
      4 import { fileURLToPath } from 'node:url';
      5 import { WebSocketServer } from 'ws';
      6 import { createStaticHarness } from '../integration/harness/static.ts';
      7 import type * as Fixture from './harness/inbox-probe.ts';
      8 declare global {
      9   interface Window {
     10     p8: typeof Fixture;
     11     p8Fixture: Awaited<ReturnType<typeof Fixture.makeProbeFixture>>;
     12     p8Pending?: Promise<string>;
     13     p8Restore?: () => void;
     14   }
     15 }
     16 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     17   sockets: WebSocketServer,
     18   endpoint: string,
     19   bundle: string;
     20 let head = '';
     21 const frames: unknown[][] = [];
     22 test.beforeAll(async () => {
     23   server = await createStaticHarness();
     24   sockets = new WebSocketServer({
     25     host: '127.0.0.1',
     26     port: 0,
     27     maxPayload: 65536
     28   });
     29   await once(sockets, 'listening');
     30   const address = sockets.address();
     31   if (!address || typeof address === 'string')
     32     throw Error('owned fixture relay');
     33   endpoint = 'ws://127.0.0.1:' + address.port;
     34   sockets.on('connection', (socket) => {
     35     socket.on('message', (bytes) => {
     36       const raw = Buffer.isBuffer(bytes)
     37         ? bytes
     38         : Array.isArray(bytes)
     39           ? Buffer.concat(bytes)
     40           : Buffer.from(bytes);
     41       const frame = JSON.parse(raw.toString()) as unknown[];
     42       frames.push(frame);
     43       if (frame[0] === 'REQ') {
     44         const filter = frame[2] as { kinds?: number[] };
     45         if (filter.kinds?.includes(10050) && head)
     46           socket.send(JSON.stringify(['EVENT', frame[1], JSON.parse(head)]));
     47         socket.send(JSON.stringify(['EOSE', frame[1]]));
     48       }
     49     });
     50   });
     51   const result = await build({
     52     configFile: false,
     53     logLevel: 'silent',
     54     build: {
     55       write: false,
     56       minify: false,
     57       lib: {
     58         entry: fileURLToPath(
     59           new URL('./harness/inbox-probe.ts', import.meta.url)
     60         ),
     61         name: 'p8',
     62         formats: ['iife']
     63       }
     64     }
     65   });
     66   const output = Array.isArray(result) ? result[0] : result;
     67   if (!('output' in output)) throw Error('actual bundle');
     68   const chunks = output.output.filter((chunk) => chunk.type === 'chunk');
     69   expect(chunks).toHaveLength(1);
     70   bundle = chunks[0].code;
     71 });
     72 test.afterAll(async () => {
     73   for (const socket of sockets.clients) socket.terminate();
     74   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     75   await server.close();
     76 });
     77 test.beforeEach(async ({ page }) => {
     78   await expect.poll(() => sockets.clients.size).toBe(0);
     79   head = '';
     80   frames.length = 0;
     81   await page.addInitScript(
     82     ({ endpoint }) => {
     83       const Native = window.WebSocket;
     84       window.WebSocket = class extends Native {
     85         constructor(url: string | URL, protocols?: string | string[]) {
     86           if (new URL(String(url)).origin !== 'wss://discovery.example.org')
     87             throw Error('construction attempted private transport');
     88           super(endpoint, protocols);
     89         }
     90       };
     91     },
     92     { endpoint }
     93   );
     94   await page.goto(server.url + '/search');
     95   await page.addScriptTag({ content: bundle });
     96   head = await page.evaluate(async () => {
     97     window.p8Fixture = await window.p8.makeProbeFixture();
     98     return window.p8Fixture.preferenceWire(['wss://inbox.example.org']);
     99   });
    100   await page.evaluate(() => window.p8Fixture.capture());
    101 });
    102 test.afterEach(async ({ page }) => {
    103   if (!page.isClosed())
    104     await page.evaluate(() => {
    105       window.p8Restore?.();
    106       window.p8Fixture.close();
    107     });
    108 });
    109 
    110 test('cold genuine self diagnostic reserves native metadata before prompts and decrypts the exact original SDK layers', async ({
    111   page
    112 }) => {
    113   const before = await page.evaluate(() => window.p8Fixture.counts());
    114   // Evaluate the native promise explicitly; there was no earlier ordinary send.
    115   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(0);
    116   const reservation = await page.evaluate(() => window.p8Fixture.reserve());
    117   expect(reservation.status).toBe('reserved');
    118   const saved = await page.evaluate(() => window.p8Fixture.stored());
    119   expect(saved).toHaveLength(1);
    120   expect(JSON.stringify(saved)).not.toContain(
    121     'Harvestcircle private inbox access check'
    122   );
    123   expect(JSON.parse(saved[0].wire)).toMatchObject({
    124     family: 'private_access_probe',
    125     revision: 0,
    126     self: null,
    127     receipts: []
    128   });
    129   expect(await page.evaluate(() => window.p8Fixture.counts())).toEqual(before);
    130   expect(await page.evaluate(() => window.p8Fixture.prepare())).toBe('wrapped');
    131   expect(await page.evaluate(() => window.p8Fixture.decryptOriginal())).toEqual(
    132     {
    133       outerVerified: true,
    134       sealVerified: true,
    135       exactRumor: true,
    136       hash: true,
    137       owner: true,
    138       recipient: true,
    139       createdAt: true,
    140       kind: 14,
    141       diagnostic: true
    142     }
    143   );
    144   expect(await page.evaluate(() => window.p8Fixture.stored())).toEqual(saved);
    145   const duplicate = await page.evaluate(() => window.p8Fixture.reserve());
    146   expect(duplicate.status).toBe('existing');
    147   expect(duplicate.snapshot).toEqual(reservation.snapshot);
    148   expect(
    149     await page.evaluate(
    150       () =>
    151         window.p8.inboxAccessControllerSnapshot(window.p8Fixture.controller()!)
    152           ?.readiness
    153     )
    154   ).toBe('unavailable');
    155   expect(
    156     frames.some((frame) => ['EVENT', 'AUTH'].includes(String(frame[0])))
    157   ).toBe(false);
    158   expect(
    159     frames
    160       .filter((frame) => frame[0] === 'REQ')
    161       .every((frame) => (frame[2] as { kinds: number[] }).kinds.includes(10050))
    162   ).toBe(true);
    163 });
    164 
    165 test('separate genuine maps reject ordinary adoption, copied snapshots and replacement crypto artifacts', async ({
    166   page
    167 }) => {
    168   await page.evaluate(() => window.p8Fixture.reserve());
    169   expect(await page.evaluate(() => window.p8Fixture.prepare())).toBe('wrapped');
    170   const result = await page.evaluate(async () => {
    171     const f = window.p8Fixture,
    172       api = window.p8,
    173       identity = f.probeIdentity()!,
    174       seal = f.seal()!,
    175       wrap = f.wrap()!,
    176       operation = f.operation()!;
    177     const same = api.buildInboxProbeGiftwrap(seal, 'reviewed_inbox_probe_wrap');
    178     const reserved = identity as unknown as Parameters<
    179       typeof api.capturePrivateSealOperation
    180     >[1];
    181     const ordinarySeal = seal as unknown as Parameters<
    182       typeof api.privateSealSnapshot
    183     >[0];
    184     const ordinaryWrap = wrap as unknown as Parameters<
    185       typeof api.privateGiftwrapSnapshot
    186     >[0];
    187     const copy = api.inboxProbeSnapshot(identity)! as unknown as Parameters<
    188       typeof api.captureInboxProbeSealOperation
    189     >[1];
    190     return {
    191       sameWrap: same === wrap,
    192       sameOperation:
    193         api.captureInboxProbeSealOperation(
    194           f.session,
    195           identity,
    196           'reviewed_inbox_probe_seal'
    197         ) === operation,
    198       duplicateRun: (await api.buildInboxProbeSeal(operation)).status,
    199       ordinaryIdentity: api.reservedSendSnapshot(reserved) === undefined,
    200       ordinaryCapture:
    201         api.capturePrivateSealOperation(
    202           f.identity,
    203           reserved,
    204           'self',
    205           'reviewed_private_seal'
    206         ) === undefined,
    207       ordinaryRun: (
    208         await api.buildPrivateSeal(
    209           operation as unknown as Parameters<typeof api.buildPrivateSeal>[0]
    210         )
    211       ).status,
    212       ordinarySeal:
    213         api.privateSealSnapshot(ordinarySeal) === undefined &&
    214         api.privateSealReservation(ordinarySeal) === undefined,
    215       ordinaryWrap:
    216         api.buildPrivateGiftwrap(ordinarySeal, 'reviewed_private_wrap') ===
    217           undefined && api.privateGiftwrapSnapshot(ordinaryWrap) === undefined,
    218       outbound:
    219         api.verifyOutboundEnvelope(
    220           reserved,
    221           ordinaryWrap,
    222           'reviewed_outbound_layers'
    223         ) === undefined,
    224       copy:
    225         api.captureInboxProbeSealOperation(
    226           f.session,
    227           copy,
    228           'reviewed_inbox_probe_seal'
    229         ) === undefined
    230     };
    231   });
    232   expect(result).toEqual({
    233     sameWrap: true,
    234     sameOperation: true,
    235     duplicateRun: 'stopped',
    236     ordinaryIdentity: true,
    237     ordinaryCapture: true,
    238     ordinaryRun: 'invalid',
    239     ordinarySeal: true,
    240     ordinaryWrap: true,
    241     outbound: true,
    242     copy: true
    243   });
    244 });
    245 
    246 test('simultaneous genuine reservation returns busy while pending and creates exactly one native original', async ({
    247   page
    248 }) => {
    249   const result = await page.evaluate(async () => {
    250     const f = window.p8Fixture,
    251       first = f.reserve(),
    252       second = f.reserve(),
    253       [a, b] = await Promise.all([first, second]);
    254     return {
    255       a,
    256       b,
    257       rows: await f.stored(),
    258       counts: f.counts(),
    259       duplicate: await f.reserve()
    260     };
    261   });
    262   expect(result.a.status).toBe('reserved');
    263   expect(result.b).toMatchObject({
    264     status: 'busy',
    265     disposition: 'not_created'
    266   });
    267   expect(result.rows).toHaveLength(1);
    268   expect(result.rows[0].id).toBe(result.a.snapshot?.id);
    269   expect(result.duplicate.status).toBe('existing');
    270   expect(result.duplicate.snapshot).toEqual(result.a.snapshot);
    271   expect(result.counts).toEqual({
    272     keys: 0,
    273     encrypts: 0,
    274     decrypts: 0,
    275     signs: 0
    276   });
    277 });
    278 
    279 test('failed original probe wrapping stays protected and cannot mint a replacement after SDK recovery', async ({
    280   page
    281 }) => {
    282   await page.evaluate(() => window.p8Fixture.reserve());
    283   expect(await page.evaluate(() => window.p8Fixture.prepareSeal())).toBe(
    284     'sealed'
    285   );
    286   const result = await page.evaluate(() => {
    287     const api = window.p8,
    288       f = window.p8Fixture,
    289       fault = f.installWrapFault();
    290     window.p8Restore = () => fault.restore();
    291     const first = f.wrapOriginal();
    292     fault.allow();
    293     const second = f.wrapOriginal();
    294     return {
    295       first,
    296       second,
    297       calls: fault.calls(),
    298       sealCurrent: api.inboxProbeSealSnapshot(f.seal()!) !== undefined,
    299       noWrap: f.wrap() === undefined,
    300       noReplacement:
    301         api.buildInboxProbeGiftwrap(f.seal()!, 'reviewed_inbox_probe_wrap') ===
    302         undefined
    303     };
    304   });
    305   expect(result).toEqual({
    306     first: 'wrap_failed',
    307     second: 'wrap_failed',
    308     calls: 1,
    309     sealCurrent: true,
    310     noWrap: true,
    311     noReplacement: true
    312   });
    313   const rows = await page.evaluate(() => window.p8Fixture.stored());
    314   expect(rows).toHaveLength(1);
    315   expect(JSON.parse(rows[0].wire)).toMatchObject({
    316     family: 'private_access_probe',
    317     revision: 0,
    318     self: null,
    319     receipts: []
    320   });
    321   expect(
    322     frames.some((frame) => ['EVENT', 'AUTH'].includes(String(frame[0])))
    323   ).toBe(false);
    324 });
    325 
    326 test('controller close rejects reentry, clears the original nonce first and retries only failed cleanup', async ({
    327   page
    328 }) => {
    329   await page.evaluate(() => window.p8Fixture.reserve());
    330   const original = await page.evaluate(() => window.p8Fixture.stored());
    331   const result = await page.evaluate(() => {
    332     const api = window.p8,
    333       f = window.p8Fixture,
    334       controller = f.controller()!;
    335     let calls = 0,
    336       nested: boolean | undefined,
    337       failing = true,
    338       cleared = false;
    339     const off = api.subscribeInboxAccessControllerClose(controller, () => {
    340       calls++;
    341       cleared =
    342         api.inboxProbeRumorWire(f.probeIdentity()!, f.session) === undefined;
    343       nested = api.closeInboxAccessController(controller);
    344       if (failing) throw Error('controlled original cleanup fault');
    345     });
    346     const first = api.closeInboxAccessController(controller),
    347       firstCleanup =
    348         api.inboxAccessControllerSnapshot(controller)?.cleanupRequired;
    349     failing = false;
    350     const second = api.closeInboxAccessController(controller),
    351       secondCleanup =
    352         api.inboxAccessControllerSnapshot(controller)?.cleanupRequired;
    353     off();
    354     return {
    355       first,
    356       firstCleanup,
    357       second,
    358       secondCleanup,
    359       calls,
    360       nested,
    361       cleared
    362     };
    363   });
    364   expect(result).toEqual({
    365     first: false,
    366     firstCleanup: true,
    367     second: true,
    368     secondCleanup: false,
    369     calls: 2,
    370     nested: false,
    371     cleared: true
    372   });
    373   expect(await page.evaluate(() => window.p8Fixture.stored())).toEqual(
    374     original
    375   );
    376   expect(await page.evaluate(() => window.p8Fixture.reserve())).toMatchObject({
    377     status: 'stopped',
    378     disposition: 'may_exist'
    379   });
    380 });
    381 
    382 test('unsupported and unconfigured declarations refuse before rows, provider work or private transport', async ({
    383   page
    384 }) => {
    385   const before = await page.evaluate(() => window.p8Fixture.counts());
    386   for (const selected of ['unsupported', 'unconfigured'] as const) {
    387     const result = await page.evaluate(
    388       (selected) =>
    389         window.p8Fixture.reserve(
    390           window.p8Fixture.operator(
    391             selected === 'unsupported',
    392             selected === 'unconfigured'
    393           )
    394         ),
    395       selected
    396     );
    397     expect(result).toMatchObject({
    398       status: 'unavailable',
    399       disposition: 'not_created'
    400     });
    401   }
    402   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(0);
    403   expect(await page.evaluate(() => window.p8Fixture.counts())).toEqual(before);
    404 });
    405 
    406 test('foreign namespace and forged owner/config inputs cannot reserve or observe a provider', async ({
    407   page
    408 }) => {
    409   const result = await page.evaluate(async () => {
    410     const f = window.p8Fixture,
    411       api = window.p8,
    412       before = f.counts();
    413     const fake = Object.freeze({ owner: f.owner, current: () => true });
    414     const reservation = await api.reserveInboxProbeIdentity(
    415       fake as unknown as Parameters<typeof api.reserveInboxProbeIdentity>[0],
    416       f.session,
    417       f.policy,
    418       f.controller()!,
    419       f.qualification,
    420       'reviewed_inbox_probe_reservation'
    421     );
    422     const forged = await api.reserveInboxProbeIdentity(
    423       f.repository,
    424       fake as unknown as Parameters<typeof api.reserveInboxProbeIdentity>[1],
    425       f.policy,
    426       f.controller()!,
    427       f.qualification,
    428       'reviewed_inbox_probe_reservation'
    429     );
    430     const config = await api.reserveInboxProbeIdentity(
    431       f.repository,
    432       f.session,
    433       f.policy,
    434       f.controller()!,
    435       fake as unknown as Parameters<typeof api.reserveInboxProbeIdentity>[4],
    436       'reviewed_inbox_probe_reservation'
    437     );
    438     return {
    439       reservation,
    440       forged,
    441       config,
    442       before,
    443       after: f.counts(),
    444       rows: await f.stored()
    445     };
    446   });
    447   expect(result.reservation).toMatchObject({
    448     status: 'invalid_scope',
    449     disposition: 'not_created'
    450   });
    451   expect(result.forged).toMatchObject({
    452     status: 'invalid_scope',
    453     disposition: 'not_created'
    454   });
    455   expect(result.config).toMatchObject({
    456     status: 'unavailable',
    457     disposition: 'not_created'
    458   });
    459   expect(result.before).toEqual(result.after);
    460   expect(result.rows).toHaveLength(0);
    461 });
    462 
    463 test('genuine foreign namespace, same-owner session and distinct policy cannot borrow the original controller', async ({
    464   page
    465 }) => {
    466   const result = await page.evaluate(async () => {
    467     const f = window.p8Fixture,
    468       api = window.p8,
    469       session = await f.foreignSession(),
    470       before = f.counts();
    471     const invoke = (
    472       repository: Parameters<typeof api.reserveInboxProbeIdentity>[0],
    473       session: Parameters<typeof api.reserveInboxProbeIdentity>[1],
    474       policy: Parameters<typeof api.reserveInboxProbeIdentity>[2]
    475     ) =>
    476       api.reserveInboxProbeIdentity(
    477         repository,
    478         session,
    479         policy,
    480         f.controller()!,
    481         f.qualification,
    482         'reviewed_inbox_probe_reservation'
    483       );
    484     return {
    485       namespace: await invoke(f.foreignRepository(), f.session, f.policy),
    486       session: await invoke(f.repository, session, f.policy),
    487       policy: await invoke(f.repository, f.session, f.copiedPolicy()),
    488       before,
    489       after: f.counts(),
    490       rows: await f.stored()
    491     };
    492   });
    493   for (const disposition of [result.namespace, result.session, result.policy])
    494     expect(disposition).toEqual({
    495       status: 'invalid_scope',
    496       disposition: 'not_created'
    497     });
    498   expect(result.before).toEqual(result.after);
    499   expect(result.rows).toHaveLength(0);
    500 });
    501 
    502 test('native put success followed by abort gives no identity, row or crypto permission', async ({
    503   page
    504 }) => {
    505   await page.evaluate(() => {
    506     window.p8Restore = window.p8Fixture.installNativeAbort();
    507   });
    508   expect(await page.evaluate(() => window.p8Fixture.reserve())).toMatchObject({
    509     status: 'aborted',
    510     disposition: 'not_created'
    511   });
    512   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(0);
    513   expect(
    514     await page.evaluate(() => window.p8Fixture.probeIdentity())
    515   ).toBeUndefined();
    516   expect(await page.evaluate(() => window.p8Fixture.counts())).toEqual({
    517     keys: 0,
    518     encrypts: 0,
    519     decrypts: 0,
    520     signs: 0
    521   });
    522 });
    523 
    524 test('actual competing native write before readonly reconciliation cannot issue an original identity', async ({
    525   page
    526 }) => {
    527   await page.evaluate(() => {
    528     window.p8Restore = window.p8Fixture.installChangedReadback();
    529   });
    530   expect(await page.evaluate(() => window.p8Fixture.reserve())).toMatchObject({
    531     status: 'conflict',
    532     disposition: 'may_exist'
    533   });
    534   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(1);
    535   expect(
    536     await page.evaluate(() => window.p8Fixture.probeIdentity())
    537   ).toBeUndefined();
    538   expect(await page.evaluate(() => window.p8Fixture.counts())).toEqual({
    539     keys: 0,
    540     encrypts: 0,
    541     decrypts: 0,
    542     signs: 0
    543   });
    544 });
    545 
    546 test('the genuine reservation respects the existing full joint native quota before prompts', async ({
    547   page
    548 }) => {
    549   await page.evaluate(() => window.p8Fixture.fillCapacity());
    550   expect(await page.evaluate(() => window.p8Fixture.reserve())).toMatchObject({
    551     status: 'capacity',
    552     disposition: 'not_created'
    553   });
    554   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(
    555     100
    556   );
    557   expect(await page.evaluate(() => window.p8Fixture.counts())).toEqual({
    558     keys: 0,
    559     encrypts: 0,
    560     decrypts: 0,
    561     signs: 0
    562   });
    563 });
    564 
    565 for (const mode of [
    566   'wrong_key',
    567   'refuse_encrypt',
    568   'refuse_decrypt',
    569   'refuse_sign',
    570   'wrong_encrypt',
    571   'wrong_decrypt',
    572   'wrong_sign_author',
    573   'wrong_sign_time',
    574   'wrong_sign_tags',
    575   'cached_signature',
    576   'stop_encrypt_getter',
    577   'stop_decrypt_getter'
    578 ] as const) {
    579   test(`genuine construction rejects ${mode} without any probe EVENT`, async ({
    580     page
    581   }) => {
    582     await page.evaluate(() => window.p8Fixture.reserve());
    583     const rows = await page.evaluate(() => window.p8Fixture.stored());
    584     await page.evaluate((mode) => window.p8Fixture.mode(mode), mode);
    585     expect(await page.evaluate(() => window.p8Fixture.prepare())).not.toBe(
    586       'wrapped'
    587     );
    588     expect(await page.evaluate(() => window.p8Fixture.wrap())).toBeUndefined();
    589     expect(await page.evaluate(() => window.p8Fixture.stored())).toEqual(rows);
    590     expect(
    591       frames.some((frame) => ['EVENT', 'AUTH'].includes(String(frame[0])))
    592     ).toBe(false);
    593     if (mode.startsWith('stop_'))
    594       expect(await page.evaluate(() => window.p8Fixture.counts())).toEqual({
    595         keys: 0,
    596         encrypts: 0,
    597         decrypts: 0,
    598         signs: 0
    599       });
    600   });
    601 }
    602 
    603 for (const stage of ['key', 'encrypt', 'decrypt', 'sign'] as const) {
    604   for (const invalidation of ['stop', 'head', 'session'] as const) {
    605     test(`pending ${stage} remains owned and late results are fenced after ${invalidation}`, async ({
    606       page
    607     }) => {
    608       await page.evaluate(() => window.p8Fixture.reserve());
    609       const rows = await page.evaluate(() => window.p8Fixture.stored());
    610       await page.evaluate((stage) => {
    611         window.p8Fixture.mode(('hold_' + stage) as Fixture.Mode);
    612         window.p8Pending = window.p8Fixture.prepare();
    613       }, stage);
    614       await expect
    615         .poll(() => page.evaluate(() => window.p8Fixture.waiting()))
    616         .toBe(stage);
    617       const observed = await page.evaluate((invalidation) => {
    618         const api = window.p8,
    619           f = window.p8Fixture;
    620         if (invalidation === 'stop') api.stopInboxProbeSeal(f.operation()!);
    621         else if (invalidation === 'head') f.churnHead();
    622         else f.logout();
    623         return {
    624           identity: api.inboxProbeSnapshot(f.probeIdentity()!) === undefined,
    625           wire:
    626             api.inboxProbeRumorWire(f.probeIdentity()!, f.session) === undefined
    627         };
    628       }, invalidation);
    629       expect(observed).toEqual({ identity: true, wire: true });
    630       await page.evaluate(() => window.p8Fixture.settle());
    631       expect(await page.evaluate(() => window.p8Pending)).toBe('stopped');
    632       expect(
    633         await page.evaluate(() => window.p8Fixture.wrap())
    634       ).toBeUndefined();
    635       expect(await page.evaluate(() => window.p8Fixture.stored())).toEqual(
    636         rows
    637       );
    638       expect(
    639         await page.evaluate(() => window.p8Fixture.reserve())
    640       ).toMatchObject({ status: 'stopped', disposition: 'may_exist' });
    641       expect(
    642         frames.some((frame) => ['EVENT', 'AUTH'].includes(String(frame[0])))
    643       ).toBe(false);
    644     });
    645   }
    646 }
    647 
    648 test('S4A genuine persistence acknowledges only the exact native original ciphertext without provider or transport work', async ({
    649   page
    650 }) => {
    651   await page.evaluate(() => window.p8Fixture.reserve());
    652   expect(await page.evaluate(() => window.p8Fixture.prepare())).toBe('wrapped');
    653   const result = await page.evaluate(async () => {
    654     const f = window.p8Fixture,
    655       api = window.p8,
    656       before = f.counts();
    657     const result = await f.commitOriginal();
    658     const ack = f.acknowledgement()!;
    659     const snapshot = api.inboxProbeAcknowledgementSnapshot(ack)!;
    660     const observed = await api.observePrivateRecord(
    661       f.repository,
    662       'private_sends',
    663       snapshot.record.id
    664     );
    665     const rumor = JSON.parse(
    666       api.inboxProbeRumorWire(f.probeIdentity()!, f.session)!
    667     ) as { content: string };
    668     const rows = await f.stored();
    669     const firstWire = JSON.stringify(rows);
    670     (snapshot.record.binding.readTargets as string[]).pop();
    671     const repeat = await f.commitOriginal();
    672     return {
    673       status: result.status,
    674       fact: result.snapshot?.fact,
    675       row: result.snapshot?.record,
    676       exact: observed.ok && observed.value.wire === rows[0].wire,
    677       verified: await api.verifyInboxProbeAcknowledgement(
    678         f.repository,
    679         f.session,
    680         ack
    681       ),
    682       repeated: repeat.status,
    683       unchanged: firstWire === JSON.stringify(await f.stored()),
    684       bodyAbsent:
    685         !firstWire.includes(rumor.content) &&
    686         !firstWire.includes(rumor.content.slice(-64)),
    687       ordinaryRejected:
    688         api.pairedDeliveryAcknowledgementSnapshot(
    689           ack as unknown as Parameters<
    690             typeof api.pairedDeliveryAcknowledgementSnapshot
    691           >[0]
    692         ) === undefined,
    693       detached:
    694         api.inboxProbeAcknowledgementSnapshot(ack)?.record.binding.readTargets
    695           .length === 1,
    696       before,
    697       after: f.counts()
    698     };
    699   });
    700   expect(result.status).toBe('prepared');
    701   expect(result.fact).toBe('acknowledged_local_probe_ciphertext_only');
    702   expect(result.row).toMatchObject({
    703     family: 'private_access_probe',
    704     revision: 1,
    705     receipts: [],
    706     self: { eventId: expect.any(String), wire: expect.any(String) }
    707   });
    708   expect(result.repeated).toBe('existing');
    709   expect(
    710     result.exact &&
    711       result.verified &&
    712       result.unchanged &&
    713       result.bodyAbsent &&
    714       result.ordinaryRejected &&
    715       result.detached
    716   ).toBe(true);
    717   expect(result.before).toEqual(result.after);
    718   expect(
    719     frames.some((frame) => ['EVENT', 'AUTH'].includes(String(frame[0])))
    720   ).toBe(false);
    721 });
    722 
    723 test('S4A simultaneous same-wrap calls admit one native original and return busy for the pending duplicate', async ({
    724   page
    725 }) => {
    726   await page.evaluate(() => window.p8Fixture.reserve());
    727   await page.evaluate(() => window.p8Fixture.prepare());
    728   const result = await page.evaluate(async () => {
    729     const f = window.p8Fixture,
    730       api = window.p8,
    731       before = f.counts();
    732     const results = await Promise.all(
    733       [1, 2].map(() =>
    734         api.commitInboxProbe(
    735           f.repository,
    736           f.session,
    737           f.wrap()!,
    738           'reviewed_inbox_probe_commit'
    739         )
    740       )
    741     );
    742     return {
    743       statuses: results.map((r) => r.status).sort(),
    744       rows: (await f.stored()).length,
    745       before,
    746       after: f.counts()
    747     };
    748   });
    749   expect(result.statuses).toEqual(['busy', 'prepared']);
    750   expect(result.rows).toBe(1);
    751   expect(result.before).toEqual(result.after);
    752 });
    753 
    754 test('S4A forged wraps, wrong consent and genuine alternate namespace/session cannot borrow the original', async ({
    755   page
    756 }) => {
    757   await page.evaluate(() => window.p8Fixture.reserve());
    758   await page.evaluate(() => window.p8Fixture.prepare());
    759   const result = await page.evaluate(async () => {
    760     const f = window.p8Fixture,
    761       api = window.p8;
    762     const other = await f.foreignSession(),
    763       before = f.counts(),
    764       rows = await f.stored();
    765     const wrap = f.wrap()!,
    766       copy = api.inboxProbeGiftwrapSnapshot(wrap)!;
    767     const results = [
    768       await api.commitInboxProbe(
    769         f.foreignRepository(),
    770         f.session,
    771         wrap,
    772         'reviewed_inbox_probe_commit'
    773       ),
    774       await api.commitInboxProbe(
    775         f.repository,
    776         other,
    777         wrap,
    778         'reviewed_inbox_probe_commit'
    779       ),
    780       await api.commitInboxProbe(
    781         f.repository,
    782         f.session,
    783         copy as unknown as typeof wrap,
    784         'reviewed_inbox_probe_commit'
    785       ),
    786       await api.commitInboxProbe(
    787         f.repository,
    788         f.session,
    789         wrap,
    790         'reviewed_private_delivery'
    791       ),
    792       await api.commitInboxProbe(
    793         f.repository,
    794         f.session,
    795         f.seal()! as unknown as typeof wrap,
    796         'reviewed_inbox_probe_commit'
    797       )
    798     ];
    799     const genuine = await f.commitOriginal();
    800     const primitiveStatuses = [];
    801     for (const primitive of [null, 0, 'wrap', true]) {
    802       primitiveStatuses.push(
    803         (
    804           await api.commitInboxProbe(
    805             f.repository,
    806             f.session,
    807             primitive as unknown as typeof wrap,
    808             'reviewed_inbox_probe_commit'
    809           )
    810         ).status
    811       );
    812     }
    813     const ack = f.acknowledgement()!;
    814     return {
    815       statuses: results.map((r) => r.status),
    816       primitiveStatuses,
    817       originalWasProtected: rows[0].wire.includes('"self":null'),
    818       genuine: genuine.status,
    819       forgedAck: await api.verifyInboxProbeAcknowledgement(
    820         f.repository,
    821         f.session,
    822         genuine.snapshot as unknown as typeof ack
    823       ),
    824       foreign: await api.verifyInboxProbeAcknowledgement(
    825         f.foreignRepository(),
    826         f.session,
    827         ack
    828       ),
    829       other: await api.verifyInboxProbeAcknowledgement(
    830         f.repository,
    831         other,
    832         ack
    833       ),
    834       actual: await api.verifyInboxProbeAcknowledgement(
    835         f.repository,
    836         f.session,
    837         ack
    838       ),
    839       before,
    840       after: f.counts()
    841     };
    842   });
    843   expect(result.statuses).toEqual([
    844     'invalid',
    845     'invalid',
    846     'invalid',
    847     'invalid',
    848     'invalid'
    849   ]);
    850   expect(result.primitiveStatuses).toEqual([
    851     'invalid',
    852     'invalid',
    853     'invalid',
    854     'invalid'
    855   ]);
    856   expect(result.originalWasProtected).toBe(true);
    857   expect(result.genuine).toBe('prepared');
    858   expect(result.forgedAck || result.foreign || result.other).toBe(false);
    859   expect(result.actual).toBe(true);
    860   expect(result.before).toEqual(result.after);
    861 });
    862 
    863 test('S4A actual owner lock and SDK slot contention preserve the native reservation for an explicit original retry', async ({
    864   page
    865 }) => {
    866   await page.evaluate(() => window.p8Fixture.reserve());
    867   await page.evaluate(() => window.p8Fixture.prepare());
    868   const result = await page.evaluate(async () => {
    869     const f = window.p8Fixture,
    870       api = window.p8,
    871       rows = JSON.stringify(await f.stored()),
    872       before = f.counts();
    873     let releaseLock = () => {},
    874       entered = () => {};
    875     const enteredPromise = new Promise<void>((resolve) => {
    876       entered = resolve;
    877     });
    878     const held = navigator.locks.request(
    879       'harvestcircle:owner:' + f.owner,
    880       async () => {
    881         entered();
    882         await new Promise<void>((resolve) => {
    883           releaseLock = resolve;
    884         });
    885       }
    886     );
    887     await enteredPromise;
    888     const lock = await f.commitOriginal();
    889     releaseLock();
    890     await held;
    891     let releaseSlot = () => {},
    892       slotEntered = () => {};
    893     const slotPromise = new Promise<void>((resolve) => {
    894       slotEntered = resolve;
    895     });
    896     const slot = api.withIdlePrivateLocalStorage(f.session, async () => {
    897       slotEntered();
    898       await new Promise<void>((resolve) => {
    899         releaseSlot = resolve;
    900       });
    901     });
    902     await slotPromise;
    903     const busy = await f.commitOriginal();
    904     const unchanged = rows === JSON.stringify(await f.stored());
    905     releaseSlot();
    906     await slot;
    907     const original = await f.commitOriginal();
    908     return {
    909       lock: lock.status,
    910       busy: busy.status,
    911       unchanged,
    912       original: original.status,
    913       before,
    914       after: f.counts()
    915     };
    916   });
    917   expect(result).toMatchObject({
    918     lock: 'busy',
    919     busy: 'busy',
    920     unchanged: true,
    921     original: 'prepared'
    922   });
    923   expect(result.before).toEqual(result.after);
    924 });
    925 
    926 test('S4A put success followed by native abort cannot issue a saved fact or alter the original reservation', async ({
    927   page
    928 }) => {
    929   await page.evaluate(() => window.p8Fixture.reserve());
    930   await page.evaluate(() => window.p8Fixture.prepare());
    931   const before = await page.evaluate(() => window.p8Fixture.stored());
    932   await page.evaluate(() => {
    933     window.p8Restore = window.p8Fixture.installNativeAbort();
    934   });
    935   expect(await page.evaluate(() => window.p8Fixture.commitOriginal())).toEqual({
    936     status: 'aborted',
    937     snapshot: undefined
    938   });
    939   expect(await page.evaluate(() => window.p8Fixture.stored())).toEqual(before);
    940   expect(
    941     await page.evaluate(() => window.p8Fixture.acknowledgement())
    942   ).toBeUndefined();
    943   await page.evaluate(() => {
    944     window.p8Restore?.();
    945     window.p8Restore = undefined;
    946   });
    947   expect(
    948     await page.evaluate(() => window.p8Fixture.commitOriginal())
    949   ).toMatchObject({ status: 'prepared' });
    950 });
    951 
    952 test('S4A genuine uncertain native completion reconciles the exact original once without rebuilding crypto', async ({
    953   page
    954 }) => {
    955   await page.evaluate(() => window.p8Fixture.reserve());
    956   await page.evaluate(() => window.p8Fixture.prepare());
    957   const result = await page.evaluate(async () => {
    958     const f = window.p8Fixture,
    959       api = window.p8,
    960       before = f.counts();
    961     const uncertain = f.installUncertainCommit();
    962     window.p8Restore = uncertain.restore;
    963     try {
    964       const result = await f.commitOriginal();
    965       const firstRows = JSON.stringify(await f.stored());
    966       const ack = f.acknowledgement()!;
    967       const verified = await api.verifyInboxProbeAcknowledgement(
    968         f.repository,
    969         f.session,
    970         ack
    971       );
    972       uncertain.restore();
    973       window.p8Restore = undefined;
    974       const repeated = await f.commitOriginal();
    975       return {
    976         status: result.status,
    977         verified,
    978         counts: uncertain.counts(),
    979         repeated: repeated.status,
    980         exactOriginal: firstRows === JSON.stringify(await f.stored()),
    981         before,
    982         after: f.counts()
    983       };
    984     } finally {
    985       uncertain.restore();
    986       window.p8Restore = undefined;
    987     }
    988   });
    989   expect(result).toMatchObject({
    990     status: 'reconciled',
    991     verified: true,
    992     repeated: 'existing',
    993     exactOriginal: true,
    994     counts: {
    995       nativeComplete: 1,
    996       nativeAbort: 0,
    997       putSuccess: 1,
    998       abortRefused: 1
    999     }
   1000   });
   1001   expect(result.before).toEqual(result.after);
   1002 });
   1003 
   1004 for (const close of ['controller', 'session', 'head'] as const) {
   1005   test(`S4A ${close} loss at actual native completion protects saved ciphertext but issues no live acknowledgement`, async ({
   1006     page
   1007   }) => {
   1008     await page.evaluate(() => window.p8Fixture.reserve());
   1009     await page.evaluate(() => window.p8Fixture.prepare());
   1010     await page.evaluate((close) => {
   1011       const f = window.p8Fixture;
   1012       window.p8Restore = f.installCommitCompletion(() => {
   1013         if (close === 'controller')
   1014           window.p8.closeInboxAccessController(f.controller()!);
   1015         else if (close === 'session') f.closeSession();
   1016         else f.churnHead();
   1017       });
   1018     }, close);
   1019     expect(
   1020       await page.evaluate(() => window.p8Fixture.commitOriginal())
   1021     ).toEqual({ status: 'stopped', snapshot: undefined });
   1022     const rows = await page.evaluate(() => window.p8Fixture.stored());
   1023     expect(rows).toHaveLength(1);
   1024     expect(JSON.parse(rows[0].wire)).toMatchObject({
   1025       revision: 1,
   1026       self: { wire: expect.any(String) }
   1027     });
   1028     expect(
   1029       await page.evaluate(() => window.p8Fixture.acknowledgement())
   1030     ).toBeUndefined();
   1031     expect(
   1032       frames.some((frame) => ['EVENT', 'AUTH'].includes(String(frame[0])))
   1033     ).toBe(false);
   1034   });
   1035 }
   1036 
   1037 test('S4A physical whitespace aliases remain detectable despite identical decoded canonical metadata', async ({
   1038   page
   1039 }) => {
   1040   await page.evaluate(() => window.p8Fixture.reserve());
   1041   await page.evaluate(() => window.p8Fixture.prepare());
   1042   const result = await page.evaluate(async () => {
   1043     const f = window.p8Fixture,
   1044       api = window.p8;
   1045     await f.commitOriginal();
   1046     const ack = f.acknowledgement()!,
   1047       row = (await f.stored())[0];
   1048     const before = await api.loadPrivateRecord(
   1049       f.repository,
   1050       'private_sends',
   1051       row.id
   1052     );
   1053     await f.inject([{ ...row, wire: '  ' + row.wire + '\n' }]);
   1054     const after = await api.loadPrivateRecord(
   1055       f.repository,
   1056       'private_sends',
   1057       row.id
   1058     );
   1059     const observed = await api.observePrivateRecord(
   1060       f.repository,
   1061       'private_sends',
   1062       row.id
   1063     );
   1064     const canonicalSame =
   1065       before.ok &&
   1066       after.ok &&
   1067       api.privateRecordWire(before.value, f.owner, row.id) ===
   1068         api.privateRecordWire(after.value, f.owner, row.id);
   1069     const verified = await api.verifyInboxProbeAcknowledgement(
   1070       f.repository,
   1071       f.session,
   1072       ack
   1073     );
   1074     const revoked = api.inboxProbeAcknowledgementSnapshot(ack) === undefined;
   1075     const retry = await f.commitOriginal();
   1076     return {
   1077       canonicalSame,
   1078       actualChanged: observed.ok && observed.value.wire !== row.wire,
   1079       verified,
   1080       revoked,
   1081       retry: retry.status,
   1082       count: (await f.stored()).length
   1083     };
   1084   });
   1085   expect(result).toEqual({
   1086     canonicalSame: true,
   1087     actualChanged: true,
   1088     verified: false,
   1089     revoked: true,
   1090     retry: 'conflict',
   1091     count: 1
   1092   });
   1093 });
   1094 
   1095 test('S4A equivalent physical mutation queued before fresh native readback prevents the first acknowledgement', async ({
   1096   page
   1097 }) => {
   1098   await page.evaluate(() => window.p8Fixture.reserve());
   1099   await page.evaluate(() => window.p8Fixture.prepare());
   1100   await page.evaluate(() => {
   1101     const f = window.p8Fixture,
   1102       record = window.p8.inboxProbeSnapshot(f.probeIdentity()!)!,
   1103       artifact = window.p8.inboxProbeGiftwrapSnapshot(f.wrap()!)!;
   1104     const wire = JSON.stringify({
   1105       ...record,
   1106       revision: 1,
   1107       self: {
   1108         eventId: (JSON.parse(artifact.wire) as { id: string }).id,
   1109         wire: artifact.wire
   1110       }
   1111     });
   1112     window.p8Restore = f.installCommitCompletion(() => {
   1113       void f.inject([{ owner: f.owner, id: record.id, wire: ' ' + wire }]);
   1114     });
   1115   });
   1116   expect(await page.evaluate(() => window.p8Fixture.commitOriginal())).toEqual({
   1117     status: 'conflict',
   1118     snapshot: undefined
   1119   });
   1120   expect(
   1121     await page.evaluate(() => window.p8Fixture.acknowledgement())
   1122   ).toBeUndefined();
   1123   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(1);
   1124 });
   1125 
   1126 for (const mutation of [
   1127   'metadata',
   1128   'later_facts',
   1129   'corrupt_tail',
   1130   'removed'
   1131 ] as const) {
   1132   test(`S4A fresh acknowledgement verification revokes ${mutation} custody without recreating an artifact`, async ({
   1133     page
   1134   }) => {
   1135     await page.evaluate(() => window.p8Fixture.reserve());
   1136     await page.evaluate(() => window.p8Fixture.prepare());
   1137     const result = await page.evaluate(async (mutation) => {
   1138       const f = window.p8Fixture,
   1139         api = window.p8;
   1140       await f.commitOriginal();
   1141       const ack = f.acknowledgement()!,
   1142         row = (await f.stored())[0];
   1143       const record = JSON.parse(row.wire) as {
   1144         createdAt: number;
   1145         revision: number;
   1146         self: { eventId: string };
   1147         binding: { archiveTargets: string[] };
   1148         receipts: unknown[];
   1149       };
   1150       if (mutation === 'removed') await f.removeOriginal();
   1151       else if (mutation === 'corrupt_tail')
   1152         await f.inject([
   1153           { owner: f.owner, id: crypto.randomUUID(), wire: 'broken' }
   1154         ]);
   1155       else {
   1156         if (mutation === 'metadata') record.createdAt++;
   1157         else {
   1158           record.revision++;
   1159           record.receipts.push({
   1160             actionId: crypto.randomUUID(),
   1161             origin: record.binding.archiveTargets[0],
   1162             role: 'access_archive',
   1163             attempt: 1,
   1164             eventId: record.self.eventId,
   1165             status: 'accepted',
   1166             observedAtMilliseconds: 1,
   1167             readbackWire: null
   1168           });
   1169         }
   1170         await f.inject([{ ...row, wire: JSON.stringify(record) }]);
   1171       }
   1172       const before = f.counts();
   1173       const verified = await api.verifyInboxProbeAcknowledgement(
   1174         f.repository,
   1175         f.session,
   1176         ack
   1177       );
   1178       const retry = await f.commitOriginal();
   1179       return {
   1180         verified,
   1181         revoked: api.inboxProbeAcknowledgementSnapshot(ack) === undefined,
   1182         status: retry.status,
   1183         before,
   1184         after: f.counts()
   1185       };
   1186     }, mutation);
   1187     expect(result.verified).toBe(false);
   1188     expect(result.revoked).toBe(true);
   1189     expect(['conflict', 'invalid_record', 'corrupt_record']).toContain(
   1190       result.status
   1191     );
   1192     expect(result.before).toEqual(result.after);
   1193   });
   1194 }
   1195 
   1196 test('S4A preparation grows the existing row at the full joint 100-row ceiling', async ({
   1197   page
   1198 }) => {
   1199   await page.evaluate(() => window.p8Fixture.reserve());
   1200   await page.evaluate(() => window.p8Fixture.prepare());
   1201   await page.evaluate(() => window.p8Fixture.fillCapacity(99));
   1202   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(
   1203     100
   1204   );
   1205   expect(
   1206     await page.evaluate(() => window.p8Fixture.commitOriginal())
   1207   ).toMatchObject({ status: 'prepared' });
   1208   expect(await page.evaluate(() => window.p8Fixture.stored())).toHaveLength(
   1209     100
   1210   );
   1211 });
   1212 
   1213 test('S4A actual complete row bytes refuse artifact growth with bounded structural filler and preserve the original', async ({
   1214   page
   1215 }) => {
   1216   await page.evaluate(() => window.p8Fixture.reserve());
   1217   await page.evaluate(() => window.p8Fixture.prepare());
   1218   const bound = await page.evaluate(() =>
   1219     window.p8Fixture.fillProbeByteHeadroom()
   1220   );
   1221   expect(bound.count).toBe(2);
   1222   expect(bound.bytes).toBeLessThanOrEqual(8 * 1024 * 1024);
   1223   expect(bound.headroom).toBeLessThan(bound.growth);
   1224   const result = await page.evaluate(async () => {
   1225     const f = window.p8Fixture,
   1226       before = JSON.stringify(await f.stored()),
   1227       counts = f.counts();
   1228     const result = await f.commitOriginal();
   1229     return {
   1230       status: result.status,
   1231       unchanged: before === JSON.stringify(await f.stored()),
   1232       noAcknowledgement: f.acknowledgement() === undefined,
   1233       counts,
   1234       after: f.counts()
   1235     };
   1236   });
   1237   expect(result).toMatchObject({
   1238     status: 'capacity',
   1239     unchanged: true,
   1240     noAcknowledgement: true
   1241   });
   1242   expect(result.counts).toEqual(result.after);
   1243 });