app

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

approved-signing.spec.ts (7904B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { createHash } from 'node:crypto';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 import type * as Signing from './harness/approved-signing.ts';
      7 import type { ApprovedPublicSigning } from '../../src/lib/nostr/approved-signing.ts';
      8 import type {
      9   ExtensionAdapter,
     10   ApprovedSignResult
     11 } from '../../src/lib/nostr/extension.ts';
     12 declare global {
     13   interface Window {
     14     hcp053: typeof Signing;
     15     hcp053Fixture: ReturnType<typeof Signing.makeFixture>;
     16     hcp053Adapter: ExtensionAdapter;
     17     hcp053Approval: ApprovedPublicSigning;
     18     hcp053Mode: Signing.Mode;
     19     hcp053Calls: string[];
     20     hcp053Release: () => void;
     21     hcp053Task: Promise<ApprovedSignResult>;
     22   }
     23 }
     24 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
     25 test.beforeAll(async () => {
     26   server = await createStaticHarness();
     27   const result = await build({
     28     configFile: false,
     29     logLevel: 'silent',
     30     build: {
     31       write: false,
     32       minify: false,
     33       lib: {
     34         entry: fileURLToPath(
     35           new URL('./harness/approved-signing.ts', import.meta.url)
     36         ),
     37         name: 'hcp053',
     38         formats: ['iife']
     39       }
     40     }
     41   });
     42   const output = Array.isArray(result) ? result[0] : result;
     43   if (!('output' in output)) throw new Error('missing bundle');
     44   const chunks = output.output.filter((item) => item.type === 'chunk');
     45   expect(chunks).toHaveLength(1);
     46   const moduleIds = Object.keys(chunks[0].modules);
     47   expect(moduleIds.some((id) => id.includes('extension-signer'))).toBe(true);
     48   expect(
     49     moduleIds.filter((id) =>
     50       /\/(?:private-key-signer|password-signer|nostr-connect-signer)\.[cm]?[jt]s(?:$|\?)/.test(
     51         id
     52       )
     53     )
     54   ).toEqual([]);
     55   bundle = chunks[0].code;
     56   console.log(
     57     JSON.stringify({
     58       fixture: 'HCP053_CONTROLLED_PROVIDER_ACTUAL_SDK_CRYPTO',
     59       moduleIds,
     60       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
     61       claim:
     62         'controlled provider source evidence only, no real extension qualification'
     63     })
     64   );
     65 });
     66 test.afterAll(async () => server.close());
     67 async function load(page: Page) {
     68   await page.goto(server.url);
     69   await page.addScriptTag({ content: bundle });
     70   await page.evaluate(async () => {
     71     const s = window.hcp053,
     72       f = s.makeFixture();
     73     window.hcp053Fixture = f;
     74     window.hcp053Mode = 'exact';
     75     window.hcp053Calls = [];
     76     window.nostr = {
     77       getPublicKey: () => {
     78         window.hcp053Calls.push('key');
     79         return Promise.resolve(f.owner);
     80       },
     81       signEvent: (template: Parameters<typeof f.sign>[0]) => {
     82         window.hcp053Calls.push('sign');
     83         return Promise.resolve(f.sign(template, window.hcp053Mode));
     84       }
     85     };
     86     window.hcp053Adapter = s.createExtensionAdapter();
     87     await s.connectExtensionAdapter(window.hcp053Adapter);
     88     const a = s.approveCapturedPublicSigning(
     89       f.record,
     90       f.owner,
     91       f.id,
     92       'reviewed_captured_operation'
     93     );
     94     if (!a) throw new Error('missing fixture approval');
     95     window.hcp053Approval = a;
     96     window.hcp053Calls = [];
     97   });
     98 }
     99 test.afterEach(async ({ page }) => {
    100   await page.evaluate(() => window.hcp053Fixture?.close());
    101 });
    102 test('exact actual SDK response returns immutable artifact and never publishes/stores', async ({
    103   page
    104 }) => {
    105   await load(page);
    106   const value = await page.evaluate(async () => {
    107     const s = window.hcp053,
    108       result = await s.signApprovedExtensionAdapter(
    109         window.hcp053Adapter,
    110         window.hcp053Approval
    111       );
    112     return {
    113       status: result.status,
    114       author:
    115         result.status === 'signed'
    116           ? s.capturedArtifactSnapshot(result.artifact)?.author
    117           : null,
    118       expected: window.hcp053Fixture.owner,
    119       calls: window.hcp053Calls
    120     };
    121   });
    122   expect(value.status).toBe('signed');
    123   expect(value.author).toBe(value.expected);
    124   expect(value.calls).toEqual(['key', 'sign', 'key']);
    125 });
    126 for (const mode of [
    127   'author',
    128   'kind',
    129   'time',
    130   'tags',
    131   'content',
    132   'cached',
    133   'mutate',
    134   'denied'
    135 ] as const)
    136   test(`actual SDK hostile ${mode} is finite and returns no artifact`, async ({
    137     page
    138   }) => {
    139     await load(page);
    140     await page.evaluate((mode) => {
    141       window.hcp053Mode = mode;
    142     }, mode);
    143     expect(
    144       await page.evaluate(
    145         async () =>
    146           (
    147             await window.hcp053.signApprovedExtensionAdapter(
    148               window.hcp053Adapter,
    149               window.hcp053Approval
    150             )
    151           ).status
    152       )
    153     ).toBe(mode === 'denied' ? 'refused' : 'mismatch');
    154   });
    155 test('unsettled signing retains shared slot and disconnect fences late exact response', async ({
    156   page
    157 }) => {
    158   await load(page);
    159   await page.evaluate(() => {
    160     const f = window.hcp053Fixture;
    161     window.nostr = {
    162       getPublicKey: () => {
    163         window.hcp053Calls.push('key');
    164         return Promise.resolve(f.owner);
    165       },
    166       signEvent: (template: Parameters<typeof f.sign>[0]) => {
    167         window.hcp053Calls.push('sign');
    168         return new Promise((resolve) => {
    169           window.hcp053Release = () => resolve(f.sign(template));
    170         });
    171       }
    172     };
    173     window.hcp053Task = window.hcp053.signApprovedExtensionAdapter(
    174       window.hcp053Adapter,
    175       window.hcp053Approval
    176     );
    177   });
    178   await expect
    179     .poll(() => page.evaluate(() => window.hcp053Calls))
    180     .toEqual(['key', 'sign']);
    181   expect(
    182     await page.evaluate(
    183       async () =>
    184         (
    185           await window.hcp053.signApprovedExtensionAdapter(
    186             window.hcp053Adapter,
    187             window.hcp053Approval
    188           )
    189         ).status
    190     )
    191   ).toBe('busy');
    192   await page.evaluate(() =>
    193     window.hcp053.disconnectExtensionAdapter(window.hcp053Adapter)
    194   );
    195   expect(
    196     await page.evaluate(
    197       async () =>
    198         (
    199           await window.hcp053.connectExtensionAdapter(
    200             window.hcp053.createExtensionAdapter()
    201           )
    202         ).admission
    203     )
    204   ).toBe('busy');
    205   expect(
    206     await page.evaluate(async () => {
    207       window.hcp053Release();
    208       return (await window.hcp053Task).status;
    209     })
    210   ).toBe('unknown');
    211   expect(
    212     await page.evaluate(() =>
    213       window.hcp053.extensionSnapshot(window.hcp053Adapter)
    214     )
    215   ).toEqual({ state: 'guest', reason: 'disconnected' });
    216   expect(await page.evaluate(() => window.hcp053Calls)).toEqual([
    217     'key',
    218     'sign'
    219   ]);
    220 });
    221 for (const phase of ['before', 'after'] as const)
    222   test(`fresh ${phase} owner change prevents artifact admission`, async ({
    223     page
    224   }) => {
    225     await load(page);
    226     const outcome = await page.evaluate(async (phase) => {
    227       const s = window.hcp053,
    228         f = window.hcp053Fixture,
    229         other = s.makeFixture();
    230       let keys = 0;
    231       try {
    232         window.nostr = {
    233           getPublicKey: () => {
    234             window.hcp053Calls.push('key');
    235             keys++;
    236             return Promise.resolve(
    237               phase === 'before' || keys > 1 ? other.owner : f.owner
    238             );
    239           },
    240           signEvent: (template: Parameters<typeof f.sign>[0]) => {
    241             window.hcp053Calls.push('sign');
    242             return Promise.resolve(f.sign(template));
    243           }
    244         };
    245         const result = await s.signApprovedExtensionAdapter(
    246           window.hcp053Adapter,
    247           window.hcp053Approval
    248         );
    249         return {
    250           status: result.status,
    251           calls: window.hcp053Calls,
    252           snapshot: s.extensionSnapshot(window.hcp053Adapter)
    253         };
    254       } finally {
    255         other.close();
    256       }
    257     }, phase);
    258     expect(outcome.status).toBe(phase === 'before' ? 'stale' : 'unknown');
    259     expect(outcome.calls).toEqual(
    260       phase === 'before' ? ['key'] : ['key', 'sign', 'key']
    261     );
    262     expect(outcome.snapshot).toEqual({ state: 'guest', reason: 'changed_key' });
    263   });