app

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

publishers.test.ts (13279B)


      1 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
      2 import { readFileSync } from 'node:fs';
      3 import { finalizeEvent } from 'applesauce-core/helpers';
      4 import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts';
      5 import type { RequestClock } from '../../src/lib/nostr/request-scope.ts';
      6 let search: typeof import('../../src/lib/catalog/search-run.ts');
      7 let runtime: typeof import('../../src/lib/runtime/public-runtime.ts');
      8 let context: ReturnType<typeof runtime.createPublicRuntimeContext>;
      9 const keys: Uint8Array[] = [];
     10 beforeEach(async () => {
     11   vi.resetModules();
     12   vi.stubGlobal('window', {});
     13   search = await import('../../src/lib/catalog/search-run.ts');
     14   runtime = await import('../../src/lib/runtime/public-runtime.ts');
     15 });
     16 afterEach(() => {
     17   if (context) runtime.closePublicRuntime(context);
     18   for (const key of keys.splice(0)) key.fill(0);
     19   vi.restoreAllMocks();
     20   vi.unstubAllGlobals();
     21 });
     22 const corpus = JSON.parse(
     23   readFileSync(
     24     new URL(
     25       '../../../contracts/interop/food_availability/corpus.v1.json',
     26       import.meta.url
     27     ),
     28     'utf8'
     29   )
     30 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
     31 const base = JSON.parse(
     32   corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous
     33 ) as { tags: string[][]; content: string; created_at: number };
     34 async function fixture(nip50 = false, sourceCount = 1) {
     35   const { RelayPool } = await import('applesauce-relay/pool');
     36   const { validateRelayPolicy } =
     37     await import('../../src/lib/config/relays.ts');
     38   const { verifyEnvelope } =
     39     await import('../../src/lib/nostr/verified-envelope.ts');
     40   const { createPublicHeadCandidate } =
     41     await import('../../src/lib/catalog/heads.ts');
     42   const channels: {
     43     emit: (value: PublicPoolMessage) => void;
     44     stopped: () => boolean;
     45   }[] = [];
     46   const provider = vi.spyOn(RelayPool.prototype, 'req').mockImplementation(
     47     () =>
     48       ({
     49         subscribe(subscriber: { next?: (value: PublicPoolMessage) => void }) {
     50           let stopped = false;
     51           channels.push({
     52             emit: (value: PublicPoolMessage) => {
     53               if (!stopped) subscriber.next?.(value);
     54             },
     55             stopped: () => stopped
     56           });
     57           return {
     58             get closed() {
     59               return stopped;
     60             },
     61             unsubscribe() {
     62               stopped = true;
     63             }
     64           };
     65         }
     66       }) as unknown as ReturnType<InstanceType<typeof RelayPool>['req']>
     67   );
     68   const origin = 'wss://one.example.org';
     69   const policy = validateRelayPolicy(
     70     JSON.stringify({
     71       schemaVersion: 1,
     72       public: Array.from({ length: sourceCount }, (_, n) => ({
     73         origin: n === 0 ? origin : `wss://source${n}.example.org`,
     74         read: true,
     75         write: false,
     76         nip50
     77       })),
     78       inbox: [],
     79       postingEnabled: false,
     80       messagingEnabled: false,
     81       operatorDenylist: []
     82     })
     83   )!;
     84   const key = crypto.getRandomValues(new Uint8Array(32));
     85   keys.push(key);
     86   const wire = (
     87     title = 'Carrots',
     88     d?: string,
     89     time = base.created_at,
     90     content = base.content
     91   ) =>
     92     finalizeEvent(
     93       {
     94         kind: 30402,
     95         created_at: time,
     96         content,
     97         tags: base.tags.map((tag) =>
     98           tag[0] === 'title'
     99             ? ['title', title]
    100             : tag[0] === 'd' && d !== undefined
    101               ? ['d', d]
    102               : [...tag]
    103         )
    104       },
    105       key
    106     );
    107   const head = (event = wire()) => {
    108     const p = verifyEnvelope(JSON.stringify(event));
    109     if (!p.ok) throw Error('fixture proof');
    110     const h = createPublicHeadCandidate(p.value);
    111     if (!h) throw Error('fixture head');
    112     return h;
    113   };
    114   let now = 0,
    115     reads = 0;
    116   let onNow = () => {};
    117   const timers = new Map<() => void, { at: number; callback: () => void }>();
    118   const clock: RequestClock = {
    119     now: () => {
    120       reads++;
    121       onNow();
    122       return now;
    123     },
    124     schedule: (callback, delay) => {
    125       const cancel = () => {
    126         timers.delete(cancel);
    127       };
    128       timers.set(cancel, { at: now + delay, callback });
    129       return cancel;
    130     }
    131   };
    132   context = runtime.createPublicRuntimeContext();
    133   const owner = runtime.mountPublicRuntime(context, policy, clock)!;
    134   const view = runtime.createPublicView(owner);
    135   const wallClock = {
    136     nowSeconds: () => base.created_at + 10
    137   };
    138   const coordinator = search.createFoodSearchCoordinator(view, wallClock);
    139   const begin = (query = '', heads: readonly ReturnType<typeof head>[] = []) =>
    140     search.beginFoodSearch(coordinator, query, heads);
    141   const snapshot = () => search.foodSearchSnapshot(coordinator)!;
    142   const emit = (i: number, event: ReturnType<typeof wire>) =>
    143     channels[i].emit({ type: 'EVENT', id: 'fixture', from: origin, event });
    144   return {
    145     eose: (i: number) => {
    146       const selected = provider.mock.calls[i][0];
    147       if (!Array.isArray(selected)) throw new Error('fixture source array');
    148       for (const source of selected)
    149         channels[i].emit({ type: 'EOSE', id: 'fixture', from: String(source) });
    150     },
    151     coordinator,
    152     view,
    153     wallClock,
    154     begin,
    155     snapshot,
    156     head,
    157     wire,
    158     emit,
    159     channels,
    160     provider,
    161     origin,
    162     timers,
    163     reads: () => reads,
    164     reenter: (callback: () => void) => {
    165       onNow = callback;
    166     },
    167     advance: (value: number) => {
    168       now = value;
    169       for (const timer of [...timers.values()])
    170         if (timer.at <= now) timer.callback();
    171     }
    172   };
    173 }
    174 let publishers: typeof import('../../src/lib/catalog/publishers.ts');
    175 beforeEach(async () => {
    176   publishers = await import('../../src/lib/catalog/publishers.ts');
    177 });
    178 describe('genuine bounded public publisher views', () => {
    179   it('coalesces displayed authors and preserves key fallback without an account', async () => {
    180     const f = await fixture(),
    181       token = f.begin(),
    182       key = f.wire().pubkey;
    183     const owner = publishers.createPublisherViews(f.view, f.wallClock),
    184       run = search.foodSearchRequestOwner(token);
    185     const reads = publishers.readPublisherPage(owner, run, [key, key]);
    186     expect(reads).toHaveLength(1);
    187     expect(f.provider).toHaveBeenCalledTimes(1);
    188     expect(publishers.readPublisherPage(owner, run, [key])).toEqual([]);
    189     expect(publishers.publisherSnapshot(owner, key)).toEqual({
    190       pubkey: key,
    191       label: key,
    192       assertedName: false
    193     });
    194     const profile = finalizeEvent(
    195       {
    196         kind: 0,
    197         created_at: base.created_at,
    198         tags: [],
    199         content: JSON.stringify({
    200           display_name: '<b>Farmer</b>',
    201           pubkey: 'attacker',
    202           nip05: 'claims@example.org',
    203           picture: 'https://tracking.example.org'
    204         })
    205       },
    206       keys[0]
    207     );
    208     f.emit(0, profile);
    209     expect(publishers.publisherSnapshot(owner, key)).toEqual({
    210       pubkey: key,
    211       label: '<b>Farmer</b>',
    212       assertedName: true
    213     });
    214     expect(f.provider).toHaveBeenCalledTimes(1);
    215     expect(f.snapshot().run?.ingress.deliveries).toBe(1);
    216   });
    217   it('selects generic latest before unsupported/future parsing and never resurrects an old name', async () => {
    218     const f = await fixture(),
    219       token = f.begin(),
    220       key = f.wire().pubkey;
    221     const owner = publishers.createPublisherViews(f.view, f.wallClock);
    222     publishers.readPublisherPage(owner, search.foodSearchRequestOwner(token), [
    223       key
    224     ]);
    225     const send = (time: number, content: string) =>
    226       f.emit(
    227         0,
    228         finalizeEvent({ kind: 0, created_at: time, tags: [], content }, keys[0])
    229       );
    230     send(base.created_at, '{"name":"Old"}');
    231     expect(publishers.publisherSnapshot(owner, key).label).toBe('Old');
    232     send(base.created_at + 1, '{"name":123}');
    233     expect(publishers.publisherSnapshot(owner, key).label).toBe(key);
    234     send(base.created_at, '{"name":"Old"}');
    235     expect(publishers.publisherSnapshot(owner, key).label).toBe(key);
    236     send(base.created_at + 311, '{"name":"Future"}');
    237     expect(publishers.publisherSnapshot(owner, key).label).toBe(key);
    238   });
    239   it('ignores corrupt signatures and nonrequested authors, and rejects a foreign run before effects', async () => {
    240     const f = await fixture(),
    241       token = f.begin(),
    242       key = f.wire().pubkey;
    243     const owner = publishers.createPublisherViews(f.view, f.wallClock),
    244       run = search.foodSearchRequestOwner(token);
    245     publishers.readPublisherPage(owner, run, [key]);
    246     const profile = finalizeEvent(
    247       {
    248         kind: 0,
    249         created_at: base.created_at,
    250         tags: [],
    251         content: '{"name":"Spoof"}'
    252       },
    253       keys[0]
    254     );
    255     f.emit(0, { ...profile, id: '0'.repeat(64) });
    256     const other = crypto.getRandomValues(new Uint8Array(32));
    257     keys.push(other);
    258     f.emit(
    259       0,
    260       finalizeEvent(
    261         {
    262           kind: 0,
    263           created_at: base.created_at,
    264           tags: [],
    265           content: '{"name":"Other"}'
    266         },
    267         other
    268       )
    269     );
    270     expect(publishers.publisherSnapshot(owner, key).label).toBe(key);
    271     expect(() =>
    272       publishers.readPublisherPage(owner, {} as typeof run, [key])
    273     ).toThrow();
    274     expect(f.provider).toHaveBeenCalledTimes(1);
    275     search.cancelFoodSearch(token);
    276     f.emit(0, profile);
    277     expect(publishers.publisherSnapshot(owner, key).label).toBe(key);
    278     expect(f.channels[0].stopped()).toBe(true);
    279   });
    280   it('reserves a failed provider read without retry or losing known food', async () => {
    281     const f = await fixture(),
    282       token = f.begin('', [f.head()]),
    283       key = f.wire().pubkey;
    284     const owner = publishers.createPublisherViews(f.view, f.wallClock),
    285       run = search.foodSearchRequestOwner(token);
    286     f.provider.mockImplementationOnce(() => {
    287       throw Error('isolated provider failure');
    288     });
    289     expect(() => publishers.readPublisherPage(owner, run, [key])).toThrow();
    290     expect(publishers.readPublisherPage(owner, run, [key])).toEqual([]);
    291     expect(publishers.publisherSnapshot(owner, key)).toEqual({
    292       pubkey: key,
    293       label: key,
    294       assertedName: false
    295     });
    296     expect(f.snapshot().rows).toHaveLength(1);
    297     expect(f.provider).toHaveBeenCalledTimes(3);
    298     expect(search.foodSearchRequestOwner(token)).toBe(run);
    299   });
    300   it('does not publish a stale name when an injected clock delivers a newer unsupported head', async () => {
    301     const f = await fixture(),
    302       token = f.begin(),
    303       key = f.wire().pubkey;
    304     const owner = publishers.createPublisherViews(f.view, f.wallClock);
    305     publishers.readPublisherPage(owner, search.foodSearchRequestOwner(token), [
    306       key
    307     ]);
    308     f.emit(
    309       0,
    310       finalizeEvent(
    311         {
    312           kind: 0,
    313           created_at: base.created_at,
    314           tags: [],
    315           content: '{"name":"Old"}'
    316         },
    317         keys[0]
    318       )
    319     );
    320     const newer = finalizeEvent(
    321       {
    322         kind: 0,
    323         created_at: base.created_at + 1,
    324         tags: [],
    325         content: '{"name":123}'
    326       },
    327       keys[0]
    328     );
    329     let armed = true;
    330     f.wallClock.nowSeconds = () => {
    331       if (armed) {
    332         armed = false;
    333         f.emit(0, newer);
    334       }
    335       return base.created_at + 10;
    336     };
    337     expect(publishers.publisherSnapshot(owner, key).label).toBe(key);
    338   });
    339   it('enforces twenty publisher admissions per page across row reordering', async () => {
    340     const f = await fixture(),
    341       token = f.begin(),
    342       owner = publishers.createPublisherViews(f.view, f.wallClock),
    343       run = search.foodSearchRequestOwner(token);
    344     const authors = Array.from({ length: 21 }, () => {
    345       const key = crypto.getRandomValues(new Uint8Array(32));
    346       keys.push(key);
    347       return finalizeEvent(
    348         { kind: 0, created_at: base.created_at, tags: [], content: '{}' },
    349         key
    350       ).pubkey;
    351     });
    352     publishers.readPublisherPage(owner, run, authors.slice(0, 20));
    353     expect(publishers.readPublisherPage(owner, run, [authors[20]])).toEqual([]);
    354     expect(f.provider).toHaveBeenCalledTimes(1);
    355     expect(publishers.publisherSnapshot(owner, authors[20]).label).toBe(
    356       authors[20]
    357     );
    358     publishers.readPublisherPage(owner, run, [authors[20]], 2);
    359     expect(f.provider).toHaveBeenCalledTimes(2);
    360     for (const page of [0, 101, 1.5, NaN])
    361       expect(() =>
    362         publishers.readPublisherPage(owner, run, [authors[20]], page)
    363       ).toThrow('publisher_page_invalid');
    364     expect(f.provider).toHaveBeenCalledTimes(2);
    365   });
    366   it('retains fallback after a failed read and shares all global work and deadlines', async () => {
    367     const f = await fixture(),
    368       token = f.begin(),
    369       key = f.wire().pubkey;
    370     const owner = publishers.createPublisherViews(f.view, f.wallClock),
    371       run = search.foodSearchRequestOwner(token);
    372     publishers.readPublisherPage(owner, run, [key]);
    373     const profile = finalizeEvent(
    374       {
    375         kind: 0,
    376         created_at: base.created_at,
    377         tags: [],
    378         content: '{"name":"Known"}'
    379       },
    380       keys[0]
    381     );
    382     for (let n = 0; n < 2000; n++) f.emit(0, profile);
    383     expect(f.snapshot().run?.ingress).toMatchObject({
    384       deliveries: 2000,
    385       stopped: true
    386     });
    387     expect(f.channels[0].stopped()).toBe(true);
    388     expect(() => publishers.readPublisherPage(owner, run, [key])).toThrow();
    389     expect(publishers.publisherSnapshot(owner, key).label).toBe('Known');
    390   });
    391 });