app

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

message-recovery.spec.ts (8847B)


      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 { createHash } from 'node:crypto';
      6 import { WebSocketServer } from 'ws';
      7 import { createStaticHarness } from '../integration/harness/static.ts';
      8 import type * as Fixture from './harness/resume-routing.ts';
      9 declare global {
     10   interface Window {
     11     hcp138: typeof Fixture;
     12     hcp138Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>;
     13   }
     14 }
     15 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     16   sockets: WebSocketServer,
     17   endpoint: string,
     18   bundle: string;
     19 let events: { origin: string; wire: string }[] = [];
     20 let rerouted = false;
     21 let silent = false;
     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('loopback unavailable');
     33   endpoint = 'ws://127.0.0.1:' + address.port;
     34   sockets.on('connection', (socket, request) =>
     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         frame = JSON.parse(raw.toString()) as unknown[];
     42       if (frame[0] !== 'EVENT') return;
     43       const event = frame[1] as { id: string };
     44       events.push({
     45         origin: new URL(request.url!, 'http://localhost').searchParams.get(
     46           'origin'
     47         )!,
     48         wire: JSON.stringify(event)
     49       });
     50       if (silent) return;
     51       const accepted =
     52         rerouted || events.at(-1)?.origin === 'wss://peer.example.org';
     53       socket.send(
     54         JSON.stringify([
     55           'OK',
     56           event.id,
     57           accepted,
     58           accepted ? '' : 'blocked: original archive refusal'
     59         ])
     60       );
     61     })
     62   );
     63   const result = await build({
     64     configFile: false,
     65     logLevel: 'silent',
     66     build: {
     67       write: false,
     68       minify: false,
     69       lib: {
     70         entry: fileURLToPath(
     71           new URL('./harness/resume-routing.ts', import.meta.url)
     72         ),
     73         name: 'hcp138',
     74         formats: ['iife']
     75       }
     76     }
     77   });
     78   const output = Array.isArray(result) ? result[0] : result;
     79   if (!('output' in output)) throw Error('bundle missing');
     80   const chunks = output.output.filter((x) => x.type === 'chunk');
     81   expect(chunks).toHaveLength(1);
     82   bundle = chunks[0].code;
     83   console.log(
     84     JSON.stringify({
     85       fixture: 'HCP138_ORIGINAL_ARCHIVE_REROUTE',
     86       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
     87       moduleIds: Object.keys(chunks[0].modules),
     88       qualification:
     89         'Actual original native IDB/SDK signed and encrypted fixed artifacts/loopback ACKs; controlled routing source port distinct from live host/relay/client qualification; write:false bundle bytes not separately retained.'
     90     })
     91   );
     92 });
     93 test.afterAll(async () => {
     94   for (const socket of sockets.clients) socket.terminate();
     95   await new Promise<void>((r) => sockets.close(() => r()));
     96   await server.close();
     97 });
     98 test.beforeEach(async ({ page }) => {
     99   events = [];
    100   rerouted = false;
    101   silent = false;
    102   await page.addInitScript(
    103     ({ endpoint }) => {
    104       const Native = window.WebSocket;
    105       window.WebSocket = class extends Native {
    106         constructor(url: string | URL, protocols?: string | string[]) {
    107           const origin = new URL(String(url)).origin;
    108           if (
    109             ![
    110               'wss://peer.example.org',
    111               'wss://archive.example.org',
    112               'wss://new-peer.example.org'
    113             ].includes(origin)
    114           )
    115             throw Error('unapproved destination');
    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   await page.evaluate(async () => {
    125     window.hcp138Fixture = await window.hcp138.makeFixture();
    126   });
    127 });
    128 test.afterEach(async ({ page }) => {
    129   if (!page.isClosed())
    130     await page.evaluate(() => window.hcp138Fixture?.close());
    131 });
    132 test('accepted peer copy survives explicit sender archive reroute with original self wire and immutable receipt history', async ({
    133   page
    134 }) => {
    135   const initial = await page.evaluate(async () => {
    136     const f = window.hcp138Fixture;
    137     const result = await f.retry(true),
    138       before = await f.row(),
    139       counts = f.counts();
    140     const captured = f.capture(
    141       'wss://peer.example.org',
    142       'wss://new-peer.example.org'
    143     );
    144     const snapshot = f.snapshot(),
    145       unreviewed = await f.approve('unreviewed');
    146     return {
    147       result,
    148       before,
    149       counts,
    150       captured,
    151       snapshot,
    152       unreviewed,
    153       untouched: await f.row()
    154     };
    155   });
    156   expect(initial.result.status).toBe('needs_action');
    157   expect(
    158     initial.before?.record.receipts?.map((r) => ({
    159       role: r.role,
    160       status: r.status
    161     }))
    162   ).toEqual([
    163     { role: 'peer', status: 'accepted' },
    164     { role: 'self_archive', status: 'refused' }
    165   ]);
    166   expect(initial.captured).toBe(true);
    167   expect(initial.snapshot?.changes.archive.removed).toEqual([
    168     'wss://archive.example.org'
    169   ]);
    170   expect(initial.unreviewed.status).toBe('invalid');
    171   expect(initial.untouched).toEqual(initial.before);
    172   expect(events.map((e) => e.origin)).toEqual([
    173     'wss://peer.example.org',
    174     'wss://archive.example.org'
    175   ]);
    176   rerouted = true;
    177   const final = await page.evaluate(async () => {
    178     const f = window.hcp138Fixture;
    179     const approved = await f.approve(),
    180       stale = await f.retry(true),
    181       retried = await f.retry();
    182     return {
    183       approved,
    184       stale,
    185       retried,
    186       after: await f.row(),
    187       counts: f.counts()
    188     };
    189   });
    190   expect(final.approved.status).toBe('updated');
    191   expect(final.stale.status).toBe('invalid');
    192   expect(final.retried.status).toBe('completed');
    193   expect(final.after?.record.self).toEqual(initial.before?.record.self);
    194   expect(final.after?.record.peerArtifact).toEqual(
    195     initial.before?.record.peerArtifact
    196   );
    197   expect(final.after?.record.receipts?.slice(0, 2)).toEqual(
    198     initial.before?.record.receipts
    199   );
    200   expect(final.after?.record.receipts).toHaveLength(3);
    201   expect(final.counts.encrypts).toBe(initial.counts.encrypts);
    202   expect(final.counts.signs).toBe(initial.counts.signs);
    203   expect(events.map((e) => e.origin)).toEqual([
    204     'wss://peer.example.org',
    205     'wss://archive.example.org',
    206     'wss://new-peer.example.org'
    207   ]);
    208   expect(events[0].wire).toBe(initial.before?.record.peerArtifact?.wire);
    209   expect(events[1].wire).toBe(initial.before?.record.self.wire);
    210   expect(events[2].wire).toBe(events[1].wire);
    211 });
    212 
    213 test('three actual silent attempts stop before archive publication without repeating crypto', async ({
    214   page
    215 }) => {
    216   silent = true;
    217   const before = await page.evaluate(async () => ({
    218     row: await window.hcp138Fixture.row(),
    219     counts: window.hcp138Fixture.counts()
    220   }));
    221   const started = process.hrtime.bigint();
    222   const result = await page.evaluate(() => window.hcp138Fixture.retry(true));
    223   const elapsedMilliseconds = Number(process.hrtime.bigint() - started) / 1e6;
    224   console.log(
    225     JSON.stringify({
    226       fixture: 'HCP138_REAL_SILENT_ATTEMPT_CAP',
    227       elapsedMilliseconds,
    228       eventCount: events.length,
    229       clock: 'native process monotonic; browser performance.now unchanged'
    230     })
    231   );
    232   expect(elapsedMilliseconds).toBeGreaterThanOrEqual(29_000);
    233   expect(result.status).toBe('needs_action');
    234   expect(events).toHaveLength(3);
    235   for (const event of events) {
    236     expect(event.origin).toBe('wss://peer.example.org');
    237     expect(event.wire).toBe(before.row?.record.peerArtifact?.wire);
    238   }
    239   const after = await page.evaluate(async () => ({
    240     row: await window.hcp138Fixture.row(),
    241     counts: window.hcp138Fixture.counts()
    242   }));
    243   expect(after.counts.encrypts).toBe(before.counts.encrypts);
    244   expect(after.counts.decrypts).toBe(before.counts.decrypts);
    245   expect(after.counts.signs).toBe(before.counts.signs);
    246   expect(after.counts.keys).toBe(before.counts.keys + 3);
    247   expect(after.row?.record.self).toEqual(before.row?.record.self);
    248   expect(after.row?.record.peerArtifact).toEqual(
    249     before.row?.record.peerArtifact
    250   );
    251   expect(
    252     after.row?.record.receipts?.some((receipt) => receipt.status === 'accepted')
    253   ).toBe(false);
    254   expect(
    255     after.row?.record.receipts?.map((receipt) => ({
    256       role: receipt.role,
    257       attempt: receipt.attempt,
    258       status: receipt.status
    259     }))
    260   ).toEqual([
    261     { role: 'peer', attempt: 1, status: 'timed_out' },
    262     { role: 'peer', attempt: 2, status: 'timed_out' },
    263     { role: 'peer', attempt: 3, status: 'timed_out' }
    264   ]);
    265 });