app

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

public-hides.spec.ts (17814B)


      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 type { NostrEvent } from 'applesauce-core/helpers';
      8 import { createStaticHarness } from '../integration/harness/static.ts';
      9 import type * as Fixture from './harness/public-hides.ts';
     10 declare global {
     11   interface Window {
     12     hcp122: typeof Fixture;
     13     hcp122Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     14   }
     15 }
     16 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     17   sockets: WebSocketServer,
     18   endpoint: string,
     19   bundle: string | undefined;
     20 let events: NostrEvent[] = [],
     21   effects = 0;
     22 let queries: { authors?: string[]; kinds?: number[] }[] = [];
     23 test.beforeAll(async () => {
     24   server = await createStaticHarness();
     25   sockets = new WebSocketServer({
     26     host: '127.0.0.1',
     27     port: 0,
     28     maxPayload: 262144
     29   });
     30   await once(sockets, 'listening');
     31   const address = sockets.address();
     32   if (!address || typeof address === 'string') throw Error('loopback missing');
     33   endpoint = 'ws://127.0.0.1:' + address.port;
     34   sockets.on('connection', (socket) =>
     35     socket.on('message', (bytes) => {
     36       const raw = Buffer.isBuffer(bytes)
     37         ? bytes
     38         : Array.isArray(bytes)
     39           ? Buffer.concat(bytes)
     40           : Buffer.from(bytes);
     41       const frame = JSON.parse(raw.toString()) as unknown[];
     42       if (frame[0] === 'EVENT' || frame[0] === 'AUTH') {
     43         effects++;
     44         return;
     45       }
     46       if (frame[0] !== 'REQ') return;
     47       const filters = frame.slice(2) as {
     48         authors?: string[];
     49         kinds?: number[];
     50         '#d'?: string[];
     51       }[];
     52       queries.push(...filters);
     53       for (const event of events)
     54         if (
     55           filters.some(
     56             (filter) =>
     57               (!filter.kinds || filter.kinds.includes(event.kind)) &&
     58               (!filter.authors || filter.authors.includes(event.pubkey)) &&
     59               (!filter['#d'] ||
     60                 event.tags.some(
     61                   (tag) => tag[0] === 'd' && filter['#d']!.includes(tag[1])
     62                 ))
     63           )
     64         )
     65           socket.send(JSON.stringify(['EVENT', frame[1], event]));
     66       socket.send(JSON.stringify(['EOSE', frame[1]]));
     67     })
     68   );
     69 });
     70 test.afterAll(async () => {
     71   for (const socket of sockets?.clients ?? []) socket.terminate();
     72   if (sockets)
     73     await new Promise<void>((resolve, reject) =>
     74       sockets.close((error) => (error ? reject(error) : resolve()))
     75     );
     76   await server?.close();
     77 });
     78 test.beforeEach(async ({ page }) => {
     79   events = [];
     80   effects = 0;
     81   queries = [];
     82   await page.addInitScript((endpoint) => {
     83     const Native = window.WebSocket;
     84     window.WebSocket = class extends Native {
     85       constructor(url: string | URL, protocols?: string | string[]) {
     86         if (
     87           !['wss://discovery.example.org', 'wss://inbox.example.org'].includes(
     88             new URL(url.toString()).origin
     89           )
     90         )
     91           throw Error('no live relay permission');
     92         super(endpoint, protocols);
     93       }
     94     };
     95   }, endpoint);
     96 });
     97 test.afterEach(async ({ page }) => {
     98   await page.evaluate(async () => {
     99     await window.hcp122Fixture?.close();
    100   });
    101 });
    102 async function start(page: Page, denied = false, retained = false) {
    103   await page.goto(server.url + '/privacy');
    104   if (!bundle) {
    105     const built = await build({
    106       configFile: false,
    107       plugins: [svelte({ configFile: false })],
    108       resolve: { conditions: ['browser'] },
    109       logLevel: 'silent',
    110       build: {
    111         write: false,
    112         minify: false,
    113         lib: {
    114           entry: fileURLToPath(
    115             new URL('./harness/public-hides.ts', import.meta.url)
    116           ),
    117           name: 'hcp122',
    118           formats: ['iife']
    119         }
    120       }
    121     });
    122     const result = Array.isArray(built) ? built[0] : built;
    123     if (!('output' in result)) throw Error('fixture bundle missing');
    124     const chunks = result.output.filter((row) => row.type === 'chunk');
    125     expect(chunks).toHaveLength(1);
    126     bundle = chunks[0].code;
    127   }
    128   await page.addScriptTag({ content: bundle });
    129   events = await page.evaluate(
    130     async ({ denied, retained }) => {
    131       window.hcp122Fixture = await window.hcp122.createFixture(
    132         denied,
    133         retained
    134       );
    135       return window.hcp122Fixture.events;
    136     },
    137     { denied, retained }
    138   );
    139   await page.evaluate(() => window.hcp122Fixture.render());
    140 }
    141 test('HCP122 SSR privacy states local hide consequences without private inventory', async ({
    142   page
    143 }) => {
    144   await page.goto(server.url + '/privacy');
    145   // Immediate body assertion is a real pre-producer failure, not a future-module collection failure.
    146   expect(await page.locator('main').innerText()).toContain(
    147     'Hiding a publisher is local'
    148   );
    149   await expect(page.getByRole('button', { name: /Undo hide/ })).toHaveCount(0);
    150   expect(queries).toEqual([]);
    151   expect(effects).toBe(0);
    152 });
    153 test('HCP122 acknowledged hide persists native owner data and Undo restores eligible source', async ({
    154   page
    155 }) => {
    156   await start(page);
    157   await expect(page.locator('#hcp122-panel')).toContainText('Visible carrots');
    158   await page
    159     .locator('#hcp122-panel')
    160     .getByRole('button', { name: 'Hide publisher locally', exact: true })
    161     .click();
    162   await expect(page.locator('#hcp122-panel')).toContainText(
    163     'Publisher hidden in this browser'
    164   );
    165   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toHaveLength(
    166     1
    167   );
    168   await page.evaluate(() => window.hcp122Fixture.refresh());
    169   expect(
    170     await page.evaluate(() => window.hcp122Fixture.publicSnapshot())
    171   ).toMatchObject({ outcome: 'unavailable', food: undefined });
    172   const before = queries.length;
    173   await page.evaluate(() => window.hcp122Fixture.read());
    174   expect(queries).toHaveLength(before);
    175   await page
    176     .locator('#hcp122-panel')
    177     .getByRole('button', { name: /Undo hide/ })
    178     .click();
    179   await expect(page.locator('#hcp122-panel')).toContainText('Hide undone');
    180   await page.evaluate(() => window.hcp122Fixture.read());
    181   await expect
    182     .poll(() =>
    183       page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title)
    184     )
    185     .toBe('Visible carrots');
    186   expect(effects).toBe(0);
    187 });
    188 test('HCP122 operator-denied canonical detail emits no head deletion or profile query', async ({
    189   page
    190 }) => {
    191   await start(page, true);
    192   await page.evaluate(() => window.hcp122Fixture.read());
    193   expect(
    194     await page.evaluate(() => window.hcp122Fixture.publicSnapshot())
    195   ).toMatchObject({ outcome: 'unavailable', food: undefined });
    196   expect(queries).toEqual([]);
    197   expect(effects).toBe(0);
    198 });
    199 test('HCP122 broad search excludes verified denied publisher before auxiliary profile lookup', async ({
    200   page
    201 }) => {
    202   await start(page, true);
    203   await page.evaluate(() => window.hcp122Fixture.search());
    204   await expect
    205     .poll(() =>
    206       page.evaluate(() => window.hcp122Fixture.searchSnapshot()?.refresh)
    207     )
    208     .toBe('bounded-eose');
    209   expect(
    210     await page.evaluate(() => window.hcp122Fixture.searchSnapshot()?.listings)
    211   ).toEqual([]);
    212   expect(
    213     queries.some((query) => query.authors?.includes(events[0].pubkey))
    214   ).toBe(false);
    215   expect(effects).toBe(0);
    216 });
    217 test('HCP122 local hide updates an already settled search and Undo restores its eligible row', async ({
    218   page
    219 }) => {
    220   await start(page);
    221   await page.evaluate(() => window.hcp122Fixture.search());
    222   const results = page.locator('#hcp122-panel [data-public-search]');
    223   await expect(results).toContainText('Visible carrots');
    224   await page
    225     .locator('#hcp122-panel')
    226     .getByRole('button', { name: 'Hide publisher locally', exact: true })
    227     .click();
    228   await expect(results).not.toContainText('Visible carrots');
    229   const before = queries.length;
    230   await page
    231     .locator('#hcp122-panel')
    232     .getByRole('button', { name: /Undo hide/ })
    233     .click();
    234   await expect(results).toContainText('Visible carrots');
    235   expect(queries).toHaveLength(before);
    236   expect(effects).toBe(0);
    237 });
    238 test('HCP122 Undo of a retained local hide cannot override operator denial or fetch that publisher', async ({
    239   page
    240 }) => {
    241   await start(page, true);
    242   expect(await page.evaluate(() => window.hcp122Fixture.hide())).toEqual({
    243     status: 'saved'
    244   });
    245   await page
    246     .locator('#hcp122-panel')
    247     .getByRole('button', { name: /Undo hide/ })
    248     .click();
    249   await page.evaluate(() => window.hcp122Fixture.read());
    250   expect(
    251     await page.evaluate(() => window.hcp122Fixture.publicSnapshot())
    252   ).toMatchObject({ outcome: 'unavailable', food: undefined });
    253   expect(queries).toEqual([]);
    254   expect(effects).toBe(0);
    255 });
    256 test('HCP122 detached render publisher cannot authorize local hide or automatic public report', async ({
    257   page
    258 }) => {
    259   await start(page);
    260   expect(await page.evaluate(() => window.hcp122Fixture.fake())).toEqual({
    261     status: 'invalid'
    262   });
    263   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual([]);
    264   expect(effects).toBe(0);
    265 });
    266 test('HCP122 actual account switch retires the old owner inventory without removing stored facts', async ({
    267   page
    268 }) => {
    269   await start(page);
    270   await page.evaluate(() => window.hcp122Fixture.hide());
    271   const before = await page.evaluate(() => window.hcp122Fixture.rows());
    272   await page.evaluate(() => window.hcp122Fixture.switchOwner());
    273   expect(
    274     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    275   ).toEqual({ state: 'guest' });
    276   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual(
    277     before
    278   );
    279   await expect(
    280     page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ })
    281   ).toHaveCount(0);
    282   expect(effects).toBe(0);
    283 });
    284 test('HCP122 hiding an own public source preserves original signed operation and delivery receipts', async ({
    285   page
    286 }) => {
    287   await start(page, false, true);
    288   const before = await page.evaluate(() => window.hcp122Fixture.nativeRecord());
    289   expect(before).toBeDefined();
    290   expect((before as { artifact?: unknown }).artifact).toBeDefined();
    291   await page.evaluate(() => window.hcp122Fixture.hide());
    292   expect(
    293     await page.evaluate(() => window.hcp122Fixture.nativeRecord())
    294   ).toEqual(before);
    295   const own = await page.evaluate(() => window.hcp122Fixture.sellingSnapshot());
    296   expect(own?.attention).toHaveLength(1);
    297   expect(own?.attention[0].provenance).toContain(
    298     'Local publication evidence retained'
    299   );
    300   expect(own?.attention[0].href).toBeUndefined();
    301   expect(effects).toBe(0);
    302 });
    303 test('HCP122 corrupt local preference is retained and never replaced with an empty inventory', async ({
    304   page
    305 }) => {
    306   await start(page);
    307   await page.evaluate(() => window.hcp122Fixture.corrupt());
    308   await page.evaluate(() => window.hcp122Fixture.refresh());
    309   expect(
    310     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    311   ).toEqual({ state: 'unavailable', reason: 'corrupt_record' });
    312   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toHaveLength(
    313     1
    314   );
    315   expect(effects).toBe(0);
    316 });
    317 test('HCP122 actual native transaction abort gives no Saved or empty-data replacement', async ({
    318   page
    319 }) => {
    320   await start(page);
    321   expect(await page.evaluate(() => window.hcp122Fixture.abortWrite())).toEqual({
    322     status: 'aborted'
    323   });
    324   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual([]);
    325   expect(
    326     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    327   ).toMatchObject({ state: 'ready', publishers: [] });
    328   expect(effects).toBe(0);
    329 });
    330 test('HCP122 failed readback after actual write completion stays unknown until explicit native reconciliation', async ({
    331   page
    332 }) => {
    333   await start(page);
    334   expect(
    335     await page.evaluate(() => window.hcp122Fixture.failReadback())
    336   ).toEqual({ status: 'unknown_completion' });
    337   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toHaveLength(
    338     1
    339   );
    340   expect(
    341     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    342   ).toMatchObject({ state: 'ready', publishers: [] });
    343   await page.evaluate(() => window.hcp122Fixture.refresh());
    344   expect(
    345     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    346   ).toMatchObject({ state: 'ready', publishers: [events[0].pubkey] });
    347   expect(effects).toBe(0);
    348 });
    349 test('HCP122 a concurrent full-wire native write causes conflict without overwriting another preference', async ({
    350   page
    351 }) => {
    352   await start(page);
    353   expect(
    354     await page.evaluate(() => window.hcp122Fixture.conflictWrite())
    355   ).toEqual({ status: 'conflict' });
    356   const rows = await page.evaluate(() => window.hcp122Fixture.rows());
    357   expect(rows).toHaveLength(1);
    358   expect(
    359     (JSON.parse((rows[0] as { wire: string }).wire) as { publishers: string[] })
    360       .publishers
    361   ).not.toContain(events[0].pubkey);
    362   expect(effects).toBe(0);
    363 });
    364 test('HCP122 denied storage leaves browse-only with honest unconfirmed preferences', async ({
    365   page
    366 }) => {
    367   await start(page);
    368   expect(await page.evaluate(() => window.hcp122Fixture.denyStorage())).toEqual(
    369     { state: 'unavailable', reason: 'unavailable' }
    370   );
    371   await expect(page.locator('#hcp122-panel')).toContainText(
    372     'previous hides are unconfirmed'
    373   );
    374   await expect(
    375     page
    376       .locator('#hcp122-panel')
    377       .getByRole('button', { name: 'Hide publisher locally', exact: true })
    378   ).toHaveCount(0);
    379   expect(effects).toBe(0);
    380 });
    381 test('HCP122 original generation is revoked after same-author reconnect and new custody reopens exact facts', async ({
    382   page
    383 }) => {
    384   await start(page);
    385   await page.evaluate(() => window.hcp122Fixture.hide());
    386   const before = await page.evaluate(() => window.hcp122Fixture.rows());
    387   expect(await page.evaluate(() => window.hcp122Fixture.reconnect())).toEqual({
    388     status: 'stopped'
    389   });
    390   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual(
    391     before
    392   );
    393   expect(
    394     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    395   ).toMatchObject({ state: 'ready', publishers: [events[0].pubkey] });
    396   expect(effects).toBe(0);
    397 });
    398 for (const width of [320, 1024])
    399   test(`HCP122 ${width}px local hide and Undo are separately visible and operable`, async ({
    400     page
    401   }) => {
    402     await page.setViewportSize({ width, height: 800 });
    403     await start(page);
    404     await page
    405       .locator('#hcp122-panel')
    406       .getByRole('button', { name: 'Hide publisher locally', exact: true })
    407       .click();
    408     await expect(
    409       page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ })
    410     ).toBeVisible();
    411     expect(
    412       await page.evaluate(
    413         () => document.documentElement.scrollWidth > window.innerWidth
    414       )
    415     ).toBe(false);
    416     expect(effects).toBe(0);
    417   });
    418 
    419 test('HCP122 existing hide reconciles the complete native row changed by another controller', async ({
    420   page
    421 }) => {
    422   await start(page);
    423   await expect
    424     .poll(() =>
    425       page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title)
    426     )
    427     .toBe('Visible carrots');
    428   await page.evaluate(() => window.hcp122Fixture.search());
    429   await expect(page.locator('[data-public-search]')).toContainText(
    430     'Visible carrots'
    431   );
    432   const before = await page.evaluate(() =>
    433     window.hcp122Fixture.hidesSnapshot()
    434   );
    435   expect(before).toMatchObject({ state: 'ready', revision: 0, publishers: [] });
    436   const concurrent = await page.evaluate(() =>
    437     window.hcp122Fixture.concurrentPreference(true)
    438   );
    439   expect(
    440     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    441   ).toEqual(before);
    442   expect(await page.evaluate(() => window.hcp122Fixture.hide())).toEqual({
    443     status: 'existing'
    444   });
    445   // Immediate actual-state assertion gives a real regression, without waiting for a UI deadline.
    446   expect(
    447     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    448   ).toEqual(concurrent.snapshot);
    449   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual(
    450     concurrent.rows
    451   );
    452   expect(concurrent.snapshot).toMatchObject({ state: 'ready', revision: 2 });
    453   await expect(
    454     page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ })
    455   ).toHaveCount(2);
    456   await expect(page.locator('[data-public-search]')).not.toContainText(
    457     'Visible carrots'
    458   );
    459   expect(
    460     await page.evaluate(() => window.hcp122Fixture.publicSnapshot())
    461   ).toMatchObject({ outcome: 'unavailable', food: undefined });
    462   expect(effects).toBe(0);
    463 });
    464 test('HCP122 existing Undo reconciles the full native row while preserving an unrelated hide', async ({
    465   page
    466 }) => {
    467   await start(page);
    468   await expect
    469     .poll(() =>
    470       page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title)
    471     )
    472     .toBe('Visible carrots');
    473   expect(await page.evaluate(() => window.hcp122Fixture.hide())).toEqual({
    474     status: 'saved'
    475   });
    476   const before = await page.evaluate(() =>
    477     window.hcp122Fixture.hidesSnapshot()
    478   );
    479   const concurrent = await page.evaluate(() =>
    480     window.hcp122Fixture.concurrentPreference(false)
    481   );
    482   expect(
    483     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    484   ).toEqual(before);
    485   expect(await page.evaluate(() => window.hcp122Fixture.undo())).toEqual({
    486     status: 'existing'
    487   });
    488   expect(
    489     await page.evaluate(() => window.hcp122Fixture.hidesSnapshot())
    490   ).toEqual(concurrent.snapshot);
    491   expect(await page.evaluate(() => window.hcp122Fixture.rows())).toEqual(
    492     concurrent.rows
    493   );
    494   expect(concurrent.snapshot).toMatchObject({ state: 'ready', revision: 3 });
    495   await expect(
    496     page.locator('#hcp122-panel').getByRole('button', { name: /Undo hide/ })
    497   ).toHaveCount(1);
    498   await page.evaluate(() => window.hcp122Fixture.read());
    499   await expect
    500     .poll(() =>
    501       page.evaluate(() => window.hcp122Fixture.publicSnapshot()?.food?.title)
    502     )
    503     .toBe('Visible carrots');
    504   expect(effects).toBe(0);
    505 });