app

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

withdraw-listing.spec.ts (18673B)


      1 import { expect, test } 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 { writeFile } from 'node:fs/promises';
      7 import { WebSocketServer } from 'ws';
      8 import { createStaticHarness } from '../integration/harness/static.ts';
      9 import type * as Fixture from './harness/withdraw-listing.ts';
     10 import type { NostrEvent } from 'applesauce-core/helpers';
     11 declare global {
     12   interface Window {
     13     hcp120: typeof Fixture;
     14     hcp120Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     15     hcp120Second: Awaited<ReturnType<typeof Fixture.openSecondEditor>>;
     16     hcp120OriginalSign(input: Fixture.ControlledSignInput): Promise<NostrEvent>;
     17   }
     18 }
     19 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     20   sockets: WebSocketServer,
     21   endpoint: string,
     22   bundle: string;
     23 let event: NostrEvent | undefined,
     24   partial = false,
     25   effects: NostrEvent[] = [],
     26   retained: NostrEvent[] = [],
     27   holdAck = false;
     28 let tabs: import('@playwright/test').Page[] = [];
     29 test.beforeAll(async () => {
     30   server = await createStaticHarness();
     31   sockets = new WebSocketServer({
     32     host: '127.0.0.1',
     33     port: 0,
     34     maxPayload: 262144
     35   });
     36   await once(sockets, 'listening');
     37   const address = sockets.address();
     38   if (!address || typeof address === 'string') throw Error('loopback missing');
     39   endpoint = 'ws://127.0.0.1:' + address.port;
     40   sockets.on('connection', (socket) =>
     41     socket.on('message', (bytes) => {
     42       const raw = Buffer.isBuffer(bytes)
     43         ? bytes
     44         : Array.isArray(bytes)
     45           ? Buffer.concat(bytes)
     46           : Buffer.from(bytes);
     47       const frame = JSON.parse(raw.toString()) as unknown[];
     48       if (frame[0] === 'EVENT') {
     49         event = frame[1] as NostrEvent;
     50         effects.push(event);
     51         retained.push(event);
     52         if (!holdAck) socket.send(JSON.stringify(['OK', event.id, true, '']));
     53         return;
     54       }
     55       if (frame[0] !== 'REQ') return;
     56       const filters = frame.slice(2) as {
     57         kinds?: number[];
     58         ids?: string[];
     59         authors?: string[];
     60         '#d'?: string[];
     61         '#e'?: string[];
     62         '#a'?: string[];
     63       }[];
     64       for (const actual of retained)
     65         if (
     66           filters.some(
     67             (filter) =>
     68               (!filter.kinds || filter.kinds.includes(actual.kind)) &&
     69               (!filter.ids || filter.ids.includes(actual.id)) &&
     70               (!filter.authors || filter.authors.includes(actual.pubkey)) &&
     71               (['#d', '#e', '#a'] as const).every(
     72                 (key) =>
     73                   !filter[key] ||
     74                   actual.tags.some(
     75                     (tag) =>
     76                       tag[0] === key.slice(1) && filter[key]!.includes(tag[1])
     77                   )
     78               )
     79           )
     80         )
     81           socket.send(JSON.stringify(['EVENT', frame[1], actual]));
     82       if (!(partial && filters.some((filter) => filter.kinds?.includes(5))))
     83         socket.send(JSON.stringify(['EOSE', frame[1]]));
     84     })
     85   );
     86   const built = await build({
     87     configFile: false,
     88     plugins: [svelte({ configFile: false })],
     89     resolve: { conditions: ['browser'] },
     90     logLevel: 'silent',
     91     build: {
     92       write: false,
     93       minify: false,
     94       lib: {
     95         entry: fileURLToPath(
     96           new URL('./harness/withdraw-listing.ts', import.meta.url)
     97         ),
     98         name: 'hcp120',
     99         formats: ['iife']
    100       }
    101     }
    102   });
    103   const result = Array.isArray(built) ? built[0] : built;
    104   if (!('output' in result)) throw Error('actual fixture bundle missing');
    105   const chunks = result.output.filter((row) => row.type === 'chunk');
    106   expect(chunks).toHaveLength(1);
    107   bundle = chunks[0].code;
    108 });
    109 test.afterAll(async () => {
    110   for (const socket of sockets?.clients ?? []) socket.terminate();
    111   if (sockets)
    112     await new Promise<void>((resolve, reject) =>
    113       sockets.close((error) => (error ? reject(error) : resolve()))
    114     );
    115   await server?.close();
    116 });
    117 test.beforeEach(async ({ page }) => {
    118   tabs = [];
    119   event = undefined;
    120   partial = false;
    121   effects = [];
    122   retained = [];
    123   holdAck = false;
    124   await page.addInitScript((endpoint) => {
    125     const Native = window.WebSocket;
    126     window.WebSocket = class extends Native {
    127       constructor(url: string | URL, protocols?: string | string[]) {
    128         if (
    129           ![
    130             'wss://discovery.example.org',
    131             'wss://inbox.example.org',
    132             'wss://second.example.org'
    133           ].includes(new URL(url.toString()).origin)
    134         )
    135           throw Error('no live relay permission');
    136         super(endpoint, protocols);
    137       }
    138     };
    139   }, endpoint);
    140   await page.goto(server.url + '/search');
    141   await page.addScriptTag({ content: bundle });
    142   event = await page.evaluate(async () => {
    143     window.hcp120Fixture = await window.hcp120.createFixture();
    144     return window.hcp120Fixture.event;
    145   });
    146   retained.push(event);
    147 });
    148 test.afterEach(async ({ page }) => {
    149   await page.evaluate(async () => {
    150     await window.hcp120Second?.close();
    151   });
    152   for (const tab of tabs) {
    153     if (!tab.isClosed()) {
    154       await tab.evaluate(async () => {
    155         await window.hcp120Second?.close();
    156       });
    157       await tab.close();
    158     }
    159   }
    160   await page.evaluate(async () => {
    161     await window.hcp120Fixture?.close();
    162   });
    163 });
    164 async function editor(page: import('@playwright/test').Page) {
    165   await page.evaluate(() => window.hcp120Fixture.renderEditor());
    166   await expect(page.locator('#listing-title')).not.toHaveAttribute(
    167     'readonly',
    168     ''
    169   );
    170 }
    171 async function secondEditorPage(
    172   page: import('@playwright/test').Page,
    173   naddr: string
    174 ) {
    175   const tab = await page.context().newPage();
    176   tabs.push(tab);
    177   const owner = await page.evaluate(() => window.hcp120Fixture.owner);
    178   await tab.exposeFunction(
    179     'hcp120OriginalSign',
    180     async (input: Fixture.ControlledSignInput) =>
    181       await page.evaluate(
    182         (input) => window.hcp120Fixture.signOriginal(input),
    183         input
    184       )
    185   );
    186   await tab.addInitScript(
    187     ({ endpoint, owner }) => {
    188       const Native = window.WebSocket;
    189       window.WebSocket = class extends Native {
    190         constructor(url: string | URL, protocols?: string | string[]) {
    191           if (
    192             ![
    193               'wss://discovery.example.org',
    194               'wss://inbox.example.org',
    195               'wss://second.example.org'
    196             ].includes(new URL(url.toString()).origin)
    197           )
    198             throw Error('no live relay permission');
    199           super(endpoint, protocols);
    200         }
    201       };
    202       Object.defineProperty(window, 'nostr', {
    203         configurable: true,
    204         value: {
    205           getPublicKey: () => Promise.resolve(owner),
    206           signEvent: (input: Fixture.ControlledSignInput) =>
    207             window.hcp120OriginalSign(input)
    208         }
    209       });
    210     },
    211     { endpoint, owner }
    212   );
    213   await tab.goto(server.url + '/search');
    214   await tab.addScriptTag({ content: bundle });
    215   await tab.evaluate(
    216     async ({ owner, naddr }) => {
    217       window.hcp120Second = await window.hcp120.openSecondEditor(owner, naddr);
    218     },
    219     { owner, naddr }
    220   );
    221   return tab;
    222 }
    223 
    224 async function removalReview(page: import('@playwright/test').Page) {
    225   await editor(page);
    226   await page.getByText('Other listing actions', { exact: true }).click();
    227   const removal = page.getByRole('button', {
    228     name: 'Request removal',
    229     exact: true
    230   });
    231   // Count is an immediate DOM observation: a missing future action fails this
    232   // body without making isEnabled wait for an element that does not exist.
    233   expect(await removal.count()).toBe(1);
    234   expect(await removal.isEnabled()).toBe(true);
    235   await removal.click();
    236   await expect(
    237     page.getByRole('region', { name: 'Confirm removal request' })
    238   ).toContainText('cannot erase all other copies');
    239   await page
    240     .getByRole('button', { name: 'Review removal request', exact: true })
    241     .click();
    242   await expect(
    243     page.getByRole('region', { name: 'Public listing review' })
    244   ).toContainText('Removal request');
    245 }
    246 test('HCP120 separate consequence confirmation and full removal review perform no sign capture or send', async ({
    247   page
    248 }) => {
    249   const before = await page.evaluate(() => window.hcp120Fixture.counts());
    250   await removalReview(page);
    251   const region = page.getByRole('region', { name: 'Public listing review' });
    252   await expect(region).toContainText(
    253     await page.evaluate(() => window.hcp120Fixture.naddr)
    254   );
    255   await expect(region).toContainText('cannot erase all other copies');
    256   expect(await page.evaluate(() => window.hcp120Fixture.counts())).toEqual(
    257     before
    258   );
    259   expect(
    260     await page.evaluate(() => window.hcp120Fixture.operations())
    261   ).toHaveLength(1);
    262   expect(effects).toHaveLength(0);
    263 });
    264 test('HCP120 explicit removal persists distinct same-author kind5 and delivery independently of suppressed listing', async ({
    265   page
    266 }) => {
    267   const base = await page.evaluate(() => window.hcp120Fixture.event);
    268   const signs = await page.evaluate(() => window.hcp120Fixture.counts().signs);
    269   await removalReview(page);
    270   await page
    271     .getByRole('button', { name: 'Publish removal request', exact: true })
    272     .click();
    273   await expect.poll(() => effects.length).toBeGreaterThan(0);
    274   await expect
    275     .poll(
    276       async () =>
    277         (await page.evaluate(() => window.hcp120Fixture.operations()))
    278           .find((row) => row.capture.kind === 5)
    279           ?.receipts.filter((fact) => fact.readbackWire !== null).length ?? 0
    280     )
    281     .toBe(1);
    282   const rows = await page.evaluate(() => window.hcp120Fixture.operations());
    283   expect(rows).toHaveLength(2);
    284   const removal = rows.find((row) => row.capture.kind === 5)!;
    285   expect(removal.source).toEqual({
    286     type: 'public_head',
    287     wire: JSON.stringify(base)
    288   });
    289   expect(removal.capture.targets).toEqual(['wss://discovery.example.org']);
    290   const signed = JSON.parse(removal.artifact!.wire) as NostrEvent;
    291   expect(signed.kind).toBe(5);
    292   expect(signed.pubkey).toBe(base.pubkey);
    293   expect(signed.tags).toEqual([
    294     ['e', base.id],
    295     [
    296       'a',
    297       `30402:${base.pubkey}:${base.tags.find((tag) => tag[0] === 'd')![1]}`
    298     ],
    299     ['k', '30402']
    300   ]);
    301   expect(signed.created_at).toBeGreaterThanOrEqual(base.created_at);
    302   expect(signed.created_at - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(
    303     300
    304   );
    305   expect(
    306     effects.every((actual) => actual.id === signed.id && actual.kind === 5)
    307   ).toBe(true);
    308   expect(await page.evaluate(() => window.hcp120Fixture.counts().signs)).toBe(
    309     signs + 1
    310   );
    311   expect(
    312     rows.find((row) => row.artifact?.eventId === base.id)?.artifact?.wire
    313   ).toBe(JSON.stringify(base));
    314   await expect(
    315     page.getByText('Exact read-back recorded for 1 of 1 targets.', {
    316       exact: true
    317     })
    318   ).toBeVisible();
    319   await page.evaluate(() => window.hcp120Fixture.open());
    320   await expect
    321     .poll(() => page.evaluate(() => window.hcp120Fixture.snapshot()?.status))
    322     .toBe('withdrawn');
    323   const after = await page.evaluate(() => window.hcp120Fixture.operations());
    324   expect(after.find((row) => row.capture.kind === 5)).toEqual(removal);
    325   await writeFile(
    326     test.info().outputPath('actual-retained-removal-operation.json'),
    327     JSON.stringify(removal)
    328   );
    329 });
    330 test('HCP120 cancel removal confirmation preserves exact proposal with no effect', async ({
    331   page
    332 }) => {
    333   await editor(page);
    334   await page.locator('#listing-title').fill('Keep my local proposed carrots');
    335   const before = await page.evaluate(() => window.hcp120Fixture.counts());
    336   await page.getByText('Other listing actions', { exact: true }).click();
    337   expect(
    338     await page
    339       .getByRole('button', { name: 'Request removal', exact: true })
    340       .isEnabled()
    341   ).toBe(true);
    342   await page
    343     .getByRole('button', { name: 'Request removal', exact: true })
    344     .click();
    345   await page.getByRole('button', { name: 'Keep editing', exact: true }).click();
    346   await expect(page.locator('#listing-title')).toHaveValue(
    347     'Keep my local proposed carrots'
    348   );
    349   expect(await page.evaluate(() => window.hcp120Fixture.counts())).toEqual(
    350     before
    351   );
    352   expect(effects).toHaveLength(0);
    353 });
    354 test('HCP120 wrong author source cannot expose a removal signing path', async ({
    355   page
    356 }) => {
    357   const before = await page.evaluate(() => window.hcp120Fixture.counts().signs);
    358   expect(
    359     await page.evaluate(() =>
    360       window.hcp120Fixture.open(false, window.hcp120Fixture.foreign())
    361     )
    362   ).toBeUndefined();
    363   const tab = await secondEditorPage(
    364     page,
    365     await page.evaluate(() => window.hcp120Fixture.foreign())
    366   );
    367   await expect(tab.locator('#hcp119-second')).toContainText(
    368     'Supported local listing values are not available for editing'
    369   );
    370   await expect(
    371     tab
    372       .locator('#hcp119-second')
    373       .getByRole('button', { name: 'Request removal', exact: true })
    374   ).toHaveCount(0);
    375   expect(await page.evaluate(() => window.hcp120Fixture.counts().signs)).toBe(
    376     before
    377   );
    378   expect(effects).toHaveLength(0);
    379 });
    380 test('HCP120 incomplete deletion coverage cannot authorize withdrawal', async ({
    381   page
    382 }) => {
    383   partial = true;
    384   await page.evaluate(() => window.hcp120Fixture.renderEditor());
    385   await expect(page.locator('#listing-title')).toHaveAttribute('readonly', '');
    386   await expect(
    387     page.getByRole('button', { name: 'Request removal', exact: true })
    388   ).toHaveCount(0);
    389   expect(effects).toHaveLength(0);
    390 });
    391 test('HCP120 independently competing head fences an already reviewed deletion without replacing proposal', async ({
    392   page
    393 }) => {
    394   await removalReview(page);
    395   event = await page.evaluate(() => window.hcp120Fixture.competing());
    396   retained.push(event);
    397   const before = await page.evaluate(() => window.hcp120Fixture.counts().signs);
    398   await page.evaluate(() => window.hcp120Fixture.lookupAgain());
    399   await expect(
    400     page.getByRole('button', { name: 'Publish removal request', exact: true })
    401   ).toHaveCount(0);
    402   expect(await page.evaluate(() => window.hcp120Fixture.counts().signs)).toBe(
    403     before
    404   );
    405   expect(effects).toHaveLength(0);
    406 });
    407 test('HCP120 Stop prevents more attempts and never retracts an already sent kind5', async ({
    408   page
    409 }) => {
    410   holdAck = true;
    411   await removalReview(page);
    412   await page
    413     .getByRole('button', { name: 'Publish removal request', exact: true })
    414     .click();
    415   await expect.poll(() => effects.length).toBe(1);
    416   const sent = effects[0];
    417   expect(sent.kind).toBe(5);
    418   await page
    419     .getByRole('button', { name: 'Stop current action', exact: true })
    420     .click();
    421   await expect(
    422     page.getByRole('button', {
    423       name: 'Publishing removal request',
    424       exact: true
    425     })
    426   ).toHaveCount(0);
    427   expect(effects).toEqual([sent]);
    428   const rows = await page.evaluate(() => window.hcp120Fixture.operations());
    429   expect(rows.find((row) => row.capture.kind === 5)?.artifact?.wire).toBe(
    430     JSON.stringify(sent)
    431   );
    432   expect(
    433     rows
    434       .find((row) => row.capture.kind === 5)
    435       ?.receipts.some((fact) => fact.status === 'accepted')
    436   ).toBe(false);
    437 });
    438 for (const width of [320, 1024])
    439   test(`HCP120 ${width}px reviewed removal is readable without raw message deletion`, async ({
    440     page
    441   }) => {
    442     await page.setViewportSize({ width, height: 900 });
    443     await removalReview(page);
    444     expect(
    445       await page.evaluate(
    446         () => document.documentElement.scrollWidth <= innerWidth
    447       )
    448     ).toBe(true);
    449     await expect(
    450       page.getByRole('button', { name: /Delete message|Delete conversation/ })
    451     ).toHaveCount(0);
    452     expect(effects).toHaveLength(0);
    453   });
    454 
    455 for (const first of ['revision', 'withdrawal'] as const)
    456   test(`HCP120 native unresolved ${first} capture fences the other original review`, async ({
    457     page
    458   }) => {
    459     await editor(page);
    460     const tab = await secondEditorPage(
    461       page,
    462       await page.evaluate(() => window.hcp120Fixture.naddr)
    463     );
    464     const second = tab.locator('#hcp119-second');
    465     await expect(second.locator('#listing-title')).not.toHaveAttribute(
    466       'readonly',
    467       ''
    468     );
    469     const primary = page.locator('#hcp118-conflict');
    470     const removal = first === 'withdrawal' ? primary : second;
    471     const revision = first === 'revision' ? primary : second;
    472     await removal.getByText('Other listing actions', { exact: true }).click();
    473     await removal
    474       .getByRole('button', { name: 'Request removal', exact: true })
    475       .click();
    476     await removal
    477       .getByRole('button', { name: 'Review removal request', exact: true })
    478       .click();
    479     await expect(
    480       removal.getByRole('region', { name: 'Public listing review' })
    481     ).toContainText('Removal request');
    482     await revision
    483       .locator('#listing-title')
    484       .fill('Concurrent proposed carrots');
    485     await revision
    486       .getByRole('button', { name: 'Review changes', exact: true })
    487       .click();
    488     await expect(
    489       revision.getByRole('region', { name: 'Public listing review' })
    490     ).toContainText('Concurrent proposed carrots');
    491     await page.evaluate(() => window.hcp120Fixture.refuseNextSignature());
    492     const firstScope = first === 'withdrawal' ? removal : revision;
    493     const firstLabel =
    494       first === 'withdrawal' ? 'Publish removal request' : 'Publish changes';
    495     await firstScope
    496       .getByRole('button', { name: firstLabel, exact: true })
    497       .click();
    498     await expect
    499       .poll(() => page.evaluate(() => window.hcp120Fixture.signRequests()))
    500       .toBe(1);
    501     await expect(
    502       firstScope.getByRole('button', { name: /^Publishing/ })
    503     ).toHaveCount(0);
    504     const before = await page.evaluate(() => window.hcp120Fixture.operations());
    505     expect(before).toHaveLength(2);
    506     expect(before.find((row) => row.artifact === null)?.capture.kind).toBe(
    507       first === 'withdrawal' ? 5 : 30402
    508     );
    509     const otherScope = first === 'withdrawal' ? revision : removal;
    510     await otherScope
    511       .getByRole('button', {
    512         name:
    513           first === 'withdrawal'
    514             ? 'Publish changes'
    515             : 'Publish removal request',
    516         exact: true
    517       })
    518       .click();
    519     await expect(
    520       otherScope.getByText(
    521         'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.',
    522         { exact: true }
    523       )
    524     ).toBeVisible();
    525     await expect(
    526       otherScope.getByRole('button', { name: /^Publishing/ })
    527     ).toHaveCount(0);
    528     expect(
    529       await page.evaluate(() => window.hcp120Fixture.operations())
    530     ).toEqual(before);
    531     expect(await page.evaluate(() => window.hcp120Fixture.signRequests())).toBe(
    532       1
    533     );
    534     expect(effects).toHaveLength(0);
    535     await writeFile(
    536       test.info().outputPath('actual-native-competing-capture.json'),
    537       JSON.stringify(before)
    538     );
    539   });