app

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

inbox-auth.spec.ts (18396B)


      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-auth.ts';
      8 declare global {
      9   interface Window {
     10     hcp068: typeof Fixture;
     11     hcp068Fixture: Awaited<ReturnType<typeof Fixture.makeAuthFixture>>;
     12     hcp068Action: NonNullable<
     13       Awaited<ReturnType<typeof Fixture.beginInboxAuthentication>>
     14     >;
     15     hcp068Run?: Promise<{ status: string }>;
     16     hcp068Settle?: () => void;
     17   }
     18 }
     19 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     20   sockets: WebSocketServer,
     21   endpoint: string,
     22   bundle: string;
     23 let frames: unknown[][] = [],
     24   accept = true,
     25   holdPage = false;
     26 test.beforeAll(async () => {
     27   server = await createStaticHarness();
     28   sockets = new WebSocketServer({
     29     host: '127.0.0.1',
     30     port: 0,
     31     maxPayload: 65536
     32   });
     33   await once(sockets, 'listening');
     34   const address = sockets.address();
     35   if (!address || typeof address === 'string')
     36     throw new Error('missing loopback');
     37   endpoint = 'ws://127.0.0.1:' + address.port;
     38   sockets.on('connection', (socket) => {
     39     socket.send(JSON.stringify(['AUTH', 'challenge-one']));
     40     socket.on('message', (bytes) => {
     41       const raw = Buffer.isBuffer(bytes)
     42         ? bytes
     43         : Array.isArray(bytes)
     44           ? Buffer.concat(bytes)
     45           : Buffer.from(bytes);
     46       const frame = JSON.parse(raw.toString()) as unknown[];
     47       frames.push(frame);
     48       if (frame[0] === 'AUTH')
     49         socket.send(
     50           JSON.stringify([
     51             'OK',
     52             (frame[1] as { id: string }).id,
     53             accept,
     54             accept ? '' : 'blocked: refusal'
     55           ])
     56         );
     57       if (frame[0] === 'REQ' && !holdPage)
     58         socket.send(JSON.stringify(['EOSE', frame[1]]));
     59     });
     60   });
     61   const result = await build({
     62     configFile: false,
     63     logLevel: 'silent',
     64     build: {
     65       write: false,
     66       minify: false,
     67       lib: {
     68         entry: fileURLToPath(
     69           new URL('./harness/inbox-auth.ts', import.meta.url)
     70         ),
     71         name: 'hcp068',
     72         formats: ['iife']
     73       }
     74     }
     75   });
     76   const output = Array.isArray(result) ? result[0] : result;
     77   if (!('output' in output)) throw new Error('missing bundle');
     78   const chunks = output.output.filter((x) => x.type === 'chunk');
     79   expect(chunks).toHaveLength(1);
     80   bundle = chunks[0].code;
     81 });
     82 test.afterAll(async () => {
     83   for (const socket of sockets.clients) socket.terminate();
     84   await new Promise<void>((resolve) => sockets.close(() => resolve()));
     85   await server.close();
     86 });
     87 test.beforeEach(async ({ page }) => {
     88   frames = [];
     89   accept = true;
     90   holdPage = false;
     91   await page.addInitScript(
     92     ({ endpoint }) => {
     93       const Native = window.WebSocket;
     94       window.WebSocket = class extends Native {
     95         constructor(url: string | URL, protocols?: string | string[]) {
     96           if (
     97             ![
     98               'wss://inbox.example.org/',
     99               'wss://discovery.example.org/'
    100             ].includes(String(url))
    101           )
    102             throw new Error('unexpected fixture destination');
    103           super(endpoint, protocols);
    104         }
    105       };
    106     },
    107     { endpoint }
    108   );
    109   await page.goto(server.url + '/search');
    110   await page.addScriptTag({ content: bundle });
    111   await page.evaluate(async () => {
    112     window.hcp068Fixture = await window.hcp068.makeAuthFixture();
    113     const action = await window.hcp068.beginInboxAuthentication(
    114       window.hcp068Fixture.pool,
    115       window.hcp068.inbox,
    116       'reviewed_connection_auth'
    117     );
    118     if (!action) throw new Error('missing AUTH action');
    119     window.hcp068Action = action;
    120   });
    121   await expect
    122     .poll(() =>
    123       page.evaluate(
    124         () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    125       )
    126     )
    127     .toBe('challenge');
    128 });
    129 test.afterEach(async ({ page }) => {
    130   if (!page.isClosed())
    131     await page.evaluate(() => {
    132       window.hcp068Settle?.();
    133       window.hcp068Fixture.close();
    134     });
    135 });
    136 test('genuine SDK connection waits without REQ or EVENT and exact signed22242 uses AUTH only', async ({
    137   page
    138 }) => {
    139   expect(frames).toHaveLength(0);
    140   const result = await page.evaluate(async () => ({
    141     result: await window.hcp068.respondInboxAuthentication(window.hcp068Action),
    142     owner: window.hcp068Fixture.owner,
    143     signs: window.hcp068Fixture.signs()
    144   }));
    145   expect(result.result.status).toBe('accepted');
    146   expect(result.signs).toBe(1);
    147   expect(frames).toHaveLength(1);
    148   expect(frames[0][0]).toBe('AUTH');
    149   expect(frames[0][1]).toMatchObject({
    150     kind: 22242,
    151     pubkey: result.owner,
    152     content: '',
    153     tags: [
    154       ['relay', 'wss://inbox.example.org/'],
    155       ['challenge', 'challenge-one']
    156     ]
    157   });
    158 });
    159 for (const mode of [
    160   'relay',
    161   'challenge',
    162   'author',
    163   'cached',
    164   'denied'
    165 ] as const)
    166   test(`actual provider ${mode} response never reaches AUTH`, async ({
    167     page
    168   }) => {
    169     const result = await page.evaluate(async (mode) => {
    170       window.hcp068Fixture.mode(mode);
    171       return window.hcp068.respondInboxAuthentication(window.hcp068Action);
    172     }, mode);
    173     expect(result.status).not.toBe('accepted');
    174     expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    175   });
    176 test('real refusal pauses without retry', async ({ page }) => {
    177   accept = false;
    178   expect(
    179     await page.evaluate(() =>
    180       window.hcp068.respondInboxAuthentication(window.hcp068Action)
    181     )
    182   ).toEqual({ status: 'refused' });
    183   await page.evaluate(() =>
    184     window.hcp068.respondInboxAuthentication(window.hcp068Action)
    185   );
    186   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(1);
    187 });
    188 test('two genuine changing challenges admit two responses and the third closes the scope', async ({
    189   page
    190 }) => {
    191   await page.evaluate(() =>
    192     window.hcp068.respondInboxAuthentication(window.hcp068Action)
    193   );
    194   for (const socket of sockets.clients)
    195     socket.send(JSON.stringify(['AUTH', 'challenge-two']));
    196   await expect
    197     .poll(() =>
    198       page.evaluate(
    199         () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    200       )
    201     )
    202     .toBe('challenge');
    203   await page.evaluate(() =>
    204     window.hcp068.respondInboxAuthentication(window.hcp068Action)
    205   );
    206   for (const socket of sockets.clients)
    207     socket.send(JSON.stringify(['AUTH', 'challenge-three']));
    208   await expect
    209     .poll(() =>
    210       page.evaluate(
    211         () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    212       )
    213     )
    214     .toBe('stopped');
    215   await page.evaluate(() =>
    216     window.hcp068.respondInboxAuthentication(window.hcp068Action)
    217   );
    218   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(2);
    219   expect(await page.evaluate(() => window.hcp068Fixture.signs())).toBe(2);
    220 });
    221 for (const stop of ['stop', 'logout', 'socket'] as const)
    222   test(`actual pending signer retains shared slot through ${stop} and cannot send late AUTH`, async ({
    223     page
    224   }) => {
    225     await page.evaluate(() => {
    226       window.hcp068Fixture.beforeSign(
    227         () =>
    228           new Promise<void>((resolve) => {
    229             window.hcp068Settle = resolve;
    230           })
    231       );
    232       window.hcp068Run = window.hcp068.respondInboxAuthentication(
    233         window.hcp068Action
    234       );
    235     });
    236     await expect
    237       .poll(() => page.evaluate(() => window.hcp068Fixture.signs()))
    238       .toBe(1);
    239     if (stop === 'socket') for (const socket of sockets.clients) socket.close();
    240     else
    241       await page.evaluate((stop) => {
    242         if (stop === 'logout') window.hcp068Fixture.logout();
    243         else window.hcp068.closeInboxAuthentication(window.hcp068Action);
    244       }, stop);
    245     await expect
    246       .poll(() =>
    247         page.evaluate(
    248           () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    249         )
    250       )
    251       .toBe('stopped');
    252     expect(
    253       await page.evaluate(
    254         () =>
    255           window.hcp068.extensionSchedulerSnapshot(
    256             window.hcp068.browserExtensionScheduler()!
    257           ).state
    258       )
    259     ).toBe('active');
    260     const result = await page.evaluate(async () => {
    261       window.hcp068Settle!();
    262       return window.hcp068Run;
    263     });
    264     expect(result?.status).not.toBe('accepted');
    265     expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    266     expect(
    267       await page.evaluate(
    268         () =>
    269           window.hcp068.extensionSchedulerSnapshot(
    270             window.hcp068.browserExtensionScheduler()!
    271           ).state
    272       )
    273     ).toBe('idle');
    274   });
    275 test('unsolicited public challenges never sign and public reads survive private Stop', async ({
    276   page
    277 }) => {
    278   const result = await page.evaluate(async () => {
    279     const s = window.hcp068,
    280       f = window.hcp068Fixture;
    281     s.closeInboxAuthentication(window.hcp068Action);
    282     const pool = s.getPublicPool(f.policy)!;
    283     let release = () => {};
    284     await new Promise<void>((resolve) => {
    285       release = s.subscribePublicPool(
    286         pool,
    287         [{ kinds: [30402], limit: 1 }],
    288         (message) => {
    289           if (message.type === 'EOSE') resolve();
    290         }
    291       );
    292     });
    293     release();
    294     s.closePublicPool(pool);
    295     return f.signs();
    296   });
    297   expect(result).toBe(0);
    298   expect(frames.some((x) => x[0] === 'REQ')).toBe(true);
    299   expect(frames.some((x) => x[0] === 'AUTH' || x[0] === 'EVENT')).toBe(false);
    300 });
    301 test('replacement during an outstanding SDK signer stops without rebinding the response', async ({
    302   page
    303 }) => {
    304   await page.evaluate(() => {
    305     window.hcp068Fixture.beforeSign(
    306       () =>
    307         new Promise<void>((resolve) => {
    308           window.hcp068Settle = resolve;
    309         })
    310     );
    311     window.hcp068Run = window.hcp068.respondInboxAuthentication(
    312       window.hcp068Action
    313     );
    314   });
    315   await expect
    316     .poll(() => page.evaluate(() => window.hcp068Fixture.signs()))
    317     .toBe(1);
    318   for (const socket of sockets.clients)
    319     socket.send(JSON.stringify(['AUTH', 'replacement']));
    320   await expect
    321     .poll(() =>
    322       page.evaluate(
    323         () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    324       )
    325     )
    326     .toBe('stopped');
    327   const result = await page.evaluate(async () => {
    328     window.hcp068Settle!();
    329     return window.hcp068Run;
    330   });
    331   expect(result?.status).not.toBe('accepted');
    332   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    333 });
    334 test('fresh SDK owner mismatch stops before the signer', async ({ page }) => {
    335   const result = await page.evaluate(async () => {
    336     window.hcp068Fixture.changeOwner();
    337     const result = await window.hcp068.respondInboxAuthentication(
    338       window.hcp068Action
    339     );
    340     return { result, signs: window.hcp068Fixture.signs() };
    341   });
    342   expect(result.result.status).not.toBe('accepted');
    343   expect(result.signs).toBe(0);
    344   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    345 });
    346 test('oversized genuine challenge stops bounded post-parse work without prompting', async ({
    347   page
    348 }) => {
    349   for (const socket of sockets.clients)
    350     socket.send(JSON.stringify(['AUTH', 'x'.repeat(4097)]));
    351   await expect
    352     .poll(() =>
    353       page.evaluate(
    354         () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    355       )
    356     )
    357     .toBe('stopped');
    358   expect(await page.evaluate(() => window.hcp068Fixture.signs())).toBe(0);
    359 });
    360 test('new physical connection and explicit action do not inherit accepted scope', async ({
    361   page
    362 }) => {
    363   await page.evaluate(() =>
    364     window.hcp068.respondInboxAuthentication(window.hcp068Action)
    365   );
    366   await page.evaluate(async () => {
    367     await window.hcp068Fixture.closeAndWait();
    368     window.hcp068Fixture = await window.hcp068.makeAuthFixture();
    369     const action = await window.hcp068.beginInboxAuthentication(
    370       window.hcp068Fixture.pool,
    371       window.hcp068.inbox,
    372       'reviewed_connection_auth'
    373     );
    374     if (!action) throw new Error('missing fresh action');
    375     window.hcp068Action = action;
    376   });
    377   await expect
    378     .poll(() =>
    379       page.evaluate(
    380         () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.state
    381       )
    382     )
    383     .toBe('challenge');
    384   expect(
    385     await page.evaluate(
    386       () => window.hcp068.inboxAuthSnapshot(window.hcp068Action)?.responses
    387     )
    388   ).toBe(0);
    389   await page.evaluate(() =>
    390     window.hcp068.respondInboxAuthentication(window.hcp068Action)
    391   );
    392   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(2);
    393   expect(await page.evaluate(() => window.hcp068Fixture.signs())).toBe(1);
    394 });
    395 test('failed physical close retains unavailable ownership until the same cleanup retries', async ({
    396   page
    397 }) => {
    398   const result = await page.evaluate(() => {
    399     const s = window.hcp068,
    400       fault = s.installCloseFailure();
    401     let closeFailed = false,
    402       reopenFailed = false;
    403     try {
    404       try {
    405         s.closeInboxAuthentication(window.hcp068Action);
    406       } catch {
    407         closeFailed = true;
    408       }
    409       try {
    410         window.hcp068Fixture.reopen();
    411       } catch {
    412         reopenFailed = true;
    413       }
    414       fault.allow();
    415       s.closeInboxAuthentication(window.hcp068Action);
    416       return { closeFailed, reopenFailed, signs: window.hcp068Fixture.signs() };
    417     } finally {
    418       fault.restore();
    419     }
    420   });
    421   expect(result).toEqual({ closeFailed: true, reopenFailed: true, signs: 0 });
    422 });
    423 test('raw private AUTH ports cannot bypass explicit review and guarded signing', async ({
    424   page
    425 }) => {
    426   const status = await page.evaluate(async () => {
    427     await window.hcp068Fixture.closeAndWait();
    428     window.hcp068Fixture = await window.hcp068.makeAuthFixture();
    429     return window.hcp068Fixture.rawPortBypass();
    430   });
    431   expect(status).not.toBe('accepted');
    432   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    433 });
    434 test('late extension owner change during signing prevents the AUTH effect', async ({
    435   page
    436 }) => {
    437   const result = await page.evaluate(async () => {
    438     window.hcp068Fixture.beforeSign(() => {
    439       window.hcp068Fixture.changeOwner();
    440       return Promise.resolve();
    441     });
    442     return window.hcp068.respondInboxAuthentication(window.hcp068Action);
    443   });
    444   expect(result.status).not.toBe('accepted');
    445   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    446 });
    447 test('reviewed AUTH uses the same genuine already-open private page connection', async ({
    448   page
    449 }) => {
    450   holdPage = true;
    451   await page.evaluate(async () => {
    452     await window.hcp068Fixture.closeAndWait();
    453     window.hcp068Fixture = await window.hcp068.makeAuthFixture();
    454     window.hcp068Fixture.startPage();
    455   });
    456   await expect.poll(() => frames.filter((x) => x[0] === 'REQ').length).toBe(1);
    457   const result = await page.evaluate(async () => {
    458     const action = await window.hcp068.beginInboxAuthentication(
    459       window.hcp068Fixture.pool,
    460       window.hcp068.inbox,
    461       'reviewed_connection_auth'
    462     );
    463     if (!action) return { status: 'missing' };
    464     window.hcp068Action = action;
    465     return window.hcp068.respondInboxAuthentication(action);
    466   });
    467   expect(result.status).toBe('accepted');
    468   expect(frames.filter((x) => x[0] === 'REQ')).toHaveLength(1);
    469   expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(1);
    470 });
    471 for (const phase of ['initial', 'post-sign'] as const)
    472   test(`actual ${phase} AUTH key loss invalidates original session identity and retained private cache`, async ({
    473     page
    474   }) => {
    475     const result = await page.evaluate(async (phase) => {
    476       const f = window.hcp068Fixture,
    477         before = f.ownership();
    478       if (phase === 'initial') f.changeOwner();
    479       else
    480         f.beforeSign(() => {
    481           f.changeOwner();
    482           return Promise.resolve();
    483         });
    484       const result = await window.hcp068.respondInboxAuthentication(
    485         window.hcp068Action
    486       );
    487       return { before, result, after: f.ownership() };
    488     }, phase);
    489     expect(result.before.private).toBe(true);
    490     expect(result.before.identity).toBe(true);
    491     expect(result.before.cache.count).toBe(1);
    492     expect(result.result.status).not.toBe('accepted');
    493     expect(result.after.private).toBe(false);
    494     expect(result.after.identity).toBe(false);
    495     expect(result.after.cache).toEqual({ closed: true, count: 0, bytes: 0 });
    496     expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    497   });
    498 test('stale original generation cannot invalidate a genuinely connected successor', async ({
    499   page
    500 }) => {
    501   expect(
    502     await page.evaluate(() =>
    503       window.hcp068Fixture.staleGenerationInvalidation()
    504     )
    505   ).toEqual({ result: false, successor: true, identity: true });
    506 });
    507 for (const phase of ['initial', 'post-sign'] as const)
    508   test(`actual ${phase} capability loss invalidates AUTH session and cache`, async ({
    509     page
    510   }) => {
    511     const result = await page.evaluate(async (phase) => {
    512       const f = window.hcp068Fixture;
    513       if (phase === 'initial') f.loseCapability();
    514       else
    515         f.beforeSign(() => {
    516           f.loseCapability();
    517           return Promise.resolve();
    518         });
    519       const result = await window.hcp068.respondInboxAuthentication(
    520         window.hcp068Action
    521       );
    522       return { result, after: f.ownership() };
    523     }, phase);
    524     expect(result.result.status).not.toBe('accepted');
    525     expect(result.after.private).toBe(false);
    526     expect(result.after.identity).toBe(false);
    527     expect(result.after.cache).toEqual({ closed: true, count: 0, bytes: 0 });
    528     expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    529   });
    530 for (const mode of ['invalid', 'missing'] as const)
    531   for (const phase of ['initial', 'post-sign'] as const)
    532     test(`actual ${phase} ${mode} key observation invalidates original ownership`, async ({
    533       page
    534     }) => {
    535       const result = await page.evaluate(
    536         async ({ mode, phase }) => {
    537           const f = window.hcp068Fixture;
    538           if (phase === 'initial') f.failKey(mode);
    539           else
    540             f.beforeSign(() => {
    541               f.failKey(mode);
    542               return Promise.resolve();
    543             });
    544           const result = await window.hcp068.respondInboxAuthentication(
    545             window.hcp068Action
    546           );
    547           return { result, after: f.ownership() };
    548         },
    549         { mode, phase }
    550       );
    551       expect(result.result.status).not.toBe('accepted');
    552       expect(result.after.private).toBe(false);
    553       expect(result.after.identity).toBe(false);
    554       expect(result.after.cache).toEqual({ closed: true, count: 0, bytes: 0 });
    555       expect(frames.filter((x) => x[0] === 'AUTH')).toHaveLength(0);
    556     });