app

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

retry-listing.spec.ts (19681B)


      1 import { expect, test } 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/retry-listing.ts';
      8 declare global {
      9   interface Window {
     10     hcp113: typeof Fixture;
     11     hcp113Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     12     hcp113Resume: Awaited<ReturnType<typeof Fixture.openResumeFixture>>;
     13   }
     14 }
     15 const first = 'wss://discovery.example.org',
     16   second = 'wss://second.example.org';
     17 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     18   sockets: WebSocketServer,
     19   bundle: string,
     20   endpoint: string;
     21 let frames: { origin: string; message: unknown[] }[] = [];
     22 let stored: Record<string, unknown> | undefined;
     23 let responses = new Map<
     24   string,
     25   'accepted' | 'refused' | 'literal-timeout' | 'silent' | 'held'
     26 >();
     27 let holdReadback = false;
     28 test.beforeAll(async () => {
     29   server = await createStaticHarness();
     30   sockets = new WebSocketServer({
     31     host: '127.0.0.1',
     32     port: 0,
     33     maxPayload: 262144
     34   });
     35   await once(sockets, 'listening');
     36   const address = sockets.address();
     37   if (!address || typeof address === 'string')
     38     throw Error('loopback unavailable');
     39   endpoint = 'ws://127.0.0.1:' + address.port;
     40   sockets.on('connection', (socket, request) => {
     41     const origin = request.url === '/b' ? second : first;
     42     socket.on('message', (bytes) => {
     43       const raw = Buffer.isBuffer(bytes)
     44         ? bytes.toString()
     45         : Array.isArray(bytes)
     46           ? Buffer.concat(bytes).toString()
     47           : Buffer.from(bytes).toString();
     48       const message = JSON.parse(raw) as unknown[];
     49       frames.push({ origin, message });
     50       if (message[0] === 'EVENT') {
     51         stored = message[1] as Record<string, unknown>;
     52         const response = responses.get(origin) ?? 'accepted';
     53         if (response === 'held' || response === 'silent') return;
     54         socket.send(
     55           JSON.stringify([
     56             'OK',
     57             stored.id,
     58             response === 'accepted',
     59             response === 'accepted'
     60               ? ''
     61               : response === 'literal-timeout'
     62                 ? 'Timeout'
     63                 : 'blocked: controlled refusal'
     64           ])
     65         );
     66       } else if (message[0] === 'REQ' && !holdReadback) {
     67         if (stored && responses.get(origin) !== 'silent')
     68           socket.send(JSON.stringify(['EVENT', message[1], stored]));
     69         socket.send(JSON.stringify(['EOSE', message[1]]));
     70       }
     71     });
     72   });
     73   const built = await build({
     74     configFile: false,
     75     logLevel: 'silent',
     76     build: {
     77       write: false,
     78       minify: false,
     79       lib: {
     80         entry: fileURLToPath(
     81           new URL('./harness/retry-listing.ts', import.meta.url)
     82         ),
     83         name: 'hcp113',
     84         formats: ['iife']
     85       }
     86     }
     87   });
     88   const output = Array.isArray(built) ? built[0] : built;
     89   if (!('output' in output)) throw Error('bundle unavailable');
     90   const chunks = output.output.filter((row) => row.type === 'chunk');
     91   expect(chunks).toHaveLength(1);
     92   bundle = chunks[0].code;
     93 });
     94 test.afterAll(async () => {
     95   for (const socket of sockets.clients) socket.terminate();
     96   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     97   await server.close();
     98 });
     99 test.beforeEach(async ({ page }) => {
    100   frames = [];
    101   stored = undefined;
    102   responses = new Map();
    103   holdReadback = false;
    104   await page.addInitScript(
    105     ({ endpoint }) => {
    106       const Native = window.WebSocket;
    107       class LoopbackSocket extends Native {
    108         constructor(url: string | URL, protocols?: string | string[]) {
    109           const role =
    110             String(url) === 'wss://discovery.example.org/'
    111               ? '/a'
    112               : String(url) === 'wss://second.example.org/'
    113                 ? '/b'
    114                 : undefined;
    115           if (!role) throw Error('unfrozen controlled target');
    116           super(endpoint + role, protocols);
    117         }
    118       }
    119       window.WebSocket = LoopbackSocket;
    120     },
    121     { endpoint }
    122   );
    123   await page.goto(server.url + '/search');
    124   await page.addScriptTag({ content: bundle });
    125   await page.evaluate(async () => {
    126     window.hcp113Fixture = await window.hcp113.createFixture(true);
    127   });
    128 });
    129 test.afterEach(async ({ page }) => {
    130   if (!page.isClosed())
    131     await page.evaluate(() => {
    132       window.hcp113Resume?.close();
    133       window.hcp113Fixture?.close();
    134     });
    135 });
    136 async function restart(page: import('@playwright/test').Page, changed = false) {
    137   const details = await page.evaluate(() => window.hcp113Fixture.details());
    138   await page.evaluate(() => window.hcp113Fixture.close());
    139   await page.reload();
    140   await page.addScriptTag({ content: bundle });
    141   await page.evaluate(
    142     async ({ owner, command, changed }) => {
    143       window.hcp113Resume = await window.hcp113.openResumeFixture(
    144         owner,
    145         command,
    146         true,
    147         changed
    148       );
    149     },
    150     { owner: details.row.owner, command: details.row.id, changed }
    151   );
    152   return details;
    153 }
    154 // Additional post-producer regressions; these receive no initial RED credit.
    155 test('HCP113 genuine original explicit retry uses one stored signature and a second reviewed action skips independently verified targets', async ({
    156   page
    157 }) => {
    158   const original = await page.evaluate(() => window.hcp113Fixture.details());
    159   expect(await page.evaluate(() => window.hcp113Fixture.start())).toBe(true);
    160   expect(await page.evaluate(() => window.hcp113Fixture.result())).toEqual({
    161     status: 'completed'
    162   });
    163   expect(frames.filter(({ message }) => message[0] === 'EVENT')).toHaveLength(
    164     2
    165   );
    166   const delivered = await page.evaluate(() => window.hcp113Fixture.details());
    167   expect(delivered.row.artifact).toEqual(original.row.artifact);
    168   expect(delivered.row.capture).toEqual(original.row.capture);
    169   expect(delivered.signs).toBe(1);
    170   expect(await page.evaluate(() => window.hcp113Fixture.start())).toBe(true);
    171   expect(await page.evaluate(() => window.hcp113Fixture.result())).toEqual({
    172     status: 'completed'
    173   });
    174   expect(frames.filter(({ message }) => message[0] === 'EVENT')).toHaveLength(
    175     2
    176   );
    177 });
    178 test('HCP113 actual forty-five-second action window stops before another target without changing host verification limits', async ({
    179   page
    180 }) => {
    181   const original = await restart(page);
    182   holdReadback = true;
    183   const started = performance.now();
    184   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    185     'started'
    186   );
    187   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    188     status: 'needs_action'
    189   });
    190   expect(performance.now() - started).toBeGreaterThanOrEqual(44000);
    191   expect(frames.filter(({ message }) => message[0] === 'EVENT')).toHaveLength(
    192     1
    193   );
    194   expect(frames.some(({ origin }) => origin === second)).toBe(false);
    195   const retained = await page.evaluate(() => window.hcp113Resume.details());
    196   expect(retained.row.artifact).toEqual(original.row.artifact);
    197   expect(retained.row.capture).toEqual(original.row.capture);
    198   expect(retained.row.receipts.some((fact) => fact.status === 'accepted')).toBe(
    199     true
    200   );
    201   expect(retained.signs).toBe(0);
    202 });
    203 test('HCP113 Stop during the last target readback remains stopped while accepted remote evidence survives', async ({
    204   page
    205 }) => {
    206   await page.evaluate(() => window.hcp113Fixture.close());
    207   await page.reload();
    208   await page.addScriptTag({ content: bundle });
    209   await page.evaluate(async () => {
    210     window.hcp113Fixture = await window.hcp113.createFixture(false);
    211   });
    212   const original = await page.evaluate(() => window.hcp113Fixture.details());
    213   await page.evaluate(() => window.hcp113Fixture.close());
    214   await page.reload();
    215   await page.addScriptTag({ content: bundle });
    216   await page.evaluate(
    217     async ({ owner, command }) => {
    218       window.hcp113Resume = await window.hcp113.openResumeFixture(
    219         owner,
    220         command,
    221         false
    222       );
    223     },
    224     { owner: original.row.owner, command: original.row.id }
    225   );
    226   holdReadback = true;
    227   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    228     'started'
    229   );
    230   await expect
    231     .poll(() => frames.filter(({ message }) => message[0] === 'REQ').length)
    232     .toBeGreaterThan(0);
    233   await page.evaluate(() => window.hcp113Resume.stop());
    234   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    235     status: 'stopped'
    236   });
    237   const retained = await page.evaluate(() => window.hcp113Resume.details());
    238   expect(retained.row.receipts.some((fact) => fact.status === 'accepted')).toBe(
    239     true
    240   );
    241   expect(retained.signs).toBe(0);
    242   expect(frames.filter(({ message }) => message[0] === 'EVENT')).toHaveLength(
    243     1
    244   );
    245 });
    246 test('HCP113 actual page restart and explicit Resume deliver the same acknowledged signed artifact without any new signature', async ({
    247   page
    248 }) => {
    249   const original = await restart(page);
    250   frames = [];
    251   expect(
    252     await page.evaluate(() => window.hcp113Resume.preview())
    253   ).toBeDefined();
    254   expect(frames).toHaveLength(0);
    255   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    256     'started'
    257   );
    258   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    259     status: 'completed'
    260   });
    261   const current = await page.evaluate(() => window.hcp113Resume.details());
    262   expect(original.signs).toBe(1);
    263   expect(current.signs).toBe(0);
    264   expect(current.row.id).toBe(original.row.id);
    265   expect(current.row.capture).toEqual(original.row.capture);
    266   expect(current.row.artifact).toEqual(original.row.artifact);
    267   const events = frames.filter((f) => f.message[0] === 'EVENT');
    268   expect(events.map((f) => f.origin)).toEqual([first, second]);
    269   for (const event of events)
    270     expect(JSON.stringify(event.message[1])).toBe(original.row.artifact!.wire);
    271 });
    272 test('HCP113 independently retained accepted first target is never republished when explicit reopened resume retries refused second target', async ({
    273   page
    274 }) => {
    275   responses.set(second, 'refused');
    276   expect(await page.evaluate(() => window.hcp113Fixture.start())).toBe(true);
    277   expect(await page.evaluate(() => window.hcp113Fixture.result())).toEqual({
    278     status: 'needs_action'
    279   });
    280   const original = await restart(page);
    281   expect(
    282     original.row.receipts.some(
    283       (f) => f.origin === first && f.status === 'accepted'
    284     )
    285   ).toBe(true);
    286   responses.set(second, 'accepted');
    287   frames = [];
    288   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    289     'started'
    290   );
    291   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    292     status: 'completed'
    293   });
    294   expect(
    295     frames.filter((f) => f.message[0] === 'EVENT').map((f) => f.origin)
    296   ).toEqual([second]);
    297   const now = await page.evaluate(() => window.hcp113Resume.details());
    298   expect(now.signs).toBe(0);
    299   expect(now.row.artifact).toEqual(original.row.artifact);
    300   expect(now.row.capture).toEqual(original.row.capture);
    301 });
    302 test('HCP113 changed qualified configuration never silently retargets original capture on explicit Resume', async ({
    303   page
    304 }) => {
    305   const original = await restart(page, true);
    306   frames = [];
    307   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    308     'needs_action'
    309   );
    310   expect(frames).toHaveLength(0);
    311   const now = await page.evaluate(() => window.hcp113Resume.details());
    312   expect(now.row).toEqual(original.row);
    313   expect(now.signs).toBe(0);
    314 });
    315 test('HCP113 fresh changed actual extension owner cannot resume a retained author command', async ({
    316   page
    317 }) => {
    318   const original = await restart(page);
    319   await page.evaluate(() => window.hcp113Resume.changeKey());
    320   frames = [];
    321   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    322     'needs_action'
    323   );
    324   expect(frames).toHaveLength(0);
    325   const now = await page.evaluate(() => window.hcp113Resume.details());
    326   expect(now.row).toEqual(original.row);
    327   expect(now.signs).toBe(0);
    328 });
    329 test('HCP113 reopening and review or wrong consent never automatically publishes', async ({
    330   page
    331 }) => {
    332   const original = await restart(page);
    333   frames = [];
    334   await page.evaluate(() => window.hcp113Resume.preview());
    335   expect(
    336     await page.evaluate(() => window.hcp113Resume.start('wrong_consent'))
    337   ).toBe('invalid');
    338   expect(frames).toHaveLength(0);
    339   expect(
    340     (await page.evaluate(() => window.hcp113Resume.details())).row
    341   ).toEqual(original.row);
    342 });
    343 test('HCP113 operation-local Stop during actual held EVENT preserves uncertainty and prevents dependent readback or another target', async ({
    344   page
    345 }) => {
    346   await restart(page);
    347   responses.set(first, 'held');
    348   frames = [];
    349   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    350     'started'
    351   );
    352   await expect
    353     .poll(() => frames.filter((f) => f.message[0] === 'EVENT').length)
    354     .toBe(1);
    355   await page.evaluate(() => window.hcp113Resume.stop());
    356   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    357     status: 'stopped'
    358   });
    359   expect(frames.filter((f) => f.message[0] === 'REQ')).toHaveLength(0);
    360   expect(frames.filter((f) => f.origin === second)).toHaveLength(0);
    361   const d = await page.evaluate(() => window.hcp113Resume.details());
    362   expect(d.row.receipts.map((f) => f.status)).toEqual(['stopped']);
    363   expect(d.signs).toBe(0);
    364   expect(d.row.artifact).not.toBeNull();
    365 });
    366 test('HCP113 copied Stop control cannot cancel the genuine action or erase native accepted evidence', async ({
    367   page
    368 }) => {
    369   await restart(page);
    370   holdReadback = true;
    371   frames = [];
    372   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    373     'started'
    374   );
    375   await expect
    376     .poll(() => frames.filter((f) => f.message[0] === 'REQ').length)
    377     .toBe(1);
    378   await page.evaluate(() => window.hcp113Resume.copiedStop());
    379   await page.waitForTimeout(100);
    380   expect(
    381     (await page.evaluate(() => window.hcp113Resume.details())).completed
    382   ).toBe(false);
    383   const before = await page.evaluate(() => window.hcp113Resume.details());
    384   expect(before.row.receipts.some((f) => f.status === 'accepted')).toBe(true);
    385   await page.evaluate(() => window.hcp113Resume.stop());
    386   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    387     status: 'stopped'
    388   });
    389   const after = await page.evaluate(() => window.hcp113Resume.details());
    390   expect(after.row.receipts.some((f) => f.status === 'accepted')).toBe(true);
    391   expect(after.row.artifact).toEqual(before.row.artifact);
    392   expect(after.signs).toBe(0);
    393   expect(frames.filter((f) => f.message[0] === 'EVENT')).toHaveLength(1);
    394 });
    395 test('HCP113 original Stop while the final actual key query is held prevents any EVENT after the provider settles', async ({
    396   page
    397 }) => {
    398   await restart(page);
    399   frames = [];
    400   expect(
    401     await page.evaluate(() =>
    402       window.hcp113Resume.start('resume_stored_listing', true)
    403     )
    404   ).toBe('started');
    405   await expect
    406     .poll(() =>
    407       page.evaluate(async () => (await window.hcp113Resume.details()).heldKeys)
    408     )
    409     .toBeGreaterThan(0);
    410   await page.evaluate(() => window.hcp113Resume.stop());
    411   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    412     status: 'stopped'
    413   });
    414   await page.evaluate(() => window.hcp113Resume.releaseKey());
    415   expect(frames).toHaveLength(0);
    416   expect(
    417     (await page.evaluate(() => window.hcp113Resume.details())).row.receipts
    418   ).toHaveLength(0);
    419 });
    420 test('HCP113 Stop before a held real native readonly completion acknowledgement settles stays stopped without later effects', async ({
    421   page
    422 }) => {
    423   const original = await restart(page);
    424   expect(
    425     await page.evaluate(() =>
    426       window.hcp113Resume.start('resume_stored_listing', false, true)
    427     )
    428   ).toBe('started');
    429   await expect
    430     .poll(() => page.evaluate(() => window.hcp113Resume.heldReadCount()))
    431     .toBe(1);
    432   expect(frames).toHaveLength(0);
    433   await page.evaluate(() => window.hcp113Resume.stop());
    434   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    435     status: 'stopped'
    436   });
    437   await page.evaluate(() => window.hcp113Resume.releaseRead());
    438   const retained = await page.evaluate(() => window.hcp113Resume.details());
    439   expect(retained.row).toEqual(original.row);
    440   expect(retained.signs).toBe(0);
    441   expect(frames).toHaveLength(0);
    442 });
    443 for (const response of ['refused', 'literal-timeout'] as const)
    444   test(
    445     'HCP113 actual ' +
    446       response +
    447       ' requires another explicit action without spin or signing',
    448     async ({ page }) => {
    449       await restart(page);
    450       responses.set(first, response);
    451       frames = [];
    452       expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    453         'started'
    454       );
    455       expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    456         status: 'needs_action'
    457       });
    458       expect(frames.filter((f) => f.message[0] === 'EVENT')).toHaveLength(1);
    459       expect(frames.filter((f) => f.message[0] === 'REQ')).toHaveLength(0);
    460       const d = await page.evaluate(() => window.hcp113Resume.details());
    461       expect(d.row.receipts[0].status).toBe(
    462         response === 'refused' ? 'refused' : 'unknown'
    463       );
    464       expect(d.signs).toBe(0);
    465     }
    466   );
    467 test('HCP113 actual resumed silent relay action retains at most three original-wire attempts and never creates a new listing', async ({
    468   page
    469 }) => {
    470   const original = await restart(page);
    471   responses.set(first, 'silent');
    472   frames = [];
    473   expect(await page.evaluate(() => window.hcp113Resume.start())).toBe(
    474     'started'
    475   );
    476   expect(await page.evaluate(() => window.hcp113Resume.result())).toEqual({
    477     status: 'needs_action'
    478   });
    479   const d = await page.evaluate(() => window.hcp113Resume.details());
    480   expect(
    481     d.row.receipts.filter((f) => f.status === 'timed_out').map((f) => f.attempt)
    482   ).toEqual([1, 2, 3]);
    483   expect(new Set(d.row.receipts.map((f) => f.actionId)).size).toBe(1);
    484   expect(frames.filter((f) => f.message[0] === 'EVENT')).toHaveLength(3);
    485   expect(d.row.artifact).toEqual(original.row.artifact);
    486   expect(d.signs).toBe(0);
    487 });
    488 test('HCP113 actual local receipt abort requires action and preserves the signed artifact without an automatic second EVENT', async ({
    489   page
    490 }) => {
    491   const original = await restart(page);
    492   frames = [];
    493   const d = await page.evaluate(async () => {
    494     const descriptor = Object.getOwnPropertyDescriptor(
    495       IDBObjectStore.prototype,
    496       'put'
    497     );
    498     if (!descriptor) throw Error('native put missing');
    499     const native = descriptor.value as IDBObjectStore['put'];
    500     Object.defineProperty(IDBObjectStore.prototype, 'put', {
    501       ...descriptor,
    502       value: function (
    503         this: IDBObjectStore,
    504         ...args: Parameters<IDBObjectStore['put']>
    505       ) {
    506         if (this.name === 'public_operations') {
    507           this.transaction.abort();
    508           throw new DOMException(
    509             'HC_TEST_ONLY controlled put refusal followed real native abort',
    510             'QuotaExceededError'
    511           );
    512         }
    513         return native.apply(this, args);
    514       }
    515     });
    516     try {
    517       const started = await window.hcp113Resume.start(),
    518         result = await window.hcp113Resume.result(),
    519         details = await window.hcp113Resume.details();
    520       return { started, result, details };
    521     } finally {
    522       Object.defineProperty(IDBObjectStore.prototype, 'put', descriptor);
    523     }
    524   });
    525   expect(d.started).toBe('started');
    526   expect(d.result).toEqual({ status: 'needs_action' });
    527   expect(d.details.row.artifact).toEqual(original.row.artifact);
    528   expect(d.details.row.receipts).toHaveLength(0);
    529   expect(d.details.signs).toBe(0);
    530   expect(frames.filter((f) => f.message[0] === 'EVENT')).toHaveLength(1);
    531   expect(frames.filter((f) => f.message[0] === 'REQ')).toHaveLength(0);
    532 });