app

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

inbox-ingress.spec.ts (10080B)


      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/inbox-ingress.ts';
      8 declare global {
      9   interface Window {
     10     hcp090: typeof Fixture;
     11     hcp090Fixture: 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 requests: unknown[][] = [],
     19   frames: Record<string, unknown>[] = [];
     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       if (frame[0] !== 'REQ') return;
     41       requests.push(frame);
     42       for (const event of frames)
     43         socket.send(JSON.stringify(['EVENT', frame[1], event]));
     44       socket.send(JSON.stringify(['EOSE', frame[1]]));
     45     })
     46   );
     47   const result = await build({
     48     configFile: false,
     49     logLevel: 'silent',
     50     build: {
     51       write: false,
     52       minify: false,
     53       lib: {
     54         entry: fileURLToPath(
     55           new URL('./harness/inbox-ingress.ts', import.meta.url)
     56         ),
     57         name: 'hcp090',
     58         formats: ['iife']
     59       }
     60     }
     61   });
     62   const output = Array.isArray(result) ? result[0] : result;
     63   if (!('output' in output)) throw Error('bundle unavailable');
     64   const chunks = output.output.filter((x) => x.type === 'chunk');
     65   expect(chunks).toHaveLength(1);
     66   bundle = chunks[0].code;
     67 });
     68 test.afterAll(async () => {
     69   for (const socket of sockets.clients) socket.terminate();
     70   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     71   await server.close();
     72 });
     73 test.beforeEach(async ({ page }) => {
     74   requests = [];
     75   frames = [];
     76   await page.addInitScript(
     77     ({ endpoint }) => {
     78       const Native = window.WebSocket;
     79       window.WebSocket = class extends Native {
     80         constructor(url: string | URL, protocols?: string | string[]) {
     81           const origin = new URL(String(url)).origin;
     82           if (origin !== 'wss://archive.example.org')
     83             throw Error('unapproved receive destination');
     84           super(endpoint, protocols);
     85         }
     86       };
     87     },
     88     { endpoint }
     89   );
     90   await page.goto(server.url + '/search');
     91   await page.addScriptTag({ content: bundle });
     92   await page.evaluate(async () => {
     93     window.hcp090Fixture = await window.hcp090.makeFixture();
     94   });
     95 });
     96 test.afterEach(async ({ page }) => {
     97   if (!page.isClosed())
     98     await page.evaluate(() => window.hcp090Fixture?.close());
     99 });
    100 test('explicit own inbox receive persists signed outer before decrypt and keeps it out of catalog', async ({
    101   page
    102 }) => {
    103   const before = await page.evaluate(() => ({
    104     wire: window.hcp090Fixture.outer,
    105     owner: window.hcp090Fixture.owner,
    106     counts: window.hcp090Fixture.countsValue()
    107   }));
    108   frames = [JSON.parse(before.wire) as Record<string, unknown>];
    109   const capture = await page.evaluate(() => window.hcp090Fixture.capture());
    110   expect(capture).toBe(true);
    111   expect(requests).toEqual([]);
    112   expect(await page.evaluate(() => window.hcp090Fixture.start())).toBe(true);
    113   await expect
    114     .poll(() =>
    115       page.evaluate(async () => !!(await window.hcp090Fixture.stored()))
    116     )
    117     .toBe(true);
    118   const r = await page.evaluate(async () => ({
    119     row: await window.hcp090Fixture.stored(),
    120     counts: window.hcp090Fixture.countsValue(),
    121     catalog: window.hcp090Fixture.publicContains(),
    122     snapshot: window.hcp090Fixture.snapshot()
    123   }));
    124   expect(r.row).toMatchObject({
    125     family: 'received_envelope',
    126     owner: before.owner,
    127     outer: before.wire,
    128     read: null
    129   });
    130   expect(r.catalog).toBe(false);
    131   expect(r.counts.encrypts).toBe(before.counts.encrypts);
    132   expect(r.counts.decrypts).toBe(before.counts.decrypts);
    133   expect(r.counts.signs).toBe(before.counts.signs);
    134   expect(requests).toHaveLength(1);
    135   expect(requests[0][2]).toMatchObject({
    136     kinds: [1059],
    137     '#p': [before.owner],
    138     limit: 200
    139   });
    140 });
    141 test('a bad signature is isolated and the following valid outer remains retainable', async ({
    142   page
    143 }) => {
    144   const wire = await page.evaluate(() => window.hcp090Fixture.outer);
    145   const valid = JSON.parse(wire) as Record<string, unknown>;
    146   frames = [{ ...valid, sig: '0'.repeat(128) }, valid];
    147   expect(await page.evaluate(() => window.hcp090Fixture.capture())).toBe(true);
    148   await page.evaluate(() => window.hcp090Fixture.start());
    149   await expect
    150     .poll(() =>
    151       page.evaluate(async () => !!(await window.hcp090Fixture.stored()))
    152     )
    153     .toBe(true);
    154   expect(await page.evaluate(() => window.hcp090Fixture.publicContains())).toBe(
    155     false
    156   );
    157 });
    158 test('duplicate candidates charge ingress before ciphertext retention dedup', async ({
    159   page
    160 }) => {
    161   const wire = await page.evaluate(() => window.hcp090Fixture.outer);
    162   const event = JSON.parse(wire) as Record<string, unknown>;
    163   frames = [event, event, event];
    164   await page.evaluate(() => {
    165     window.hcp090Fixture.capture();
    166     window.hcp090Fixture.start();
    167   });
    168   await expect
    169     .poll(() =>
    170       page.evaluate(() => window.hcp090Fixture.snapshot()?.candidates)
    171     )
    172     .toBe(3);
    173   await expect
    174     .poll(() =>
    175       page.evaluate(() => window.hcp090Fixture.snapshot()?.duplicates)
    176     )
    177     .toBe(2);
    178   expect(await page.evaluate(() => window.hcp090Fixture.publicContains())).toBe(
    179     false
    180   );
    181 });
    182 test('absent exercised access or wrong review cannot start private receive', async ({
    183   page
    184 }) => {
    185   const r = await page.evaluate(() => ({
    186     without: window.hcp090Fixture.capture(false),
    187     wrong: window.hcp090Fixture.capture(true, 'unreviewed'),
    188     started: window.hcp090Fixture.start()
    189   }));
    190   expect(r).toEqual({ without: false, wrong: false, started: false });
    191   expect(requests).toEqual([]);
    192 });
    193 test('Stop before start prevents REQ and retention', async ({ page }) => {
    194   const result = await page.evaluate(() => {
    195     const f = window.hcp090Fixture;
    196     f.capture();
    197     f.stop();
    198     return { start: f.start(), snapshot: f.snapshot() };
    199   });
    200   expect(result.start).toBe(false);
    201   expect(result.snapshot).toMatchObject({
    202     state: 'stopped',
    203     retained: 0,
    204     candidates: 0
    205   });
    206   expect(requests).toEqual([]);
    207 });
    208 test('revoked actual access between capture and start prevents REQ', async ({
    209   page
    210 }) => {
    211   expect(
    212     await page.evaluate(() => {
    213       const f = window.hcp090Fixture;
    214       f.capture();
    215       f.revokeAccess();
    216       return f.start();
    217     })
    218   ).toBe(false);
    219   expect(requests).toEqual([]);
    220 });
    221 test('logout after capture fences start and closes the admitted private lifecycle', async ({
    222   page
    223 }) => {
    224   const result = await page.evaluate(() => {
    225     const f = window.hcp090Fixture;
    226     f.capture();
    227     f.logout();
    228     return { start: f.start(), snapshot: f.snapshot() };
    229   });
    230   expect(result.start).toBe(false);
    231   expect(result.snapshot?.state).toBe('stopped');
    232   expect(requests).toEqual([]);
    233 });
    234 test('duplicate flood is charged before dedup and stops at the fixed 500-candidate budget', async ({
    235   page
    236 }) => {
    237   const wire = await page.evaluate(() => window.hcp090Fixture.outer);
    238   frames = Array.from(
    239     { length: 501 },
    240     () => JSON.parse(wire) as Record<string, unknown>
    241   );
    242   await page.evaluate(() => {
    243     window.hcp090Fixture.capture();
    244     window.hcp090Fixture.start();
    245   });
    246   await expect
    247     .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.pending))
    248     .toBe(0);
    249   await expect
    250     .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.reason))
    251     .toBe('budget');
    252   const snapshot = await page.evaluate(() => window.hcp090Fixture.snapshot());
    253   expect(snapshot?.candidates).toBe(500);
    254   expect(requests).toHaveLength(1);
    255   expect(await page.evaluate(() => window.hcp090Fixture.publicContains())).toBe(
    256     false
    257   );
    258 });
    259 test('actual received-envelope transaction abort cannot report retained ciphertext', async ({
    260   page
    261 }) => {
    262   frames = [
    263     JSON.parse(await page.evaluate(() => window.hcp090Fixture.outer)) as Record<
    264       string,
    265       unknown
    266     >
    267   ];
    268   await page.evaluate(() => {
    269     const f = window.hcp090Fixture;
    270     f.faultRetention('abort');
    271     f.capture();
    272     f.start();
    273   });
    274   await expect
    275     .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.state))
    276     .toBe('needs_action');
    277   const result = await page.evaluate(async () => {
    278     const f = window.hcp090Fixture;
    279     f.restoreFault();
    280     return { snapshot: f.snapshot(), row: await f.stored() };
    281   });
    282   expect(result.snapshot).toMatchObject({ retained: 0, reason: 'aborted' });
    283   expect(result.row).toBeUndefined();
    284 });
    285 test('actual post-put readback failure stays uncertain despite durable ciphertext', async ({
    286   page
    287 }) => {
    288   frames = [
    289     JSON.parse(await page.evaluate(() => window.hcp090Fixture.outer)) as Record<
    290       string,
    291       unknown
    292     >
    293   ];
    294   await page.evaluate(() => {
    295     const f = window.hcp090Fixture;
    296     f.faultRetention('readback');
    297     f.capture();
    298     f.start();
    299   });
    300   await expect
    301     .poll(() => page.evaluate(() => window.hcp090Fixture.snapshot()?.state))
    302     .toBe('needs_action');
    303   const result = await page.evaluate(async () => {
    304     const f = window.hcp090Fixture;
    305     f.restoreFault();
    306     return { snapshot: f.snapshot(), row: await f.stored() };
    307   });
    308   expect(result.snapshot).toMatchObject({
    309     retained: 0,
    310     reason: 'unknown_completion'
    311   });
    312   expect(result.row).toMatchObject({ family: 'received_envelope', read: null });
    313 });