app

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

inbox-resolution.test.ts (14045B)


      1 import { describe, it, expect } from 'vitest';
      2 import { finalizeEvent } from 'applesauce-core/helpers';
      3 import { validateRelayPolicy } from '../../src/lib/config/relays.ts';
      4 import {
      5   createPublicScheduler,
      6   createPublicRun,
      7   openInboxRequest,
      8   openPublicRequest,
      9   closePublicScheduler,
     10   publicRunSnapshot,
     11   publicRunObservations,
     12   publicSchedulerSnapshot,
     13   type RequestClock
     14 } from '../../src/lib/nostr/request-scope.ts';
     15 import type { PublicPoolMessage } from '../../src/lib/nostr/exports.ts';
     16 import {
     17   createInboxResolver,
     18   inboxResolutionSnapshot,
     19   closeInboxResolver
     20 } from '../../src/lib/messaging/resolve-inbox.ts';
     21 import {
     22   inboxPreferenceWire,
     23   inboxPreferenceSnapshot
     24 } from '../../src/lib/nostr/inbox-preferences.ts';
     25 import { inboxPreferenceQueries } from '../../src/lib/nostr/inbox-queries.ts';
     26 const origins = ['wss://one.example.org', 'wss://two.example.org'];
     27 function signed() {
     28   const key = crypto.getRandomValues(new Uint8Array(32));
     29   try {
     30     const old = finalizeEvent(
     31       {
     32         kind: 10050,
     33         created_at: 100,
     34         tags: [
     35           ['relay', origins[0]],
     36           ['unknown', 'keep']
     37         ],
     38         content: 'preserve'
     39       },
     40       key
     41     );
     42     const newer = finalizeEvent(
     43       { kind: 10050, created_at: 200, tags: [['relay']], content: '' },
     44       key
     45     );
     46     const tie = finalizeEvent(
     47       {
     48         kind: 10050,
     49         created_at: 100,
     50         tags: [['relay', origins[1]]],
     51         content: ''
     52       },
     53       key
     54     );
     55     const unrelated = finalizeEvent(
     56       { kind: 10002, created_at: 300, tags: [['r', origins[0]]], content: '' },
     57       key
     58     );
     59     return { old, newer, tie, unrelated };
     60   } finally {
     61     key.fill(0);
     62   }
     63 }
     64 function setup(author: string, sources = origins, stopFailures = 0) {
     65   const policy = validateRelayPolicy(
     66     JSON.stringify({
     67       schemaVersion: 1,
     68       public: sources.map((origin) => ({
     69         origin,
     70         read: true,
     71         write: false,
     72         nip50: false
     73       })),
     74       inbox: [{ origin: 'wss://archive.example.org', read: true, write: true }],
     75       postingEnabled: false,
     76       messagingEnabled: false,
     77       operatorDenylist: []
     78     })
     79   )!;
     80   let now = 0,
     81     stops = 0;
     82   let clockHook: (() => void) | undefined;
     83   const timers = new Map<() => void, () => void>();
     84   const clock: RequestClock = {
     85     now: () => {
     86       const hook = clockHook;
     87       clockHook = undefined;
     88       hook?.();
     89       return now;
     90     },
     91     schedule(callback) {
     92       const cancel = () => {
     93         timers.delete(cancel);
     94       };
     95       timers.set(cancel, callback);
     96       return cancel;
     97     }
     98   };
     99   const scheduler = createPublicScheduler(clock),
    100     run = createPublicRun(scheduler, policy);
    101   let sink: (message: PublicPoolMessage) => void = () => {},
    102     current = true;
    103   const resolver = createInboxResolver(
    104     run,
    105     author,
    106     (next) =>
    107       openInboxRequest(
    108         run,
    109         author,
    110         (callback) => {
    111           sink = callback;
    112           return () => {
    113             stops++;
    114             if (stops <= stopFailures)
    115               throw new Error('fixture_cleanup_failed');
    116           };
    117         },
    118         next
    119       ),
    120     () => current
    121   );
    122   return {
    123     resolver,
    124     scheduler,
    125     run,
    126     emit(message: PublicPoolMessage) {
    127       sink(message);
    128     },
    129     eose() {
    130       for (const from of sources) sink({ type: 'EOSE', from, id: 'fixture' });
    131     },
    132     stale() {
    133       current = false;
    134     },
    135     duringClock(callback: () => void) {
    136       clockHook = callback;
    137     },
    138     expire() {
    139       now = 10001;
    140       for (const callback of [...timers.values()]) callback();
    141     },
    142     stops: () => stops
    143   };
    144 }
    145 function event(
    146   from: string,
    147   value: ReturnType<typeof signed>['old']
    148 ): PublicPoolMessage {
    149   return { type: 'EVENT', from, id: 'fixture', event: value };
    150 }
    151 describe('bounded recipient preference discovery', () => {
    152   it('rechecks current generation after the injected clock synchronously invalidates discovery ownership', () => {
    153     const f = signed(),
    154       s = setup(f.old.pubkey);
    155     try {
    156       s.emit(event(origins[0], f.old));
    157       s.eose();
    158       expect(inboxResolutionSnapshot(s.resolver).status).toBe('ready');
    159       s.duringClock(() => s.stale());
    160       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    161     } finally {
    162       closePublicScheduler(s.scheduler);
    163     }
    164   });
    165   it('cleanup failure cannot enable ready and explicit close retries retained admission', () => {
    166     const f = signed(),
    167       s = setup(f.old.pubkey, origins, 1);
    168     try {
    169       s.emit(event(origins[0], f.old));
    170       s.eose();
    171       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    172       expect(publicSchedulerSnapshot(s.scheduler).activeRequests).toBe(1);
    173       closeInboxResolver(s.resolver);
    174       expect(publicSchedulerSnapshot(s.scheduler).activeRequests).toBe(0);
    175       expect(s.stops()).toBe(2);
    176     } finally {
    177       closePublicScheduler(s.scheduler);
    178     }
    179   });
    180   it('rejects non-JSON extras, cycles, huge decoded fields and reentrant descriptor traps under shared ingress bounds', () => {
    181     const f = signed();
    182     let getterCalls = 0;
    183     const cycle: Record<string, unknown> = {};
    184     cycle.self = cycle;
    185     for (const extra of [
    186       () => {
    187         getterCalls++;
    188         return 'unsafe';
    189       },
    190       cycle,
    191       'x'.repeat(262145),
    192       {
    193         get nested() {
    194           getterCalls++;
    195           return 'unsafe';
    196         }
    197       }
    198     ]) {
    199       const s = setup(f.old.pubkey);
    200       try {
    201         const candidate = { ...f.old, extra };
    202         s.emit(event(origins[0], candidate));
    203         s.eose();
    204         expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    205         expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(1);
    206       } finally {
    207         closePublicScheduler(s.scheduler);
    208       }
    209     }
    210     expect(getterCalls).toBe(0);
    211     const s = setup(f.old.pubkey);
    212     let entered = false;
    213     try {
    214       const hostile = new Proxy(
    215         { ...f.old },
    216         {
    217           getOwnPropertyDescriptor(target, name) {
    218             if (!entered) {
    219               entered = true;
    220               s.emit(event(origins[0], f.old));
    221             }
    222             return Reflect.getOwnPropertyDescriptor(target, name);
    223           }
    224         }
    225       );
    226       s.emit(event(origins[0], hostile));
    227       expect(publicRunSnapshot(s.run).ingress).toMatchObject({
    228         stopped: true,
    229         deliveries: 2
    230       });
    231       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    232     } finally {
    233       closePublicScheduler(s.scheduler);
    234     }
    235   });
    236   it('fixes exact kind and author without time filters or sender routing', () => {
    237     const f = signed();
    238     expect(inboxPreferenceQueries(f.old.pubkey)).toEqual([
    239       { kinds: [10050], authors: [f.old.pubkey], limit: 200 }
    240     ]);
    241     expect(() => inboxPreferenceQueries('f'.repeat(64))).toThrow(
    242       'inbox_author_invalid'
    243     );
    244   });
    245   it('requires every admitted fixed source and never caches degraded empty lookup as missing', () => {
    246     const f = signed(),
    247       s = setup(f.old.pubkey);
    248     try {
    249       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    250       s.emit({ type: 'EOSE', from: origins[0], id: 'fixture' });
    251       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    252       s.eose();
    253       expect(inboxResolutionSnapshot(s.resolver)).toMatchObject({
    254         status: 'missing',
    255         coverage: 'bounded-eose',
    256         definitiveAbsence: false
    257       });
    258       s.stale();
    259       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    260     } finally {
    261       closePublicScheduler(s.scheduler);
    262     }
    263   });
    264   it('empty discovery manifest stays inconclusive without falling back to configured archive', () => {
    265     const f = signed(),
    266       s = setup(f.old.pubkey, []);
    267     try {
    268       expect(inboxResolutionSnapshot(s.resolver)).toMatchObject({
    269         status: 'inconclusive',
    270         sources: []
    271       });
    272     } finally {
    273       closePublicScheduler(s.scheduler);
    274     }
    275   });
    276   it('new verified incompatible head blocks older compatible preference and retains both source versions', () => {
    277     const f = signed(),
    278       s = setup(f.old.pubkey);
    279     try {
    280       s.emit(event(origins[0], f.old));
    281       s.emit(event(origins[1] + '/', f.newer));
    282       s.eose();
    283       const r = inboxResolutionSnapshot(s.resolver);
    284       expect(r.status).toBe('unsupported');
    285       expect(inboxPreferenceSnapshot(r.head!)?.id).toBe(f.newer.id);
    286       expect(r.knownBase).toEqual({
    287         author: f.old.pubkey,
    288         id: f.newer.id,
    289         createdAt: 200
    290       });
    291       expect(r.sources.map((row) => row.head?.id)).toEqual([
    292         f.old.id,
    293         f.newer.id
    294       ]);
    295       expect(publicRunObservations(s.run, r.request)).toEqual([]);
    296     } finally {
    297       closePublicScheduler(s.scheduler);
    298     }
    299   });
    300   it('selects timestamp then lower ID deterministically independently of arrival order', () => {
    301     const f = signed();
    302     for (const rows of [
    303       [f.old, f.tie],
    304       [f.tie, f.old]
    305     ]) {
    306       const s = setup(f.old.pubkey);
    307       try {
    308         for (const row of rows) s.emit(event(origins[0], row));
    309         s.eose();
    310         const r = inboxResolutionSnapshot(s.resolver);
    311         expect(r.status).toBe('ready');
    312         expect(r.knownBase?.id).toBe([f.old.id, f.tie.id].sort()[0]);
    313       } finally {
    314         closePublicScheduler(s.scheduler);
    315       }
    316     }
    317   });
    318   it('preserves decoded unknown JSON and signed tags without trusting getters or cached SDK metadata', () => {
    319     const f = signed(),
    320       s = setup(f.old.pubkey);
    321     try {
    322       const extra = {
    323         ...f.old,
    324         extra: { nested: [null, true, 1, 'untrusted'] }
    325       };
    326       s.emit(event(origins[0], extra));
    327       s.eose();
    328       const r = inboxResolutionSnapshot(s.resolver);
    329       expect(r.status).toBe('ready');
    330       const raw: unknown = JSON.parse(inboxPreferenceWire(r.head!)!);
    331       expect(raw).toEqual(JSON.parse(JSON.stringify(extra)));
    332       expect(Object.getOwnPropertySymbols(raw as object)).toHaveLength(0);
    333       r.sources.pop();
    334       expect(inboxResolutionSnapshot(s.resolver).sources).toHaveLength(2);
    335       expect(r.wireProvenance).toBe('decoded-sdk-json');
    336     } finally {
    337       closePublicScheduler(s.scheduler);
    338     }
    339     const t = setup(f.old.pubkey);
    340     let reads = 0;
    341     try {
    342       const hostile = {
    343         ...f.old,
    344         get extra() {
    345           reads++;
    346           throw new Error('unsafe');
    347         }
    348       };
    349       t.emit(event(origins[0], hostile));
    350       t.eose();
    351       expect(reads).toBe(0);
    352       expect(inboxResolutionSnapshot(t.resolver).status).toBe('inconclusive');
    353     } finally {
    354       closePublicScheduler(t.scheduler);
    355     }
    356   });
    357   it('rejects wrong author, wrong kind and bad signature without turning a partial lookup ready or missing', () => {
    358     const f = signed(),
    359       other = signed();
    360     for (const bad of [
    361       other.old,
    362       f.unrelated,
    363       { ...f.old, sig: '0'.repeat(128) }
    364     ]) {
    365       const s = setup(f.old.pubkey);
    366       try {
    367         s.emit(event(origins[0], bad));
    368         s.eose();
    369         expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    370         expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(1);
    371       } finally {
    372         closePublicScheduler(s.scheduler);
    373       }
    374     }
    375   });
    376   it('saturation and failed source prevent bounded readiness despite a valid known head', () => {
    377     const f = signed(),
    378       s = setup(f.old.pubkey);
    379     try {
    380       for (let i = 0; i < 200; i++) s.emit(event(origins[0], f.old));
    381       s.eose();
    382       const r = inboxResolutionSnapshot(s.resolver);
    383       expect(r.status).toBe('inconclusive');
    384       expect(r.knownBase?.id).toBe(f.old.id);
    385       expect(r.sources[0]).toMatchObject({ state: 'limit', candidates: 200 });
    386       expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(200);
    387     } finally {
    388       closePublicScheduler(s.scheduler);
    389     }
    390     const t = setup(f.old.pubkey);
    391     try {
    392       t.emit(event(origins[0], f.old));
    393       t.emit({
    394         type: 'ERROR',
    395         from: origins[1],
    396         error: new Error('untrusted')
    397       });
    398       t.emit({ type: 'EOSE', from: origins[0], id: 'fixture' });
    399       expect(inboxResolutionSnapshot(t.resolver).status).toBe('inconclusive');
    400     } finally {
    401       closePublicScheduler(t.scheduler);
    402     }
    403   });
    404   it('unknown source never supplies preference authority and deadline/close revoke readiness', () => {
    405     const f = signed(),
    406       s = setup(f.old.pubkey);
    407     try {
    408       s.emit(event('wss://hint.example.org', f.old));
    409       s.expire();
    410       expect(inboxResolutionSnapshot(s.resolver).status).toBe('inconclusive');
    411       expect(publicRunSnapshot(s.run).ingress.deliveries).toBe(1);
    412       s.emit(event(origins[0], f.old));
    413       expect(inboxResolutionSnapshot(s.resolver).head).toBeUndefined();
    414       closeInboxResolver(s.resolver);
    415       expect(s.stops()).toBe(1);
    416     } finally {
    417       closePublicScheduler(s.scheduler);
    418     }
    419   });
    420   it('shares six-scope concurrency and forbids generic inbox mode before effects', () => {
    421     const f = signed(),
    422       s = setup(f.old.pubkey);
    423     let effects = 0;
    424     try {
    425       for (let i = 0; i < 5; i++)
    426         openPublicRequest(
    427           s.run,
    428           'profile',
    429           () => {
    430             effects++;
    431             return () => {};
    432           },
    433           () => {}
    434         );
    435       expect(() =>
    436         openInboxRequest(
    437           s.run,
    438           f.old.pubkey,
    439           () => {
    440             effects++;
    441             return () => {};
    442           },
    443           () => {}
    444         )
    445       ).toThrow('public_request_concurrency_limit');
    446       expect(effects).toBe(5);
    447       expect(publicSchedulerSnapshot(s.scheduler).activeRequests).toBe(6);
    448       expect(() =>
    449         openPublicRequest(
    450           s.run,
    451           'inbox',
    452           () => {
    453             effects++;
    454             return () => {};
    455           },
    456           () => {}
    457         )
    458       ).toThrow('inbox_author_invalid');
    459     } finally {
    460       closePublicScheduler(s.scheduler);
    461     }
    462   });
    463 });