app

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

operation-flags.spec.ts (16685B)


      1 import { expect, test } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { svelte } from '@sveltejs/vite-plugin-svelte';
      4 import { finalizeEvent, getPublicKey } from 'applesauce-core/helpers';
      5 import { fileURLToPath } from 'node:url';
      6 import { once } from 'node:events';
      7 import { WebSocketServer } from 'ws';
      8 import { createStaticHarness } from '../integration/harness/static.ts';
      9 import type * as Fixture from './harness/operation-flags.ts';
     10 declare global {
     11   interface Window {
     12     hcp126: typeof Fixture;
     13   }
     14 }
     15 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     16   sockets: WebSocketServer,
     17   endpoint: string,
     18   bundle: string;
     19 let frames: string[] = [];
     20 const sellerSecret = new Uint8Array(32).fill(84);
     21 const seller = getPublicKey(sellerSecret);
     22 test.beforeAll(async () => {
     23   server = await createStaticHarness();
     24   sockets = new WebSocketServer({
     25     host: '127.0.0.1',
     26     port: 0,
     27     maxPayload: 65536
     28   });
     29   await once(sockets, 'listening');
     30   const address = sockets.address();
     31   if (!address || typeof address === 'string')
     32     throw Error('actual 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.toString()
     38         : Array.isArray(bytes)
     39           ? Buffer.concat(bytes).toString()
     40           : Buffer.from(bytes).toString();
     41       const frame = JSON.parse(raw) as [string, { id: string }];
     42       if (frame[0] === 'REQ') {
     43         const request = JSON.parse(raw) as [
     44           string,
     45           string,
     46           ...{ kinds?: number[]; authors?: string[] }[]
     47         ];
     48         const [, requestId, ...filters] = request;
     49         if (
     50           filters.some(
     51             (f) =>
     52               f.kinds?.includes(30402) &&
     53               (!f.authors || f.authors.includes(seller))
     54           )
     55         ) {
     56           const event = finalizeEvent(
     57             {
     58               kind: 30402,
     59               created_at: 1700000060,
     60               content: 'Signed carrots',
     61               tags: [
     62                 ['d', 'carrots'],
     63                 ['title', 'Verified carrots'],
     64                 ['summary', 'Actual signed listing'],
     65                 ['published_at', '1700000000'],
     66                 ['location', 'Victoria'],
     67                 ['price', '3.5', 'CAD'],
     68                 ['radroots:price_unit', 'lb'],
     69                 ['status', 'active']
     70               ]
     71             },
     72             sellerSecret
     73           );
     74           socket.send(JSON.stringify(['EVENT', requestId, event]));
     75         }
     76         socket.send(JSON.stringify(['EOSE', requestId]));
     77       }
     78 
     79       if (frame[0] === 'EVENT') {
     80         frames.push(raw);
     81         socket.send(JSON.stringify(['OK', frame[1].id, true, '']));
     82       }
     83     })
     84   );
     85   const result = await build({
     86     configFile: false,
     87     plugins: [svelte({ configFile: false })],
     88     resolve: { conditions: ['browser'] },
     89     logLevel: 'silent',
     90     build: {
     91       write: false,
     92       minify: false,
     93       lib: {
     94         entry: fileURLToPath(
     95           new URL('./harness/operation-flags.ts', import.meta.url)
     96         ),
     97         name: 'hcp126',
     98         formats: ['iife']
     99       }
    100     }
    101   });
    102   const output = Array.isArray(result) ? result[0] : result;
    103   if (!('output' in output)) throw Error('actual fixture bundle missing');
    104   const chunks = output.output.filter((x) => x.type === 'chunk');
    105   expect(chunks).toHaveLength(1);
    106   bundle = chunks[0].code;
    107 });
    108 test.afterAll(async () => {
    109   for (const socket of sockets.clients) socket.terminate();
    110   await new Promise<void>((resolve) => sockets.close(() => resolve()));
    111   await server.close();
    112 });
    113 test.beforeEach(async ({ page }) => {
    114   frames = [];
    115   await page.addInitScript(
    116     ({ endpoint }) => {
    117       const Native = window.WebSocket;
    118       window.WebSocket = class extends Native {
    119         constructor(url: string | URL, protocols?: string | string[]) {
    120           if (String(url) !== 'wss://discovery.example.org/')
    121             throw Error('unexpected original fixture destination');
    122           super(endpoint, protocols);
    123         }
    124       };
    125     },
    126     { endpoint }
    127   );
    128   await page.goto(server.url + '/search');
    129   await page.addScriptTag({ content: bundle });
    130 });
    131 test('HCP126 first-level static availability is honest and cannot promise revocation of already-open tabs', async ({
    132   page
    133 }) => {
    134   const actual = await page.locator('body').innerText();
    135   expect(actual).toContain('Posting is disabled in this build.');
    136   await expect(
    137     page.getByText('Posting is disabled in this build.', { exact: true })
    138   ).toBeVisible();
    139   await expect(
    140     page.getByText('Messaging is disabled in this build.', { exact: true })
    141   ).toBeVisible();
    142   await page.getByText('Availability limits', { exact: true }).click();
    143   await expect(
    144     page.getByText(/Static build flags do not instantly stop already-open tabs/)
    145   ).toBeVisible();
    146   await expect(
    147     page.getByText(/Availability flags do not establish full qualification/)
    148   ).toBeVisible();
    149   expect(frames).toHaveLength(0);
    150 });
    151 test('HCP126 messaging-only genuine preference action signs once after native acknowledgment and sends actual kind10050', async ({
    152   page
    153 }) => {
    154   const result = await page.evaluate(async () => {
    155     const s = window.hcp126,
    156       f = await s.makePublisherFixture({
    157         postingEnabled: false,
    158         messagingEnabled: true
    159       });
    160     let database: Parameters<typeof s.closeBrowserDatabase>[0] | undefined;
    161     try {
    162       const policy = f.policy;
    163       if (!policy) throw Error('genuine messaging-only policy missing');
    164       const reviewed = await s.reviewInboxSetup(
    165         f.identity,
    166         f.resolve(),
    167         policy,
    168         s.setupInput(),
    169         () => 101
    170       );
    171       if (reviewed.status !== 'review')
    172         return {
    173           stage: reviewed.status,
    174           reason: reviewed.reason,
    175           signs: f.signs()
    176         };
    177       const opened = await s.openBrowserDatabase();
    178       if (opened.state !== 'ready') throw Error(opened.reason);
    179       database = opened.owner;
    180       const repo = s.createPublicQuotaRepository(database, f.owner);
    181       if (!repo) throw Error('genuine original repo missing');
    182       const id = crypto.randomUUID();
    183       const saved = await s.saveInboxPreferenceOperation(
    184         repo,
    185         reviewed.review,
    186         f.resolve(),
    187         id,
    188         'reviewed_global_inbox_replacement'
    189       );
    190       if (saved.status !== 'saved' && saved.status !== 'existing')
    191         throw Error(saved.status);
    192       const prepared = await s.beginInboxPreferenceOperation(
    193         repo,
    194         f.identity,
    195         policy,
    196         reviewed.review,
    197         id,
    198         () => Promise.resolve(f.resolve()),
    199         'reviewed_global_inbox_replacement'
    200       );
    201       if (prepared.status !== 'prepared')
    202         return { stage: prepared.status, signs: f.signs() };
    203       const trace = s.installEffectTrace();
    204       try {
    205         const delivered = await s.runInboxPreferenceOperation(prepared.action);
    206         const read = await s.loadPreferenceOperation(repo, id);
    207         const row = read.ok && s.publicRecordSnapshot(read.value, f.owner, id);
    208         return {
    209           stage: delivered.status,
    210           signs: f.signs(),
    211           trace: trace.events(),
    212           artifact:
    213             row && row.family === 'preference_operation'
    214               ? row.artifact?.eventId
    215               : undefined
    216         };
    217       } finally {
    218         trace.restore();
    219       }
    220     } finally {
    221       f.close();
    222       if (database) s.closeBrowserDatabase(database);
    223     }
    224   });
    225   expect(result.stage).toBe('completed');
    226   expect(result.signs).toBe(1);
    227   expect(result.trace).toEqual(
    228     expect.arrayContaining(['ack:1', 'ack:2', 'EVENT'])
    229   );
    230   expect(result.trace?.indexOf('ack:1')).toBeLessThan(
    231     result.trace?.indexOf('ack:2') ?? -1
    232   );
    233   expect(result.trace?.indexOf('ack:2')).toBeLessThan(
    234     result.trace?.indexOf('EVENT') ?? -1
    235   );
    236   expect(frames).toHaveLength(1);
    237   const event = (
    238     JSON.parse(frames[0]) as [string, { id: string; kind: number }]
    239   )[1];
    240   expect(event.kind).toBe(10050);
    241   expect(event.id).toBe(result.artifact);
    242 });
    243 
    244 test('HCP126 posting-off stored public recovery remains needs-action with exact native record and no signature or EVENT', async ({
    245   page
    246 }) => {
    247   const result = await page.evaluate(async () => {
    248     const s = window.hcp126,
    249       f = await s.makeStoredPublicFixture(),
    250       identity = s.createIdentitySession();
    251     let db: Parameters<typeof s.closeBrowserDatabase>[0] | undefined;
    252     try {
    253       await s.connectIdentity(identity);
    254       await s.probeIdentityMessaging(identity, 'reviewed_self_copy');
    255       const opened = await s.openBrowserDatabase();
    256       if (opened.state !== 'ready') throw Error(opened.reason);
    257       db = opened.owner;
    258       const repo = s.createPublicPublicationRepository(db, f.owner);
    259       if (!repo) throw Error('genuine stored repo absent');
    260       const off = s.validateRelayPolicy(
    261         JSON.stringify({
    262           ...s.readRelayPolicy(f.policy),
    263           postingEnabled: false,
    264           messagingEnabled: true
    265         })
    266       );
    267       if (!off) throw Error('genuine disabled policy absent');
    268       const before = await f.details();
    269       const action = await s.prepareListingResume(
    270         repo,
    271         identity,
    272         off,
    273         f.command,
    274         'reviewed_stored_listing_resume'
    275       );
    276       const read = await s.readListingOperationView(repo, identity, f.command);
    277       const snapshot =
    278         read.status === 'found'
    279           ? s.listingOperationSnapshot(read.view)
    280           : undefined;
    281       if (read.status === 'found') s.closeListingOperationView(read.view);
    282       const after = await f.details();
    283       return {
    284         status: action.status,
    285         before: before.row,
    286         after: after.row,
    287         signsBefore: before.signs,
    288         signsAfter: after.signs,
    289         snapshot
    290       };
    291     } finally {
    292       if (db) s.closeBrowserDatabase(db);
    293       s.disconnectIdentity(identity);
    294       f.close();
    295     }
    296   });
    297   expect(result.status).toBe('needs_action');
    298   expect(result.after).toEqual(result.before);
    299   expect(result.signsAfter).toBe(result.signsBefore);
    300   expect(result.snapshot).toBeDefined();
    301   expect(frames).toHaveLength(0);
    302 });
    303 test('HCP126 actual uncertain public signing stays visible in this disabled build and is never retried automatically', async ({
    304   page
    305 }) => {
    306   const result = await page.evaluate(async () => {
    307     const f = await window.hcp126.makeUnknownPublicFixture();
    308     try {
    309       await f.holdSigning();
    310       await f.stopSigning();
    311       const before = await f.row(),
    312         counts = f.counts();
    313       const snapshot = await f.renderView();
    314       const after = await f.row();
    315       return { before, after, counts, afterCounts: f.counts(), snapshot };
    316     } finally {
    317       f.close();
    318     }
    319   });
    320   expect(result.after).toEqual(result.before);
    321   expect(result.afterCounts).toEqual(result.counts);
    322   expect(result.snapshot).toMatchObject({ state: 'unknown' });
    323   await expect(
    324     page.getByText('Posting is disabled in this build.', { exact: true })
    325   ).toBeVisible();
    326   expect(frames).toHaveLength(0);
    327 });
    328 test('HCP126 messaging-off denies actual publication while preserving explicitly prepared stored recovery', async ({
    329   page
    330 }) => {
    331   const result = await page.evaluate(async () => {
    332     const s = window.hcp126,
    333       f = await s.makeDisabledPairFixture({ messaging: false });
    334     try {
    335       const self = await s.prepareSelfRecovery(
    336         f.preparation,
    337         'reviewed_self_recovery'
    338       );
    339       if (self.status !== 'saved') throw Error(self.status);
    340       const pair = await s.preparePairedDelivery(
    341         f.preparation,
    342         f.context,
    343         'reviewed_pair_preparation'
    344       );
    345       if (pair.status !== 'prepared') throw Error(pair.status);
    346       const session = await s.createPrivateSession(
    347         f.identity,
    348         'reviewed_private_session'
    349       );
    350       if (!session) throw Error('genuine retained private session missing');
    351       const before = await f.stored(),
    352         counts = f.counts();
    353       let disabled = false;
    354       try {
    355         const pool = s.getPrivatePool(session, f.context.policy, [
    356           'wss://peer.example.org',
    357           'wss://archive.example.org'
    358         ]);
    359         if (pool) s.closePrivatePool(pool);
    360       } catch (error) {
    361         if (
    362           !(error instanceof Error) ||
    363           error.message !== 'private_pool_disabled'
    364         )
    365           throw error;
    366         disabled = true;
    367       } finally {
    368         s.closePrivateSession(session);
    369       }
    370       return {
    371         disabled,
    372         before,
    373         after: await f.stored(),
    374         counts,
    375         afterCounts: f.counts()
    376       };
    377     } finally {
    378       f.close();
    379     }
    380   });
    381   expect(result.disabled).toBe(true);
    382   expect(result.after).toEqual(result.before);
    383   expect(result.afterCounts).toEqual(result.counts);
    384   expect(frames).toHaveLength(0);
    385 });
    386 test('HCP126 messaging-off original product request keeps unsaved text and denies actual Send before any effect', async ({
    387   page
    388 }) => {
    389   const result = await page.evaluate(async (seller) => {
    390     const s = window.hcp126,
    391       f = await s.makeSetupFixture(),
    392       context = s.createPublicRuntimeContext(),
    393       policy = s.fixturePolicy({
    394         postingEnabled: true,
    395         messagingEnabled: false
    396       });
    397     const runtime = s.mountPublicRuntime(context, policy);
    398     if (!runtime) throw Error('genuine runtime absent');
    399     const address = s.encodeProductReference({
    400       kind: 30402,
    401       pubkey: seller,
    402       identifier: 'carrots'
    403     });
    404     if (!address) throw Error('original coordinate absent');
    405     let settled = () => {};
    406     const observed = new Promise<void>((resolve) => {
    407       settled = resolve;
    408     });
    409     const view = s.createProductView(
    410       s.createPublicView(runtime),
    411       address,
    412       { nowSeconds: () => 1700000200 },
    413       (snapshot) => {
    414         if (snapshot.outcome === 'active') settled();
    415       }
    416     );
    417     let setup: ReturnType<typeof s.createInboxSetupView>,
    418       controller: ReturnType<typeof s.createProductRequestController>;
    419     try {
    420       // Await the original bounded resolver's actual completed SDK request, not a fabricated listing.
    421       if (s.productViewSnapshot(view).outcome !== 'active') await observed;
    422       const acknowledgement = s.acknowledgeProductViewUncertainty(
    423         view,
    424         'reviewed_last_known_listing'
    425       );
    426       const draft = s.captureProductEnquiry(
    427         view,
    428         'reviewed_product_enquiry',
    429         acknowledgement
    430       );
    431       if (!draft)
    432         throw Error(
    433           'genuine verified product enquiry absent: ' +
    434             s.productViewSnapshot(view).outcome
    435         );
    436       setup = s.createInboxSetupView({
    437         identity: f.identity,
    438         policy,
    439         lookup: () => Promise.resolve(f.own.resolver)
    440       });
    441       if (!setup) throw Error('genuine original setup absent');
    442       controller = s.createProductRequestController(draft, runtime);
    443       if (
    444         !controller ||
    445         !s.configureProductRequest(
    446           controller,
    447           f.identity,
    448           setup,
    449           'reviewed_product_request_setup'
    450         )
    451       )
    452         throw Error('genuine request owner absent');
    453       const text = 'HCP126 preserve my unsaved memory text';
    454       if (
    455         !s.updateProductRequestText(controller, text, 'reviewed_private_text')
    456       )
    457         throw Error('original text update absent');
    458       let encrypts = 0;
    459       const provider = window.nostr as {
    460         nip44: { encrypt: (...args: unknown[]) => unknown };
    461       };
    462       const originalEncrypt = provider.nip44.encrypt;
    463       provider.nip44.encrypt = (...args: unknown[]) => {
    464         encrypts++;
    465         return Reflect.apply(originalEncrypt, provider.nip44, args);
    466       };
    467       const counts = f.counts();
    468       const delivered = await s.sendProductRequest(
    469         controller,
    470         'reviewed_product_request_send'
    471       );
    472       return {
    473         status: delivered.status,
    474         text: s.productRequestText(controller),
    475         snapshot: s.productRequestSnapshot(controller),
    476         counts,
    477         afterCounts: f.counts(),
    478         encrypts
    479       };
    480     } finally {
    481       if (controller) s.closeProductRequestController(controller);
    482       if (setup) s.closeInboxSetupView(setup);
    483       s.closeProductView(view);
    484       s.closePublicRuntime(context);
    485       f.close();
    486     }
    487   }, seller);
    488   expect(result.status).toBe('needs_action');
    489   expect(result.text).toBe('HCP126 preserve my unsaved memory text');
    490   expect(result.snapshot).toMatchObject({ readyToSend: false, dirty: true });
    491   expect(result.encrypts).toBe(0);
    492   expect(result.afterCounts).toEqual(result.counts);
    493   expect(frames).toHaveLength(0);
    494 });