app

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

support-report.spec.ts (18468B)


      1 import { expect, test, 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 { createStaticHarness } from '../integration/harness/static.ts';
      8 import type * as Fixture from './harness/support-report.ts';
      9 declare global {
     10   interface Window {
     11     hcp124: typeof Fixture;
     12     hcp124Private?: Awaited<ReturnType<typeof Fixture.createPrivateFixture>>;
     13     hcp124Public?: Awaited<ReturnType<typeof Fixture.createPublicFixture>>;
     14     hcp124General?: ReturnType<typeof Fixture.createGeneralFixture>;
     15     hcp124Support?: ReturnType<typeof Fixture.createSupportFixture>;
     16     hcp124Clipboard: string[];
     17     hcp124PendingCopy?: Promise<'copied' | 'unavailable' | 'stopped'>;
     18     hcp124FinishCopy?: () => void;
     19     hcp124CopyStarted?: boolean;
     20   }
     21 }
     22 
     23 // This case deliberately needs no future fixture/producer compilation. The
     24 // first preproducer run uses exact accepted HCP123 clean static output.
     25 test('HCP124 SSR practical About and honest missing support without private inventory', async ({
     26   page
     27 }) => {
     28   const server = await createStaticHarness();
     29   try {
     30     await page.addInitScript(() => {
     31       Object.defineProperty(window, 'nostr', {
     32         configurable: true,
     33         get() {
     34           throw Error('About must not acquire an extension');
     35         }
     36       });
     37     });
     38     await page.goto(server.url + '/about');
     39     expect(await page.locator('h1').innerText()).toBe('About HarvestCircle');
     40     await expect(
     41       page.getByText('Search without connecting.', { exact: false })
     42     ).toBeVisible();
     43     await expect(
     44       page.getByText('Messages do not reserve food or confirm an order.', {
     45         exact: false
     46       })
     47     ).toBeVisible();
     48     await expect(
     49       page.getByText('Payments are not handled here.', { exact: false })
     50     ).toBeVisible();
     51     await expect(page.locator('#report')).toBeVisible();
     52     await expect(
     53       page.getByText('Support has not been configured.', { exact: false })
     54     ).toBeVisible();
     55     await expect(
     56       page.getByRole('link', { name: 'Contact support', exact: true })
     57     ).toHaveCount(0);
     58     await expect(page.locator('input[type=checkbox]')).toHaveCount(0);
     59     await expect(page).toHaveTitle('About — HarvestCircle');
     60   } finally {
     61     await server.close();
     62   }
     63 });
     64 
     65 test.describe('HCP124 actual production selected-report controls', () => {
     66   let server: Awaited<ReturnType<typeof createStaticHarness>>,
     67     sockets: WebSocketServer,
     68     endpoint: string,
     69     bundle: string | undefined;
     70   let publicEvents: unknown[] = [],
     71     events: unknown[][] = [],
     72     queries: unknown[][] = [];
     73   test.beforeAll(async () => {
     74     server = await createStaticHarness();
     75     sockets = new WebSocketServer({
     76       host: '127.0.0.1',
     77       port: 0,
     78       maxPayload: 262144
     79     });
     80     await once(sockets, 'listening');
     81     const address = sockets.address();
     82     if (!address || typeof address === 'string')
     83       throw Error('controlled loopback unavailable');
     84     endpoint = 'ws://127.0.0.1:' + address.port;
     85     sockets.on('connection', (socket) =>
     86       socket.on('message', (bytes) => {
     87         const raw = Buffer.isBuffer(bytes)
     88           ? bytes
     89           : Array.isArray(bytes)
     90             ? Buffer.concat(bytes)
     91             : Buffer.from(bytes);
     92         const frame = JSON.parse(raw.toString()) as unknown[];
     93         if (frame[0] === 'EVENT' || frame[0] === 'AUTH') events.push(frame);
     94         if (frame[0] === 'REQ') {
     95           queries.push(frame);
     96           const filters = frame.slice(2) as {
     97             kinds?: number[];
     98             ids?: string[];
     99           }[];
    100           if (filters.some((filter) => filter.kinds?.includes(30402)))
    101             for (const event of publicEvents)
    102               socket.send(JSON.stringify(['EVENT', frame[1], event]));
    103           socket.send(JSON.stringify(['EOSE', frame[1]]));
    104         }
    105       })
    106     );
    107   });
    108   test.afterAll(async () => {
    109     for (const socket of sockets?.clients ?? []) socket.terminate();
    110     if (sockets)
    111       await new Promise<void>((resolve) => sockets.close(() => resolve()));
    112     await server?.close();
    113   });
    114   test.beforeEach(async ({ page }) => {
    115     publicEvents = [];
    116     events = [];
    117     queries = [];
    118     await page.addInitScript((endpoint) => {
    119       const Native = window.WebSocket;
    120       window.WebSocket = class extends Native {
    121         constructor(url: string | URL, protocols?: string | string[]) {
    122           if (
    123             ![
    124               'wss://peer.example.org',
    125               'wss://archive.example.org',
    126               'wss://discovery.example.org'
    127             ].includes(new URL(String(url)).origin)
    128           )
    129             throw Error('no live relay authorization');
    130           super(endpoint, protocols);
    131         }
    132       };
    133       window.hcp124Clipboard = [];
    134       Object.defineProperty(navigator, 'clipboard', {
    135         configurable: true,
    136         value: {
    137           writeText: (text: string) => {
    138             window.hcp124Clipboard.push(text);
    139             return Promise.resolve();
    140           }
    141         }
    142       });
    143     }, endpoint);
    144   });
    145   test.afterEach(async ({ page }) => {
    146     if (!page.isClosed())
    147       await page.evaluate(async () => {
    148         await window.hcp124Private?.close();
    149         await window.hcp124Public?.close();
    150         await window.hcp124General?.close();
    151         await window.hcp124Support?.close();
    152       });
    153   });
    154   async function load(page: Page) {
    155     await page.goto(server.url + '/about');
    156     if (!bundle) {
    157       const output = await build({
    158         configFile: false,
    159         root: process.cwd(),
    160         logLevel: 'silent',
    161         plugins: [
    162           svelte({ configFile: false, compilerOptions: { dev: false } })
    163         ],
    164         resolve: {
    165           conditions: ['browser'],
    166           alias: {
    167             '$app/navigation': fileURLToPath(
    168               new URL('./harness/conversation-thread.ts', import.meta.url)
    169             )
    170           }
    171         },
    172         build: {
    173           write: false,
    174           emptyOutDir: false,
    175           minify: false,
    176           lib: {
    177             entry: fileURLToPath(
    178               new URL('./harness/support-report.ts', import.meta.url)
    179             ),
    180             name: 'hcp124',
    181             formats: ['iife']
    182           }
    183         }
    184       });
    185       const result = Array.isArray(output) ? output[0] : output;
    186       if (!result || !('output' in result))
    187         throw Error('fixture output unavailable');
    188       const chunks = result.output.filter((row) => row.type === 'chunk');
    189       expect(chunks).toHaveLength(1);
    190       const chunk = chunks[0];
    191       bundle = chunk.code;
    192     }
    193     await page.addScriptTag({ content: bundle });
    194   }
    195   async function privateReport(page: Page) {
    196     await load(page);
    197     await page.evaluate(async () => {
    198       window.hcp124Private = await window.hcp124.createPrivateFixture();
    199     });
    200     await page.evaluate(() => window.hcp124Private!.checkSetup());
    201     expect(await page.evaluate(() => window.hcp124Private!.unlock())).toBe(
    202       true
    203     );
    204     await expect
    205       .poll(() =>
    206         page.evaluate(() => window.hcp124Private!.thread().messages.length)
    207       )
    208       .toBe(3);
    209     await expect
    210       .poll(() =>
    211         page.evaluate(
    212           async () =>
    213             (await window.hcp124Private!.native()).received.filter((row) => {
    214               const parsed = JSON.parse((row as { wire: string }).wire) as {
    215                 read: unknown;
    216               };
    217               return parsed.read !== null;
    218             }).length
    219         )
    220       )
    221       .toBe(3);
    222     await page.evaluate(async () => {
    223       await window.hcp124Private!.waitOwner();
    224       window.hcp124Private!.report();
    225     });
    226     await expect(page.locator('#hcp124-report-fixture')).toBeVisible();
    227   }
    228   const panel = (page: Page) => page.locator('#hcp124-report-fixture');
    229 
    230   test('actual support link has the reviewed destination without transcript carrier or automatic navigation', async ({
    231     page
    232   }) => {
    233     await load(page);
    234     await page.evaluate(() => {
    235       window.hcp124Support = window.hcp124.createSupportFixture();
    236     });
    237     const link = page
    238       .locator('#hcp124-support-fixture')
    239       .getByRole('link', { name: 'Contact support', exact: true });
    240     await expect(link).toHaveAttribute(
    241       'href',
    242       'https://support.operator.org/report'
    243     );
    244     await expect(link).toHaveAttribute('rel', /noopener/);
    245     await expect(link).toHaveAttribute('rel', /noreferrer/);
    246     await expect(link).toHaveAttribute('referrerpolicy', 'no-referrer');
    247     expect(page.url()).toBe(server.url + '/about');
    248     expect(events).toEqual([]);
    249     expect(queries).toEqual([]);
    250   });
    251   test('voluntary plain notes require explicit review and optional copy without support transport', async ({
    252     page
    253   }) => {
    254     await load(page);
    255     await page.evaluate(() => {
    256       window.hcp124General = window.hcp124.createGeneralFixture();
    257     });
    258     await panel(page)
    259       .getByLabel('Problem description')
    260       .fill('<img src=x> Deliberately selected description');
    261     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
    262     await panel(page)
    263       .getByRole('button', { name: 'Review report', exact: true })
    264       .click();
    265     await expect(
    266       panel(page).getByRole('region', { name: 'Selected report preview' })
    267     ).toContainText('<img src=x> Deliberately selected description');
    268     await expect(panel(page).locator('img')).toHaveCount(0);
    269     await panel(page)
    270       .getByRole('button', { name: 'Copy reviewed report', exact: true })
    271       .click();
    272     expect(await page.evaluate(() => window.hcp124Clipboard.length)).toBe(1);
    273     expect(events).toEqual([]);
    274     expect(queries).toEqual([]);
    275     expect(page.url()).toBe(server.url + '/about');
    276   });
    277   test('private message and peer choices start unselected and no transcript is copied automatically', async ({
    278     page
    279   }) => {
    280     await privateReport(page);
    281     expect(
    282       await panel(page).locator('input[type=checkbox]:checked').count()
    283     ).toBe(0);
    284     await expect(
    285       panel(page).getByRole('region', { name: 'Selected report preview' })
    286     ).toHaveCount(0);
    287     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
    288     await expect(
    289       panel(page).getByText(
    290         'Support cannot automatically read encrypted messages.',
    291         { exact: false }
    292       )
    293     ).toBeVisible();
    294     await expect(
    295       panel(page).getByText(
    296         'Copied text can remain in your clipboard or other applications.',
    297         { exact: false }
    298       )
    299     ).toBeVisible();
    300   });
    301   test('selected private text needs extra acknowledgment and excludes every unselected message and owner', async ({
    302     page
    303   }) => {
    304     await privateReport(page);
    305     const before = await page.evaluate(async () => ({
    306       native: await window.hcp124Private!.native(),
    307       delta: window.hcp124Private!.delta(),
    308       owner: window.hcp124Private!.owner,
    309       peer: window.hcp124Private!.peer
    310     }));
    311     await panel(page)
    312       .getByLabel('Share message text and ID 1', { exact: true })
    313       .check();
    314     await panel(page)
    315       .getByRole('button', { name: 'Review report', exact: true })
    316       .click();
    317     await expect(
    318       panel(page).getByRole('region', { name: 'Selected report preview' })
    319     ).toHaveCount(0);
    320     await panel(page)
    321       .getByLabel(
    322         'I understand selected private information will leave HarvestCircle if I share it.',
    323         { exact: true }
    324       )
    325       .check();
    326     await panel(page)
    327       .getByRole('button', { name: 'Review report', exact: true })
    328       .click();
    329     const text = await panel(page)
    330       .getByRole('region', { name: 'Selected report preview' })
    331       .innerText();
    332     expect(text).toContain('Actual encrypted thread fixture');
    333     expect(text).not.toContain('About carrots');
    334     expect(text).not.toContain('About apples');
    335     expect(text).not.toContain(before.owner);
    336     expect(text).not.toContain(before.peer);
    337     await panel(page)
    338       .getByRole('button', { name: 'Copy reviewed report', exact: true })
    339       .click();
    340     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([text]);
    341     expect(await page.evaluate(() => window.hcp124Private!.delta())).toEqual(
    342       before.delta
    343     );
    344     expect(await page.evaluate(() => window.hcp124Private!.native())).toEqual(
    345       before.native
    346     );
    347     expect(events).toEqual([]);
    348     const support = panel(page).getByRole('link', {
    349       name: 'Contact support',
    350       exact: true
    351     });
    352     await expect(support).toHaveAttribute(
    353       'href',
    354       'https://support.operator.org/report'
    355     );
    356   });
    357   test('genuine logout retires an already captured selected private preview before copy', async ({
    358     page
    359   }) => {
    360     await privateReport(page);
    361     expect(
    362       await page.evaluate(() => window.hcp124Private!.captureSelected())
    363     ).toContain('Actual encrypted thread fixture');
    364     await page.evaluate(() => window.hcp124Private!.logout());
    365     expect(
    366       await page.evaluate(() => window.hcp124Private!.captured())
    367     ).toBeUndefined();
    368     expect(
    369       await page.evaluate(() => window.hcp124Private!.copyCaptured())
    370     ).toBe('stopped');
    371     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
    372     await expect(
    373       panel(page).getByRole('region', { name: 'Selected report preview' })
    374     ).toHaveCount(0);
    375   });
    376   test('an already requested clipboard copy can finish after logout without claiming current success', async ({
    377     page
    378   }) => {
    379     await privateReport(page);
    380     const selected = await page.evaluate(() =>
    381       window.hcp124Private!.captureSelected()
    382     );
    383     await page.evaluate(() => {
    384       Object.defineProperty(navigator, 'clipboard', {
    385         configurable: true,
    386         value: {
    387           writeText: (text: string) =>
    388             new Promise<void>((resolve) => {
    389               window.hcp124CopyStarted = true;
    390               window.hcp124FinishCopy = () => {
    391                 window.hcp124Clipboard.push(text);
    392                 resolve();
    393               };
    394             })
    395         }
    396       });
    397       window.hcp124PendingCopy = window.hcp124Private!.copyCaptured();
    398     });
    399     await expect
    400       .poll(() => page.evaluate(() => window.hcp124CopyStarted))
    401       .toBe(true);
    402     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
    403     await page.evaluate(() => window.hcp124Private!.logout());
    404     expect(
    405       await page.evaluate(() => window.hcp124Private!.captured())
    406     ).toBeUndefined();
    407     const outcome = await page.evaluate(async () => {
    408       window.hcp124FinishCopy!();
    409       return await window.hcp124PendingCopy;
    410     });
    411     expect(outcome).toBe('stopped');
    412     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([
    413       selected
    414     ]);
    415     await expect(
    416       panel(page).getByRole('region', { name: 'Selected report preview' })
    417     ).toHaveCount(0);
    418     expect(events).toEqual([]);
    419   });
    420   test('acknowledged real native block retires captured private report with encrypted evidence retained', async ({
    421     page
    422   }) => {
    423     await privateReport(page);
    424     await page.evaluate(() => window.hcp124Private!.captureSelected());
    425     const before = await page.evaluate(() => window.hcp124Private!.native());
    426     expect(await page.evaluate(() => window.hcp124Private!.block())).toEqual({
    427       status: 'saved'
    428     });
    429     expect(
    430       await page.evaluate(() => window.hcp124Private!.captured())
    431     ).toBeUndefined();
    432     expect(
    433       await page.evaluate(() => window.hcp124Private!.copyCaptured())
    434     ).toBe('stopped');
    435     expect(await page.evaluate(() => window.hcp124Clipboard)).toEqual([]);
    436     expect(await page.evaluate(() => window.hcp124Private!.native())).toEqual(
    437       before
    438     );
    439   });
    440   test('actual signed public listing copies only separately selected version and coordinate', async ({
    441     page
    442   }) => {
    443     await load(page);
    444     publicEvents = await page.evaluate(async () => {
    445       window.hcp124Public = await window.hcp124.createPublicFixture();
    446       return window.hcp124Public.events;
    447     });
    448     await page.evaluate(() => window.hcp124Public!.read());
    449     await expect
    450       .poll(() =>
    451         page.evaluate(() => window.hcp124Public!.publicSnapshot()?.outcome)
    452       )
    453       .toBe('active');
    454     const selected = await page.evaluate(() => window.hcp124Public!.report());
    455     expect(selected?.kind).toBe('listing');
    456     expect(
    457       await panel(page).locator('input[type=checkbox]:checked').count()
    458     ).toBe(0);
    459     await panel(page)
    460       .getByLabel('Share listing version', { exact: true })
    461       .check();
    462     await panel(page)
    463       .getByRole('button', { name: 'Review report', exact: true })
    464       .click();
    465     const text = await panel(page)
    466       .getByRole('region', { name: 'Selected report preview' })
    467       .innerText();
    468     expect(text).toContain((publicEvents[0] as { id: string }).id);
    469     expect(text).not.toContain('Coordinate:');
    470     await panel(page).getByLabel('Share coordinate', { exact: true }).check();
    471     await panel(page)
    472       .getByRole('button', { name: 'Review report', exact: true })
    473       .click();
    474     await expect(
    475       panel(page).getByRole('region', { name: 'Selected report preview' })
    476     ).toContainText('30402:');
    477     expect(events).toEqual([]);
    478   });
    479   for (const width of [320, 1024])
    480     test(
    481       'HCP124 ' +
    482         width +
    483         ' private report selection and disclosure reflow without hidden confirmation',
    484       async ({ page }) => {
    485         await page.setViewportSize({ width, height: 900 });
    486         await privateReport(page);
    487         await panel(page)
    488           .getByLabel('Share message text and ID 1', { exact: true })
    489           .check();
    490         await panel(page)
    491           .getByLabel(
    492             'I understand selected private information will leave HarvestCircle if I share it.',
    493             { exact: true }
    494           )
    495           .check();
    496         await panel(page)
    497           .getByRole('button', { name: 'Review report', exact: true })
    498           .click();
    499         await expect(
    500           panel(page).getByRole('region', { name: 'Selected report preview' })
    501         ).toBeVisible();
    502         expect(
    503           await page.evaluate(
    504             () => document.documentElement.scrollWidth <= window.innerWidth
    505           )
    506         ).toBe(true);
    507         await expect(
    508           panel(page).getByRole('button', {
    509             name: 'Copy reviewed report',
    510             exact: true
    511           })
    512         ).toBeVisible();
    513       }
    514     );
    515 });