app

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

conversation-options.spec.ts (17133B)


      1 import { test, expect, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { svelte } from '@sveltejs/vite-plugin-svelte';
      4 import { fileURLToPath } from 'node:url';
      5 import { once } from 'node:events';
      6 import { WebSocketServer } from 'ws';
      7 import { finalizeEvent, getPublicKey } from 'applesauce-core/helpers';
      8 import { createStaticHarness } from '../integration/harness/static.ts';
      9 import type * as Fixture from './harness/conversation-options.ts';
     10 declare global {
     11   interface Window {
     12     hcp105: typeof Fixture;
     13     hcp105Fixture: Awaited<ReturnType<typeof Fixture.renderFixture>>;
     14   }
     15 }
     16 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     17   sockets: WebSocketServer,
     18   endpoint: string,
     19   bundle: string;
     20 type Mode =
     21   | 'normal'
     22   | 'missing'
     23   | 'wrong_author'
     24   | 'wrong_coordinate'
     25   | 'invalid_signature'
     26   | 'sold'
     27   | 'deleted'
     28   | 'partial'
     29   | 'hold';
     30 let mode: Mode = 'normal',
     31   requests: unknown[][] = [],
     32   events: unknown[][] = [],
     33   release = () => {};
     34 const secret = new Uint8Array(32).fill(84),
     35   otherSecret = new Uint8Array(32).fill(90),
     36   peer = getPublicKey(secret);
     37 function listing(createdAt = 1700000060) {
     38   const event = finalizeEvent(
     39     {
     40       kind: 30402,
     41       created_at: createdAt,
     42       content: 'Independently signed carrots',
     43       tags: [
     44         ['d', mode === 'wrong_coordinate' ? 'apples' : 'carrots'],
     45         ['title', 'Verified carrots'],
     46         ['summary', 'Actual signed listing'],
     47         ['published_at', '1700000000'],
     48         ['location', 'Victoria'],
     49         ['price', '3.5', 'CAD'],
     50         ['radroots:price_unit', 'lb'],
     51         ['status', mode === 'sold' ? 'sold' : 'active']
     52       ]
     53     },
     54     mode === 'wrong_author' ? otherSecret : secret
     55   );
     56   return mode === 'invalid_signature'
     57     ? { ...event, sig: '0'.repeat(128) }
     58     : event;
     59 }
     60 test.beforeAll(async () => {
     61   server = await createStaticHarness();
     62   sockets = new WebSocketServer({
     63     host: '127.0.0.1',
     64     port: 0,
     65     maxPayload: 65536
     66   });
     67   await once(sockets, 'listening');
     68   const address = sockets.address();
     69   if (!address || typeof address === 'string') throw Error('no loopback');
     70   endpoint = 'ws://127.0.0.1:' + address.port;
     71   sockets.on('connection', (socket) =>
     72     socket.on('message', (bytes) => {
     73       const raw = Buffer.isBuffer(bytes)
     74         ? bytes
     75         : Array.isArray(bytes)
     76           ? Buffer.concat(bytes)
     77           : Buffer.from(bytes);
     78       const frame = JSON.parse(raw.toString()) as unknown[];
     79       if (frame[0] === 'EVENT') {
     80         events.push(frame);
     81         return;
     82       }
     83       if (frame[0] !== 'REQ') return;
     84       requests.push(frame);
     85       const filters = frame.slice(2) as { kinds?: number[]; ids?: string[] }[];
     86       const send = () => {
     87         if (mode !== 'missing') {
     88           if (filters.some((f) => f.kinds?.includes(30402))) {
     89             const exact = filters.find((f) => f.ids)?.ids;
     90             const event = exact?.includes(listing(1700000050).id)
     91               ? listing(1700000050)
     92               : listing();
     93             socket.send(JSON.stringify(['EVENT', frame[1], event]));
     94           }
     95           if (mode === 'deleted' && filters.some((f) => f.kinds?.includes(5)))
     96             socket.send(
     97               JSON.stringify([
     98                 'EVENT',
     99                 frame[1],
    100                 finalizeEvent(
    101                   {
    102                     kind: 5,
    103                     created_at: 1700000070,
    104                     tags: [['a', '30402:' + peer + ':carrots']],
    105                     content: ''
    106                   },
    107                   secret
    108                 )
    109               ])
    110             );
    111         }
    112         if (!(
    113           mode === 'partial' &&
    114           filters.some((filter) => filter.kinds?.includes(5))
    115         ))
    116           socket.send(JSON.stringify(['EOSE', frame[1]]));
    117       };
    118       if (mode === 'hold') release = send;
    119       else send();
    120     })
    121   );
    122   const result = await build({
    123     configFile: false,
    124     logLevel: 'silent',
    125     plugins: [svelte({ configFile: false })],
    126     resolve: {
    127       conditions: ['browser'],
    128       alias: {
    129         '$app/navigation': fileURLToPath(
    130           new URL('./harness/conversation-options.ts', import.meta.url)
    131         )
    132       }
    133     },
    134     build: {
    135       write: false,
    136       minify: false,
    137       lib: {
    138         entry: fileURLToPath(
    139           new URL('./harness/conversation-options.ts', import.meta.url)
    140         ),
    141         name: 'hcp105',
    142         formats: ['iife']
    143       }
    144     }
    145   });
    146   const output = Array.isArray(result) ? result[0] : result;
    147   if (!('output' in output)) throw Error('no bundle');
    148   const chunks = output.output.filter((row) => row.type === 'chunk');
    149   expect(chunks).toHaveLength(1);
    150   bundle = chunks[0].code;
    151 });
    152 test.afterAll(async () => {
    153   for (const socket of sockets.clients) socket.terminate();
    154   await new Promise<void>((resolve) => sockets.close(() => resolve()));
    155   await server.close();
    156 });
    157 test.beforeEach(async ({ page }) => {
    158   mode = 'normal';
    159   requests = [];
    160   events = [];
    161   release = () => {};
    162   await page.addInitScript(
    163     ({ endpoint }) => {
    164       const Native = window.WebSocket;
    165       window.WebSocket = class extends Native {
    166         constructor(url: string | URL, protocols?: string | string[]) {
    167           if (
    168             ![
    169               'wss://discovery.example.org',
    170               'wss://archive.example.org',
    171               'wss://peer.example.org'
    172             ].includes(new URL(String(url)).origin)
    173           )
    174             throw Error('unapproved destination');
    175           super(endpoint, protocols);
    176         }
    177       };
    178     },
    179     { endpoint }
    180   );
    181   await page.goto(server.url + '/search');
    182   await page.addScriptTag({ content: bundle });
    183 });
    184 test.afterEach(async ({ page }) => {
    185   if (!page.isClosed())
    186     await page.evaluate(() => window.hcp105Fixture?.close());
    187 });
    188 async function ready(
    189   page: Page,
    190   scenario: Fixture.OptionsScenario = 'contexts'
    191 ) {
    192   await page.evaluate(async (scenario) => {
    193     window.hcp105Fixture = await window.hcp105.renderFixture(scenario);
    194   }, scenario);
    195   await expect(page.locator('[data-options-fixture]')).toBeVisible();
    196   await expect
    197     .poll(() =>
    198       page.evaluate(async () =>
    199         (await window.hcp105Fixture.native()).received.every(
    200           (row) =>
    201             (JSON.parse((row as { wire: string }).wire) as { read: unknown })
    202               .read !== null
    203         )
    204       )
    205     )
    206     .toBe(true);
    207 }
    208 const panel = (page: Page) => page.locator('[data-options-fixture]');
    209 const verify = (page: Page) =>
    210   panel(page)
    211     .getByRole('button', { name: 'Verify product citation', exact: true })
    212     .click();
    213 
    214 test('mount and conversation disclosure show the original authenticated peer without discovery native writes or profile routes', async ({
    215   page
    216 }) => {
    217   await ready(page);
    218   const before = await page.evaluate(async () => ({
    219     native: await window.hcp105Fixture.native(),
    220     delta: window.hcp105Fixture.delta()
    221   }));
    222   await panel(page)
    223     .getByText('Identity and conversation options', { exact: true })
    224     .click();
    225   await expect(panel(page)).toContainText(peer);
    226   expect(await page.evaluate(() => window.hcp105Fixture.options()?.peer)).toBe(
    227     peer
    228   );
    229   expect(requests).toEqual([]);
    230   expect(events).toEqual([]);
    231   expect(
    232     await panel(page).locator('a[href*="/profiles"],a[href*="/shops"]').count()
    233   ).toBe(0);
    234   expect(
    235     await page.evaluate(async () => ({
    236       native: await window.hcp105Fixture.native(),
    237       delta: window.hcp105Fixture.delta()
    238     }))
    239   ).toEqual(before);
    240 });
    241 test('local block and report hooks receive the authenticated inner peer without implementing private disclosure or public reports', async ({
    242   page
    243 }) => {
    244   await ready(page);
    245   await panel(page)
    246     .getByText('Identity and conversation options', { exact: true })
    247     .click();
    248   await panel(page)
    249     .getByRole('button', { name: 'Block person', exact: true })
    250     .click();
    251   await panel(page)
    252     .getByRole('button', { name: 'Report conversation', exact: true })
    253     .click();
    254   expect(await page.evaluate(() => window.hcp105Fixture.hooks())).toEqual([
    255     { action: 'block', peer },
    256     { action: 'report', peer }
    257   ]);
    258   expect(requests).toEqual([]);
    259   expect(events).toEqual([]);
    260 });
    261 test('explicit citation verification uses actual independently signed pair publisher and fixed bounded public queries', async ({
    262   page
    263 }) => {
    264   await ready(page);
    265   const before = await page.evaluate(async () => ({
    266     native: await window.hcp105Fixture.native(),
    267     delta: window.hcp105Fixture.delta()
    268   }));
    269   await verify(page);
    270   await expect(panel(page)).toContainText('Verified carrots');
    271   await expect(panel(page)).toContainText('Signed listing observed');
    272   expect(requests.length).toBeGreaterThan(0);
    273   for (const frame of requests)
    274     for (const filter of frame.slice(2) as {
    275       kinds: number[];
    276       authors: string[];
    277       limit: number;
    278     }[]) {
    279       expect(filter.kinds.every((kind) => [30402, 5].includes(kind))).toBe(
    280         true
    281       );
    282       expect(filter.authors).toEqual([peer]);
    283       expect(filter.limit).toBe(200);
    284     }
    285   expect(events).toEqual([]);
    286   expect(
    287     await page.evaluate(async () => ({
    288       native: await window.hcp105Fixture.native(),
    289       delta: window.hcp105Fixture.delta()
    290     }))
    291   ).toEqual(before);
    292   await expect(panel(page)).toContainText('not a current or locked quote');
    293 });
    294 for (const rejection of [
    295   'missing',
    296   'wrong_author',
    297   'wrong_coordinate',
    298   'invalid_signature'
    299 ] as const)
    300   test('untrusted listing stays unresolved: ' + rejection, async ({ page }) => {
    301     mode = rejection;
    302     await ready(page);
    303     await verify(page);
    304     await expect(panel(page)).toContainText(
    305       'Listing citation remains unresolved'
    306     );
    307     await expect(panel(page)).not.toContainText('Signed listing observed');
    308     expect(events).toEqual([]);
    309   });
    310 test('sold listing is independently observed without reserving inventory or accepting an order', async ({
    311   page
    312 }) => {
    313   mode = 'sold';
    314   await ready(page);
    315   const native = await page.evaluate(() => window.hcp105Fixture.native());
    316   await verify(page);
    317   await expect(panel(page)).toContainText('Listing is sold');
    318   expect(await page.evaluate(() => window.hcp105Fixture.native())).toEqual(
    319     native
    320   );
    321   expect(events).toEqual([]);
    322 });
    323 test('actual signed public deletion keeps the citation withdrawn rather than trusted', async ({
    324   page
    325 }) => {
    326   mode = 'deleted';
    327   await ready(page);
    328   await verify(page);
    329   await expect(panel(page)).toContainText('Listing is withdrawn');
    330   await expect(panel(page)).not.toContainText('Signed listing observed');
    331   expect(events).toEqual([]);
    332 });
    333 test('unknown private parent and arbitrary body link never spawn a public hash query or external navigation', async ({
    334   page
    335 }) => {
    336   await ready(page, 'parent_reference');
    337   await expect(panel(page)).toContainText('Earlier message unavailable');
    338   await expect(panel(page)).toContainText('https://untrusted.example.org');
    339   expect(
    340     await page.evaluate(() => window.hcp105Fixture.capture('f'.repeat(64)))
    341   ).toBe(false);
    342   expect(requests).toEqual([]);
    343   expect(await panel(page).locator('a[href^="https://"]').count()).toBe(0);
    344   expect(events).toEqual([]);
    345   await verify(page);
    346   await expect(panel(page)).toContainText('Verified carrots');
    347   expect(JSON.stringify(requests)).not.toContain('f'.repeat(64));
    348 });
    349 test('included exact public version is independently verified from the genuine original message', async ({
    350   page
    351 }) => {
    352   await ready(page, 'exact');
    353   await verify(page);
    354   await expect(panel(page)).toContainText('Included version verified');
    355   const id = await page.evaluate(() => window.hcp105Fixture.citedVersion);
    356   expect(
    357     requests.some((frame) =>
    358       (frame.slice(2) as { ids?: string[] }[]).some((filter) =>
    359         filter.ids?.includes(id)
    360       )
    361     )
    362   ).toBe(true);
    363   expect(events).toEqual([]);
    364 });
    365 test('a genuinely signed older included version stays distinct from the observed current listing and cannot lock a quote', async ({
    366   page
    367 }) => {
    368   await ready(page, 'stale');
    369   await verify(page);
    370   await expect(panel(page)).toContainText(
    371     'Included version differs from the observed listing'
    372   );
    373   await expect(panel(page)).not.toContainText('Included version verified');
    374   await expect(panel(page)).toContainText('not a current or locked quote');
    375   expect(events).toEqual([]);
    376 });
    377 test('copied view runtime and citation tokens cannot borrow independent verification or option authority', async ({
    378   page
    379 }) => {
    380   await ready(page);
    381   expect(
    382     await page.evaluate(() =>
    383       window.hcp105Fixture.capture(undefined, 'unreviewed')
    384     )
    385   ).toBe(false);
    386   expect(requests).toEqual([]);
    387   expect(await page.evaluate(() => window.hcp105Fixture.copied())).toEqual({
    388     view: false,
    389     runtime: false,
    390     snapshot: undefined,
    391     options: undefined,
    392     hook: false
    393   });
    394   expect(requests).toEqual([]);
    395   expect(events).toEqual([]);
    396 });
    397 test('logout during actual held public response cannot revive private citation context or invoke local hooks', async ({
    398   page
    399 }) => {
    400   mode = 'hold';
    401   await ready(page);
    402   await verify(page);
    403   await expect.poll(() => requests.length).toBe(1);
    404   await page.evaluate(() => window.hcp105Fixture.logout());
    405   mode = 'normal';
    406   release();
    407   await expect(panel(page)).not.toContainText('Verified carrots');
    408   await expect(panel(page)).not.toContainText(peer);
    409   expect(events).toEqual([]);
    410   expect(await page.evaluate(() => window.hcp105Fixture.hooks())).toEqual([]);
    411 });
    412 test('unmount closes the original held query without private writes or late context rendering', async ({
    413   page
    414 }) => {
    415   mode = 'hold';
    416   await ready(page);
    417   const native = await page.evaluate(() => window.hcp105Fixture.native());
    418   await verify(page);
    419   await expect.poll(() => requests.length).toBe(1);
    420   await page.evaluate(() => window.hcp105Fixture.closePanel());
    421   mode = 'normal';
    422   release();
    423   await expect(panel(page)).toHaveCount(0);
    424   expect(events).toEqual([]);
    425   expect(await page.evaluate(() => window.hcp105Fixture.native())).toEqual(
    426     native
    427   );
    428 });
    429 
    430 test('expired signed listing with incomplete deletion coverage remains visibly unresolved', async ({
    431   page
    432 }) => {
    433   mode = 'partial';
    434   await ready(page, 'exact');
    435   const before = await page.evaluate(async () => ({
    436     native: await window.hcp105Fixture.native(),
    437     delta: window.hcp105Fixture.delta()
    438   }));
    439   await verify(page);
    440   await expect
    441     .poll(() =>
    442       requests.some((frame) =>
    443         (frame.slice(2) as { kinds: number[] }[]).some((filter) =>
    444           filter.kinds.includes(5)
    445         )
    446       )
    447     )
    448     .toBe(true);
    449   await page.evaluate(() => window.hcp105Fixture.advance());
    450   await expect(panel(page)).toContainText(
    451     'Listing citation remains unresolved'
    452   );
    453   await expect(panel(page)).not.toContainText('Included version verified');
    454   await expect(panel(page)).not.toContainText('Signed listing observed');
    455   expect(
    456     await page.evaluate(async () => ({
    457       native: await window.hcp105Fixture.native(),
    458       delta: window.hcp105Fixture.delta()
    459     }))
    460   ).toEqual(before);
    461   expect(events).toEqual([]);
    462 });
    463 
    464 for (const action of ['logout', 'selection', 'close'] as const)
    465   test(
    466     'standalone original message revocation clears private rendering and stale Reply: ' +
    467       action,
    468     async ({ page }) => {
    469       await ready(page, 'exact');
    470       await expect(panel(page).locator('article[data-message-id]')).toHaveCount(
    471         1
    472       );
    473       await expect(panel(page)).toContainText(
    474         'Quoted price: 4 GBP https://untrusted.example.org'
    475       );
    476       await expect(
    477         panel(page).getByRole('button', {
    478           name: 'Reply to this message',
    479           exact: true
    480         })
    481       ).toBeVisible();
    482       const before = await page.evaluate(async () => ({
    483         native: await window.hcp105Fixture.native(),
    484         delta: window.hcp105Fixture.delta()
    485       }));
    486       await page.evaluate(
    487         (action) => window.hcp105Fixture.revokeAndClick(action),
    488         action
    489       );
    490       expect(
    491         await page.evaluate(() => window.hcp105Fixture.currentMessage())
    492       ).toBe(false);
    493       if (action === 'close')
    494         expect(
    495           await page.evaluate(() => window.hcp105Fixture.terminal())
    496         ).toEqual(['reentered', 'survived']);
    497       expect(await page.evaluate(() => window.hcp105Fixture.hooks())).toEqual(
    498         []
    499       );
    500       await expect(panel(page).locator('article[data-message-id]')).toHaveCount(
    501         0
    502       );
    503       await expect(panel(page)).not.toContainText(
    504         'Quoted price: 4 GBP https://untrusted.example.org'
    505       );
    506       await expect(
    507         panel(page).getByRole('button', {
    508           name: 'Reply to this message',
    509           exact: true
    510         })
    511       ).toHaveCount(0);
    512       await expect(panel(page).locator('a[href*="/products/"]')).toHaveCount(0);
    513       await expect(panel(page)).not.toContainText(peer);
    514       expect(
    515         await page.evaluate(async () => ({
    516           native: await window.hcp105Fixture.native(),
    517           delta: window.hcp105Fixture.delta()
    518         }))
    519       ).toEqual(before);
    520       expect(requests).toEqual([]);
    521       expect(events).toEqual([]);
    522     }
    523   );