app

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

seal-builder.spec.ts (12840B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { createHash } from 'node:crypto';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 import type * as Seals from './harness/seal-builder.ts';
      7 declare global {
      8   interface Window {
      9     hcp075: typeof Seals;
     10     hcp075Fixture: Awaited<ReturnType<typeof Seals.makeFixture>>;
     11     hcp075Job: ReturnType<typeof Seals.buildPrivateSeal>;
     12     hcp075Release: () => void;
     13     hcp075Held: Promise<unknown>;
     14     hcp075Operation: NonNullable<
     15       ReturnType<typeof Seals.capturePrivateSealOperation>
     16     >;
     17   }
     18 }
     19 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
     20 test.beforeAll(async () => {
     21   server = await createStaticHarness();
     22   const result = await build({
     23     configFile: false,
     24     logLevel: 'silent',
     25     build: {
     26       write: false,
     27       minify: false,
     28       lib: {
     29         entry: fileURLToPath(
     30           new URL('./harness/seal-builder.ts', import.meta.url)
     31         ),
     32         name: 'hcp075',
     33         formats: ['iife']
     34       }
     35     }
     36   });
     37   const output = Array.isArray(result) ? result[0] : result;
     38   if (!('output' in output)) throw Error('missing bundle');
     39   const chunks = output.output.filter((x) => x.type === 'chunk');
     40   expect(chunks).toHaveLength(1);
     41   bundle = chunks[0].code;
     42   console.log(
     43     JSON.stringify({
     44       fixture: 'HCP075_ACTUAL_SDK_CRYPTO_IDB_OWNER_LOCK',
     45       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
     46       moduleIds: Object.keys(chunks[0].modules),
     47       qualification:
     48         'Ephemeral controlled provider; not installed extension/relay/client Q'
     49     })
     50   );
     51 });
     52 test.afterAll(async () => server.close());
     53 async function load(page: Page) {
     54   await page.goto(server.url + '/search');
     55   await page.addScriptTag({ content: bundle });
     56   await page.evaluate(async () => {
     57     window.hcp075Fixture = await window.hcp075.makeFixture();
     58   });
     59 }
     60 for (const role of ['peer', 'self'] as const)
     61   test(`actual SDK ${role} ciphertext preserves original rumor; sender signs empty-tag13 only`, async ({
     62     page
     63   }) => {
     64     await load(page);
     65     const result = await page.evaluate(async (role) => {
     66       const f = window.hcp075Fixture,
     67         s = window.hcp075,
     68         before = f.counts(),
     69         operation = f.operation(role);
     70       if (!operation) throw Error('missing operation');
     71       const outcome = await s.buildPrivateSeal(operation);
     72       if (outcome.status !== 'sealed') return { status: outcome.status };
     73       const saved = s.privateSealSnapshot(outcome.seal);
     74       if (!saved) throw Error('missing seal');
     75       const decrypted = f.decrypt(saved.wire, role),
     76         stored = await f.stored(),
     77         after = f.counts(),
     78         again = await s.buildPrivateSeal(operation);
     79       f.close();
     80       return {
     81         status: outcome.status,
     82         equal: decrypted.equal,
     83         kind: (JSON.parse(saved.wire) as { kind: number }).kind,
     84         tags: (JSON.parse(saved.wire) as { tags: string[][] }).tags,
     85         owner: saved.owner,
     86         target: saved.destination,
     87         expected: role === 'self' ? f.owner : f.peer,
     88         seven: Object.keys(JSON.parse(saved.wire) as Record<string, unknown>)
     89           .length,
     90         noPlaintext: !stored.includes('sentinel'),
     91         randomizedBounds:
     92           (JSON.parse(saved.wire) as { created_at: number }).created_at <=
     93             Math.floor(Date.now() / 1000) &&
     94           (JSON.parse(saved.wire) as { created_at: number }).created_at >=
     95             Math.floor(Date.now() / 1000) - 3599,
     96         signs: after.signs - before.signs,
     97         encrypts: after.encrypts - before.encrypts,
     98         keys: after.keys - before.keys,
     99         again: again.status
    100       };
    101     }, role);
    102     expect(result).toMatchObject({
    103       status: 'sealed',
    104       equal: true,
    105       kind: 13,
    106       tags: [],
    107       seven: 7,
    108       noPlaintext: true,
    109       randomizedBounds: true,
    110       signs: 1,
    111       encrypts: 1,
    112       keys: 4,
    113       again: 'stopped'
    114     });
    115     expect(result.target).toBe(result.expected);
    116   });
    117 for (const mode of [
    118   'wrong_cipher',
    119   'wrong_author',
    120   'wrong_tags',
    121   'wrong_time',
    122   'cached_bad_id'
    123 ] as const)
    124   test(`rejects ${mode} from provider without a seal capability`, async ({
    125     page
    126   }) => {
    127     await load(page);
    128     const result = await page.evaluate(async (mode) => {
    129       const f = window.hcp075Fixture,
    130         op = f.operation();
    131       if (!op) throw Error('missing operation');
    132       f.mode(mode);
    133       const outcome = await window.hcp075.buildPrivateSeal(op);
    134       f.close();
    135       return outcome.status;
    136     }, mode);
    137     expect(result).toBe('mismatch');
    138   });
    139 for (const mode of ['missing', 'declined', 'changed_key'] as const)
    140   test(`${mode} pauses without extra signature or retry`, async ({ page }) => {
    141     await load(page);
    142     const result = await page.evaluate(async (mode) => {
    143       const f = window.hcp075Fixture,
    144         op = f.operation(),
    145         before = f.counts();
    146       if (!op) throw Error('missing operation');
    147       f.mode(mode);
    148       const result = await window.hcp075.buildPrivateSeal(op),
    149         after = f.counts();
    150       f.close();
    151       return { status: result.status, signs: after.signs - before.signs };
    152     }, mode);
    153     expect(['unavailable', 'refused', 'stopped']).toContain(result.status);
    154     expect(result.signs).toBe(0);
    155   });
    156 test('detached reservation, wrong role or absent explicit review cannot acquire crypto authority', async ({
    157   page
    158 }) => {
    159   await load(page);
    160   const result = await page.evaluate(() => {
    161     const f = window.hcp075Fixture,
    162       s = window.hcp075,
    163       before = f.counts();
    164     const invalid = [
    165       f.operation('other'),
    166       f.operation('peer', 'connect'),
    167       s.capturePrivateSealOperation(
    168         f.identity,
    169         {} as typeof f.reserved,
    170         'peer',
    171         'reviewed_private_seal'
    172       )
    173     ];
    174     const after = f.counts();
    175     f.close();
    176     return {
    177       absent: invalid.every((x) => x === undefined),
    178       same: JSON.stringify(before) === JSON.stringify(after)
    179     };
    180   });
    181   expect(result).toEqual({ absent: true, same: true });
    182 });
    183 for (const phase of ['hold_encrypt', 'hold_decrypt', 'hold_sign'] as const)
    184   test(`disconnect during ${phase} retains real slot until settlement and fences late result`, async ({
    185     page
    186   }) => {
    187     await load(page);
    188     await page.evaluate((phase) => {
    189       const f = window.hcp075Fixture,
    190         op = f.operation();
    191       if (!op) throw Error('missing operation');
    192       window.hcp075Operation = op;
    193       f.mode(phase);
    194       window.hcp075Job = window.hcp075.buildPrivateSeal(op);
    195     }, phase);
    196     await expect
    197       .poll(() => page.evaluate(() => window.hcp075Fixture.slot()))
    198       .toMatchObject({
    199         state: 'active',
    200         pending:
    201           phase === 'hold_encrypt'
    202             ? 'encrypt'
    203             : phase === 'hold_decrypt'
    204               ? 'decrypt'
    205               : 'sign'
    206       });
    207     const pending = await page.evaluate(() => {
    208       const f = window.hcp075Fixture;
    209       f.disconnect();
    210       window.hcp075.stopPrivateSeal(window.hcp075Operation);
    211       return f.slot();
    212     });
    213     expect(pending).toMatchObject({ state: 'active' });
    214     const result = await page.evaluate(async () => {
    215       const f = window.hcp075Fixture,
    216         before = f.counts();
    217       f.settle();
    218       const outcome = await window.hcp075Job,
    219         after = f.counts(),
    220         slot = f.slot();
    221       f.close();
    222       return {
    223         status: outcome.status,
    224         slot,
    225         same: JSON.stringify(before) === JSON.stringify(after)
    226       };
    227     });
    228     expect(result).toEqual({
    229       status: 'stopped',
    230       slot: { state: 'idle' },
    231       same: true
    232     });
    233   });
    234 test('wait expiry prevents more calls but does not pretend to cancel pending extension approval', async ({
    235   page
    236 }) => {
    237   await load(page);
    238   await page.evaluate(() => {
    239     const f = window.hcp075Fixture,
    240       op = f.operation();
    241     if (!op) throw Error('missing operation');
    242     f.mode('hold_encrypt');
    243     window.hcp075Operation = op;
    244     window.hcp075Job = window.hcp075.buildPrivateSeal(op);
    245   });
    246   await expect
    247     .poll(() => page.evaluate(() => window.hcp075Fixture.slot()))
    248     .toMatchObject({ pending: 'encrypt' });
    249   const result = await page.evaluate(async () => {
    250     const f = window.hcp075Fixture,
    251       s = window.hcp075;
    252     s.expirePrivateSealWait(window.hcp075Operation);
    253     const pending = f.slot();
    254     f.settle();
    255     const outcome = await window.hcp075Job,
    256       slot = f.slot();
    257     f.close();
    258     return { pending, status: outcome.status, slot };
    259   });
    260   expect(result.pending).toMatchObject({
    261     state: 'active',
    262     pending: 'encrypt',
    263     phase: 'wait_expired'
    264   });
    265   expect(result.status).toBe('stopped');
    266   expect(result.slot).toEqual({ state: 'idle' });
    267 });
    268 test('held origin owner lock fails busy before any extension call and never queues a retry', async ({
    269   page
    270 }) => {
    271   await load(page);
    272   await page.evaluate(async () => {
    273     let acquired: () => void = () => {};
    274     const ready = new Promise<void>((resolve) => {
    275       acquired = resolve;
    276     });
    277     window.hcp075Held = navigator.locks.request(
    278       'harvestcircle:owner:' + window.hcp075Fixture.owner,
    279       async () => {
    280         acquired();
    281         await new Promise<void>((resolve) => {
    282           window.hcp075Release = resolve;
    283         });
    284       }
    285     );
    286     await ready;
    287   });
    288   const result = await page.evaluate(async () => {
    289     const f = window.hcp075Fixture,
    290       op = f.operation(),
    291       before = f.counts();
    292     if (!op) throw Error('missing operation');
    293     const outcome = await window.hcp075.buildPrivateSeal(op),
    294       after = f.counts();
    295     window.hcp075Release();
    296     await window.hcp075Held;
    297     const again = await window.hcp075.buildPrivateSeal(op);
    298     f.close();
    299     return {
    300       status: outcome.status,
    301       same: JSON.stringify(before) === JSON.stringify(after),
    302       again: again.status
    303     };
    304   });
    305   expect(result).toEqual({ status: 'busy', same: true, again: 'stopped' });
    306 });
    307 test('second peer/self operation cannot overlap the held scheduler/owner scope', async ({
    308   page
    309 }) => {
    310   await load(page);
    311   await page.evaluate(() => {
    312     const f = window.hcp075Fixture,
    313       op = f.operation('self');
    314     if (!op) throw Error('missing operation');
    315     f.mode('hold_encrypt');
    316     window.hcp075Operation = op;
    317     window.hcp075Job = window.hcp075.buildPrivateSeal(op);
    318   });
    319   await expect
    320     .poll(() => page.evaluate(() => window.hcp075Fixture.slot()))
    321     .toMatchObject({ state: 'active', pending: 'encrypt' });
    322   const result = await page.evaluate(async () => {
    323     const f = window.hcp075Fixture,
    324       s = window.hcp075,
    325       second = f.operation('peer'),
    326       before = f.counts();
    327     if (!second) throw Error('missing second operation');
    328     const blocked = await s.buildPrivateSeal(second),
    329       after = f.counts();
    330     s.stopPrivateSeal(window.hcp075Operation);
    331     f.settle();
    332     const original = await window.hcp075Job;
    333     f.close();
    334     return {
    335       blocked: blocked.status,
    336       same: JSON.stringify(before) === JSON.stringify(after),
    337       original: original.status
    338     };
    339   });
    340   expect(result).toEqual({ blocked: 'busy', same: true, original: 'stopped' });
    341 });
    342 test('provider method getter is captured before scheduler encryption admission, never re-read with private input', async ({
    343   page
    344 }) => {
    345   await load(page);
    346   const result = await page.evaluate(async () => {
    347     const f = window.hcp075Fixture,
    348       op = f.operation();
    349     if (!op) throw Error('missing operation');
    350     f.mode('getter_reentry');
    351     const outcome = await window.hcp075.buildPrivateSeal(op),
    352       counts = f.counts();
    353     f.close();
    354     return {
    355       status: outcome.status,
    356       reentrant: counts.reentrantReads,
    357       postStop: counts.postStopEncrypts
    358     };
    359   });
    360   expect(result).toEqual({ status: 'sealed', reentrant: 0, postStop: 0 });
    361 });
    362 for (const mode of [
    363   'stop_capability_getter',
    364   'stop_capability_after_key'
    365 ] as const)
    366   test(`${mode} stops only the original operation and preserves the current shared identity`, async ({
    367     page
    368   }) => {
    369     await load(page);
    370     const result = await page.evaluate(async (mode) => {
    371       const f = window.hcp075Fixture,
    372         op = f.operation(),
    373         before = f.counts();
    374       if (!op) throw Error('missing operation');
    375       f.mode(mode);
    376       const outcome = await window.hcp075.buildPrivateSeal(op),
    377         state = f.identityState(),
    378         after = f.counts();
    379       f.close();
    380       return {
    381         status: outcome.status,
    382         state,
    383         signs: after.signs - before.signs,
    384         encrypts: after.encrypts - before.encrypts
    385       };
    386     }, mode);
    387     expect(result).toEqual({
    388       status: 'stopped',
    389       state: 'messaging_capable',
    390       signs: 0,
    391       encrypts: 0
    392     });
    393   });