app

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

messaging-readiness.test.ts (11326B)


      1 import { it, expect } from 'vitest';
      2 import { finalizeEvent } from 'applesauce-core/helpers';
      3 import {
      4   validateRelayPolicy,
      5   type RelayPolicy
      6 } from '../../src/lib/config/relays.ts';
      7 import {
      8   createPublicScheduler,
      9   createPublicRun,
     10   openInboxRequest,
     11   closePublicScheduler
     12 } from '../../src/lib/nostr/request-scope.ts';
     13 import {
     14   createInboxResolver,
     15   type InboxResolver
     16 } from '../../src/lib/messaging/resolve-inbox.ts';
     17 import {
     18   createIdentitySession,
     19   connectIdentity,
     20   probeIdentityMessaging,
     21   disconnectIdentity,
     22   identitySessionSnapshot
     23 } from '../../src/lib/runtime/identity-session.ts';
     24 import {
     25   createPrivateSession,
     26   closePrivateSession
     27 } from '../../src/lib/runtime/private-session.ts';
     28 import {
     29   messagingReadinessSnapshot,
     30   type OwnInboxAccessContext,
     31   type InboxAccessObservation
     32 } from '../../src/lib/messaging/readiness.ts';
     33 const discovery = 'wss://discovery.example.org',
     34   ownOrigin = 'wss://archive.example.org',
     35   peerOrigin = 'wss://peer.example.org';
     36 function policy(): RelayPolicy {
     37   return validateRelayPolicy(
     38     JSON.stringify({
     39       schemaVersion: 1,
     40       public: [{ origin: discovery, read: true, write: false, nip50: false }],
     41       inbox: [ownOrigin, peerOrigin].map((origin) => ({
     42         origin,
     43         read: true,
     44         write: true
     45       })),
     46       postingEnabled: true,
     47       messagingEnabled: true,
     48       operatorDenylist: []
     49     })
     50   )!;
     51 }
     52 function signed(origin: string) {
     53   const key = crypto.getRandomValues(new Uint8Array(32));
     54   try {
     55     return finalizeEvent(
     56       { kind: 10050, created_at: 100, tags: [['relay', origin]], content: '' },
     57       key
     58     );
     59   } finally {
     60     key.fill(0);
     61   }
     62 }
     63 function resolve(event: ReturnType<typeof signed>, complete = true) {
     64   const scheduler = createPublicScheduler({
     65       now: () => 0,
     66       schedule: () => () => {}
     67     }),
     68     run = createPublicRun(scheduler, policy());
     69   let current = true;
     70   const resolver = createInboxResolver(
     71     run,
     72     event.pubkey,
     73     (next) =>
     74       openInboxRequest(
     75         run,
     76         event.pubkey,
     77         (sink) => {
     78           sink({ type: 'EVENT', from: discovery, id: 'fixture', event });
     79           if (complete) sink({ type: 'EOSE', from: discovery, id: 'fixture' });
     80           return () => {};
     81         },
     82         next
     83       ),
     84     () => current
     85   );
     86   return {
     87     resolver,
     88     close() {
     89       closePublicScheduler(scheduler);
     90     },
     91     stale() {
     92       current = false;
     93     }
     94   };
     95 }
     96 // HC_TEST_ONLY_QUALIFICATION_PORT: controlled observations test the projection;
     97 // neither this echo provider nor its claims qualify a real extension or relay.
     98 function qualified(c: OwnInboxAccessContext): InboxAccessObservation {
     99   return {
    100     owner: c.owner,
    101     session: c.session,
    102     preferenceId: c.preferenceId,
    103     readTargets: c.readTargets.slice(),
    104     archiveTargets: c.archiveTargets.slice(),
    105     receive: 'qualified_exercised',
    106     archive: 'qualified_exercised',
    107     current: () => true
    108   };
    109 }
    110 async function fixture(messaging = true) {
    111   const self = signed(ownOrigin),
    112     peer = signed(peerOrigin),
    113     own = resolve(self),
    114     other = resolve(peer),
    115     identity = createIdentitySession();
    116   const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
    117   let observations = 0,
    118     signatures = 0;
    119   Object.defineProperty(globalThis, 'window', {
    120     configurable: true,
    121     value: {
    122       nostr: {
    123         getPublicKey() {
    124           observations++;
    125           return Promise.resolve(self.pubkey);
    126         },
    127         signEvent() {
    128           signatures++;
    129           return Promise.reject(new Error('HC_TEST_ONLY_UNEXPECTED_SIGN'));
    130         },
    131         ...(messaging
    132           ? {
    133               nip44: {
    134                 encrypt: (_peer: string, text: string) =>
    135                   Promise.resolve('fixture:' + text),
    136                 decrypt: (_peer: string, text: string) =>
    137                   Promise.resolve(text.slice(8))
    138               }
    139             }
    140           : {})
    141       }
    142     }
    143   });
    144   await connectIdentity(identity);
    145   if (messaging) await probeIdentityMessaging(identity, 'reviewed_self_copy');
    146   const session = await createPrivateSession(
    147     identity,
    148     'reviewed_private_session'
    149   );
    150   return {
    151     self,
    152     peer,
    153     own,
    154     other,
    155     identity,
    156     session,
    157     counts: () => ({ observations, signatures }),
    158     close() {
    159       if (session) closePrivateSession(session);
    160       disconnectIdentity(identity);
    161       own.close();
    162       other.close();
    163       if (previous) Object.defineProperty(globalThis, 'window', previous);
    164       else Reflect.deleteProperty(globalThis, 'window');
    165     }
    166   };
    167 }
    168 it('SSR and guest browse/draft do not need inbox setup or identity effects', () => {
    169   const r = messagingReadinessSnapshot(
    170     createIdentitySession(),
    171     undefined,
    172     policy(),
    173     undefined
    174   );
    175   expect(r).toMatchObject({
    176     browse: true,
    177     draft: true,
    178     newListingReady: false,
    179     sendReady: false,
    180     preferenceWrite: 'not_requested'
    181   });
    182 });
    183 it('signing-only real SDK observation cannot advertise a messaging-ready new listing', async () => {
    184   const f = await fixture(false);
    185   try {
    186     expect(f.session).toBeUndefined();
    187     const before = f.counts();
    188     expect(
    189       messagingReadinessSnapshot(
    190         f.identity,
    191         f.session,
    192         policy(),
    193         f.own.resolver,
    194         { author: f.peer.pubkey, resolver: f.other.resolver },
    195         qualified
    196       )
    197     ).toMatchObject({ newListingReady: false, sendReady: false });
    198     expect(f.counts()).toEqual(before);
    199   } finally {
    200     f.close();
    201   }
    202 });
    203 it('compatible existing own preference needs no write and qualified source fixture permits prepared exchange', async () => {
    204   const f = await fixture();
    205   try {
    206     const before = f.counts();
    207     expect(
    208       messagingReadinessSnapshot(
    209         f.identity,
    210         f.session,
    211         policy(),
    212         f.own.resolver,
    213         { author: f.peer.pubkey, resolver: f.other.resolver },
    214         qualified
    215       )
    216     ).toMatchObject({
    217       ownConfiguration: 'compatible',
    218       ownAccess: 'qualified_exercised',
    219       newListingReady: true,
    220       sendReady: true,
    221       preferenceWrite: 'not_requested'
    222     });
    223     expect(f.counts()).toEqual(before);
    224   } finally {
    225     f.close();
    226   }
    227 });
    228 it('capable connection and compatible routes without qualified access stay blocked', async () => {
    229   const f = await fixture();
    230   try {
    231     expect(
    232       messagingReadinessSnapshot(
    233         f.identity,
    234         f.session,
    235         policy(),
    236         f.own.resolver,
    237         { author: f.peer.pubkey, resolver: f.other.resolver }
    238       )
    239     ).toMatchObject({
    240       ownConfiguration: 'compatible',
    241       ownAccess: 'unavailable',
    242       newListingReady: false,
    243       sendReady: false
    244     });
    245   } finally {
    246     f.close();
    247   }
    248 });
    249 it('unknown peer cannot enable send while qualified own configuration remains useful', async () => {
    250   const f = await fixture(),
    251     partial = resolve(f.peer, false);
    252   try {
    253     expect(
    254       messagingReadinessSnapshot(
    255         f.identity,
    256         f.session,
    257         policy(),
    258         f.own.resolver,
    259         { author: f.peer.pubkey, resolver: partial.resolver },
    260         qualified
    261       )
    262     ).toMatchObject({ newListingReady: true, sendReady: false });
    263   } finally {
    264     partial.close();
    265     f.close();
    266   }
    267 });
    268 it('qualified access observation must match actual account generation preference and fixed targets', async () => {
    269   const f = await fixture();
    270   try {
    271     for (const mutate of [
    272       (r: InboxAccessObservation) => ({ ...r, owner: f.peer.pubkey }),
    273       (r: InboxAccessObservation) => ({ ...r, session: Symbol() }),
    274       (r: InboxAccessObservation) => ({ ...r, preferenceId: '0'.repeat(64) }),
    275       (r: InboxAccessObservation) => ({
    276         ...r,
    277         readTargets: ['wss://hint.example.org']
    278       }),
    279       (r: InboxAccessObservation) => ({ ...r, archiveTargets: [] })
    280     ]) {
    281       expect(
    282         messagingReadinessSnapshot(
    283           f.identity,
    284           f.session,
    285           policy(),
    286           f.own.resolver,
    287           { author: f.peer.pubkey, resolver: f.other.resolver },
    288           (c) => mutate(qualified(c))
    289         )
    290       ).toMatchObject({ newListingReady: false, sendReady: false });
    291     }
    292   } finally {
    293     f.close();
    294   }
    295 });
    296 it('stale private session, forged own resolver and trusted observer invalidation cannot retain readiness', async () => {
    297   const f = await fixture();
    298   try {
    299     expect(
    300       messagingReadinessSnapshot(
    301         f.identity,
    302         f.session,
    303         policy(),
    304         {} as InboxResolver,
    305         undefined,
    306         qualified
    307       ).newListingReady
    308     ).toBe(false);
    309     expect(
    310       messagingReadinessSnapshot(
    311         f.identity,
    312         f.session,
    313         policy(),
    314         f.own.resolver,
    315         undefined,
    316         (c) => {
    317           f.own.stale();
    318           return qualified(c);
    319         }
    320       ).newListingReady
    321     ).toBe(false);
    322     if (f.session) closePrivateSession(f.session);
    323     expect(
    324       messagingReadinessSnapshot(
    325         f.identity,
    326         f.session,
    327         policy(),
    328         f.own.resolver,
    329         undefined,
    330         qualified
    331       ).newListingReady
    332     ).toBe(false);
    333   } finally {
    334     f.close();
    335   }
    336 });
    337 
    338 it('explicit private closure blocks readiness while identity remains messaging capable', async () => {
    339   const f = await fixture();
    340   try {
    341     expect(
    342       messagingReadinessSnapshot(
    343         f.identity,
    344         f.session,
    345         policy(),
    346         f.own.resolver,
    347         undefined,
    348         qualified
    349       ).newListingReady
    350     ).toBe(true);
    351     if (f.session) closePrivateSession(f.session);
    352     expect(identitySessionSnapshot(f.identity).state).toBe('messaging_capable');
    353     expect(
    354       messagingReadinessSnapshot(
    355         f.identity,
    356         f.session,
    357         policy(),
    358         f.own.resolver,
    359         undefined,
    360         qualified
    361       ).newListingReady
    362     ).toBe(false);
    363   } finally {
    364     f.close();
    365   }
    366 });
    367 it('mutating detached qualification context cannot retarget expected receiving sources', async () => {
    368   const f = await fixture();
    369   try {
    370     expect(
    371       messagingReadinessSnapshot(
    372         f.identity,
    373         f.session,
    374         policy(),
    375         f.own.resolver,
    376         undefined,
    377         (c) => {
    378           (c.readTargets as string[]).push('wss://hint.example.org');
    379           return qualified(c);
    380         }
    381       ).newListingReady
    382     ).toBe(false);
    383   } finally {
    384     f.close();
    385   }
    386 });
    387 it('disabled messaging never asks a trusted qualification port to grant readiness', async () => {
    388   const f = await fixture();
    389   let called = 0;
    390   try {
    391     const disabled = validateRelayPolicy(
    392       JSON.stringify({
    393         schemaVersion: 1,
    394         public: [{ origin: discovery, read: true, write: false, nip50: false }],
    395         inbox: [ownOrigin, peerOrigin].map((origin) => ({
    396           origin,
    397           read: true,
    398           write: true
    399         })),
    400         postingEnabled: true,
    401         messagingEnabled: false,
    402         operatorDenylist: []
    403       })
    404     )!;
    405     expect(
    406       messagingReadinessSnapshot(
    407         f.identity,
    408         f.session,
    409         disabled,
    410         f.own.resolver,
    411         undefined,
    412         (c) => {
    413           called++;
    414           return qualified(c);
    415         }
    416       )
    417     ).toMatchObject({
    418       ownConfiguration: 'compatible',
    419       newListingReady: false,
    420       sendReady: false
    421     });
    422     expect(called).toBe(0);
    423   } finally {
    424     f.close();
    425   }
    426 });