app

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

private-receipts.spec.ts (11937B)


      1 import { test, expect } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { once } from 'node:events';
      5 import { WebSocketServer } from 'ws';
      6 import { createStaticHarness } from '../integration/harness/static.ts';
      7 import type * as Fixture from './harness/private-receipts.ts';
      8 declare global {
      9   interface Window {
     10     hcp086: typeof Fixture;
     11     hcp086Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>;
     12   }
     13 }
     14 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     15   sockets: WebSocketServer,
     16   endpoint: string,
     17   bundle: string;
     18 let frames: unknown[][] = [],
     19   response = true;
     20 test.beforeAll(async () => {
     21   server = await createStaticHarness();
     22   sockets = new WebSocketServer({
     23     host: '127.0.0.1',
     24     port: 0,
     25     maxPayload: 65536
     26   });
     27   await once(sockets, 'listening');
     28   const address = sockets.address();
     29   if (!address || typeof address === 'string')
     30     throw Error('loopback unavailable');
     31   endpoint = 'ws://127.0.0.1:' + address.port;
     32   sockets.on('connection', (socket) =>
     33     socket.on('message', (bytes) => {
     34       const raw = Buffer.isBuffer(bytes)
     35           ? bytes
     36           : Array.isArray(bytes)
     37             ? Buffer.concat(bytes)
     38             : Buffer.from(bytes),
     39         frame = JSON.parse(raw.toString()) as unknown[];
     40       frames.push(frame);
     41       if (frame[0] === 'EVENT')
     42         socket.send(
     43           JSON.stringify([
     44             'OK',
     45             (frame[1] as { id: string }).id,
     46             response,
     47             response ? '' : 'blocked: fixture refusal'
     48           ])
     49         );
     50     })
     51   );
     52   const result = await build({
     53     configFile: false,
     54     logLevel: 'silent',
     55     build: {
     56       write: false,
     57       minify: false,
     58       lib: {
     59         entry: fileURLToPath(
     60           new URL('./harness/private-receipts.ts', import.meta.url)
     61         ),
     62         name: 'hcp086',
     63         formats: ['iife']
     64       }
     65     }
     66   });
     67   const output = Array.isArray(result) ? result[0] : result;
     68   if (!('output' in output)) throw Error('bundle unavailable');
     69   const chunks = output.output.filter((x) => x.type === 'chunk');
     70   expect(chunks).toHaveLength(1);
     71   bundle = chunks[0].code;
     72 });
     73 test.afterAll(async () => {
     74   for (const socket of sockets.clients) socket.terminate();
     75   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     76   await server.close();
     77 });
     78 async function load(page: import('@playwright/test').Page) {
     79   await page.goto(server.url + '/search');
     80   await page.addScriptTag({ content: bundle });
     81 }
     82 test.beforeEach(async ({ page }) => {
     83   frames = [];
     84   response = true;
     85   await page.addInitScript(
     86     ({ endpoint }) => {
     87       const Native = window.WebSocket;
     88       window.WebSocket = class extends Native {
     89         constructor(url: string | URL, protocols?: string | string[]) {
     90           const origin = new URL(String(url)).origin;
     91           if (
     92             !['wss://peer.example.org', 'wss://archive.example.org'].includes(
     93               origin
     94             )
     95           )
     96             throw Error('unapproved fixture destination');
     97           super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols);
     98         }
     99       };
    100     },
    101     { endpoint }
    102   );
    103   await load(page);
    104   await page.evaluate(async () => {
    105     window.hcp086Fixture = await window.hcp086.makeFixture();
    106     await window.hcp086Fixture.prepare();
    107   });
    108 });
    109 test.afterEach(async ({ page }) => {
    110   if (!page.isClosed())
    111     await page.evaluate(() => window.hcp086Fixture?.close());
    112 });
    113 test('actual archive ACK persists without claiming recipient receipt', async ({
    114   page
    115 }) => {
    116   const result = await page.evaluate(async () => {
    117     const f = window.hcp086Fixture,
    118       attempt = await f.deliver('self_archive'),
    119       saved = await f.observe('self_archive', attempt.status);
    120     return { attempt, saved, state: await f.state() };
    121   });
    122   expect(result.attempt.status).toBe('accepted');
    123   expect(result.saved.status).toBe('saved');
    124   expect(result.state.status?.recipient.state).toBe('unknown');
    125   expect(result.state.status?.archive.state).toBe('accepted_by_inbox_relay');
    126   expect(frames.filter((f) => f[0] === 'EVENT')).toHaveLength(1);
    127 });
    128 test('canonical receipt successor retains genuine custody for the remaining exact archive artifact', async ({
    129   page
    130 }) => {
    131   const r = await page.evaluate(async () => {
    132     const f = window.hcp086Fixture,
    133       original = await f.storedPair(),
    134       peer = await f.deliver('peer'),
    135       saved = await f.observe('peer', peer.status),
    136       verified = await f.verified(),
    137       archive = await f.deliver('self_archive'),
    138       savedArchive = await f.observe('self_archive', archive.status);
    139     return {
    140       original,
    141       peer,
    142       saved,
    143       verified,
    144       archive,
    145       savedArchive,
    146       state: await f.state()
    147     };
    148   });
    149   expect(r.saved.status).toBe('saved');
    150   expect(r.verified).toBe(true);
    151   expect(r.archive.status).toBe('accepted');
    152   expect(r.savedArchive.status).toBe('saved');
    153   expect(r.state.status?.partial).toBe(false);
    154   expect(
    155     r.state.row?.family === 'private_send_operation' && r.state.row.self
    156   ).toEqual(r.original!.self);
    157   expect(
    158     frames.filter((f) => f[0] === 'EVENT').map((f) => JSON.stringify(f[1]))
    159   ).toEqual([r.original!.peerArtifact!.wire, r.original!.self.wire]);
    160 });
    161 test('late duplicate actual ACK is idempotent without changing the retained first observation', async ({
    162   page
    163 }) => {
    164   const r = await page.evaluate(async () => {
    165     const f = window.hcp086Fixture,
    166       a = await f.deliver('peer');
    167     await f.observe('peer', a.status, 100);
    168     const before = await f.state(),
    169       again = await f.observe('peer', a.status, 200);
    170     return { before, again, after: await f.state() };
    171   });
    172   expect(r.again.status).toBe('existing');
    173   expect(r.after.wire).toBe(r.before.wire);
    174   expect(frames.filter((f) => f[0] === 'EVENT')).toHaveLength(1);
    175 });
    176 test('actual named refusal stays distinct from recipient success and archive pending', async ({
    177   page
    178 }) => {
    179   response = false;
    180   const r = await page.evaluate(async () => {
    181     const f = window.hcp086Fixture,
    182       a = await f.deliver('peer');
    183     return {
    184       attempt: a,
    185       saved: await f.observe('peer', a.status),
    186       state: await f.state()
    187     };
    188   });
    189   expect(r.attempt.status).toBe('refused');
    190   expect(r.saved.status).toBe('saved');
    191   expect(r.state.status?.recipient.state).toBe('unknown');
    192   expect(r.state.status?.archive.state).toBe('pending');
    193 });
    194 test('exact observed ciphertext readback is retained separately from acceptance', async ({
    195   page
    196 }) => {
    197   await page.evaluate(async () => {
    198     await window.hcp086Fixture.deliver('peer');
    199   });
    200   const event = frames.find((f) => f[0] === 'EVENT')?.[1];
    201   expect(event).toBeDefined();
    202   const r = await page.evaluate(async (wire) => {
    203     const f = window.hcp086Fixture;
    204     return {
    205       saved: await f.observe('peer', 'readback', 100, wire),
    206       state: await f.state()
    207     };
    208   }, JSON.stringify(event));
    209   expect(r.saved.status).toBe('saved');
    210   expect(r.state.status?.recipient.readbackTargets).toEqual([
    211     'wss://peer.example.org'
    212   ]);
    213   expect(r.state.status?.recipient.acceptedTargets).toEqual([]);
    214 });
    215 test('real full-wire CAS races preserve the winning role and reject stale receipt append', async ({
    216   page
    217 }) => {
    218   const r = await page.evaluate(async () => {
    219     const f = window.hcp086Fixture;
    220     return { results: await f.race(), state: await f.state() };
    221   });
    222   expect(r.results.map((x) => x.status).sort()).toEqual(['conflict', 'saved']);
    223   expect(
    224     r.state.row?.family === 'private_send_operation' && r.state.row.receipts
    225   ).toHaveLength(1);
    226   expect(frames).toEqual([]);
    227 });
    228 test('concurrent genuine receipt renewal keeps one exact winner and admits only its remaining stored artifact', async ({
    229   page
    230 }) => {
    231   const r = await page.evaluate(() => window.hcp086Fixture.genuineRace());
    232   expect(r.results.map((x) => x.status).sort()).toEqual(['conflict', 'saved']);
    233   expect(r.verified).toBe(true);
    234   expect(
    235     r.observed.row?.family === 'private_send_operation' &&
    236       r.observed.row.receipts
    237   ).toHaveLength(1);
    238   expect(r.remaining.status).toBe('accepted');
    239   const events = frames.filter((f) => f[0] === 'EVENT');
    240   expect(events).toHaveLength(1);
    241   const row = r.observed.row;
    242   if (!row || row.family !== 'private_send_operation')
    243     throw Error('missing winning row');
    244   const winner = row.receipts![0].role;
    245   expect(JSON.stringify(events[0][1])).toBe(
    246     winner === 'peer' ? row.self.wire : row.peerArtifact!.wire
    247   );
    248 });
    249 test('native put request followed by actual abort never acknowledges a receipt', async ({
    250   page
    251 }) => {
    252   const r = await page.evaluate(async () => {
    253     const f = window.hcp086Fixture,
    254       before = await f.state();
    255     f.failAfterPut('abort');
    256     const saved = await f.observe('peer', 'accepted');
    257     const faults = f.faults();
    258     f.clearFault();
    259     return { before, saved, faults, after: await f.state() };
    260   });
    261   expect(r.faults).toBe(1);
    262   expect(r.saved.status).toBe('aborted');
    263   expect(r.after.wire).toBe(r.before.wire);
    264 });
    265 test('failed actual post-put readback preserves uncertainty and cannot renew effect custody', async ({
    266   page
    267 }) => {
    268   const r = await page.evaluate(async () => {
    269     const f = window.hcp086Fixture;
    270     f.failAfterPut('readback');
    271     const saved = await f.observe('peer', 'accepted'),
    272       faults = f.faults();
    273     f.clearFault();
    274     return {
    275       saved,
    276       faults,
    277       verified: await f.verified(),
    278       state: await f.state(),
    279       attempt: await f.deliver('self_archive')
    280     };
    281   });
    282   expect(r.faults).toBe(1);
    283   expect(r.saved.status).toBe('unknown_completion');
    284   expect(r.verified).toBe(false);
    285   expect(
    286     r.state.row?.family === 'private_send_operation' && r.state.row.receipts
    287   ).toHaveLength(1);
    288   expect(r.attempt.status).toBe('stopped');
    289   expect(frames).toEqual([]);
    290 });
    291 test('reload retains named receipt uncertainty as local evidence without sender presence', async ({
    292   page
    293 }) => {
    294   const identity = await page.evaluate(async () => {
    295     const f = window.hcp086Fixture;
    296     await f.observe('peer', 'unknown');
    297     return { owner: f.owner, id: f.id };
    298   });
    299   await load(page);
    300   const state = await page.evaluate(
    301     ({ owner, id }) => window.hcp086.readExisting(owner, id),
    302     identity
    303   );
    304   expect(state.status?.recipient.state).toBe('unknown');
    305   expect(
    306     state.row?.family === 'private_send_operation' &&
    307       state.row.receipts?.[0].status
    308   ).toBe('unknown');
    309   expect(frames).toEqual([]);
    310 });
    311 test('forged pair acknowledgment cannot append a fact or mint a successor', async ({
    312   page
    313 }) => {
    314   const r = await page.evaluate(async () => {
    315     const f = window.hcp086Fixture,
    316       before = await f.state();
    317     return { before, saved: await f.forged(), after: await f.state() };
    318   });
    319   expect(r.saved.status).toBe('invalid');
    320   expect(r.after.wire).toBe(r.before.wire);
    321   expect(frames).toEqual([]);
    322 });
    323 test('private receipt storage never contains the composer marker or plaintext fields', async ({
    324   page
    325 }) => {
    326   const r = await page.evaluate(async () => {
    327     const f = window.hcp086Fixture;
    328     await f.observe('self_archive', 'unknown');
    329     return { marker: f.marker, state: await f.state() };
    330   });
    331   expect(r.state.wire).not.toContain(r.marker);
    332   expect(Object.keys(r.state.row ?? {})).not.toContain('body');
    333   expect(JSON.stringify(r.state.status)).not.toMatch(
    334     /Delivered|Seen|Order accepted|Reserved/
    335   );
    336   expect(frames).toEqual([]);
    337 });
    338 test('unrecognized record revision remains fenced after a genuine receipt successor', async ({
    339   page
    340 }) => {
    341   const r = await page.evaluate(async () => {
    342     const f = window.hcp086Fixture;
    343     await f.observe('peer', 'accepted');
    344     await f.changePairRevision();
    345     return {
    346       verified: await f.verified(),
    347       attempt: await f.deliver('self_archive')
    348     };
    349   });
    350   expect(r.verified).toBe(false);
    351   expect(r.attempt.status).toBe('stopped');
    352   expect(frames).toEqual([]);
    353 });