app

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

public-pool.test.ts (11404B)


      1 import { test } from 'node:test';
      2 import assert from 'node:assert/strict';
      3 import { once } from 'node:events';
      4 import WebSocket, { WebSocketServer } from 'ws';
      5 import { RelayPool } from 'applesauce-relay/pool';
      6 import { validateRelayPolicy } from '../../src/lib/config/relays.ts';
      7 import {
      8   getPublicPool,
      9   publicPoolOrigins,
     10   subscribePublicPool,
     11   closePublicPool
     12 } from '../../src/lib/nostr/public-pool.ts';
     13 
     14 // HC_TEST_ONLY_RELAY: SDK constructor mapping is confined to this test.
     15 await test('anonymous public pool owns one browser lifetime', async (t) => {
     16   const origins = ['wss://relay.example.org', 'wss://relay-two.example.org'];
     17   const policy = validateRelayPolicy(
     18     JSON.stringify({
     19       schemaVersion: 1,
     20       public: origins.map((origin) => ({
     21         origin,
     22         read: true,
     23         write: true,
     24         nip50: false
     25       })),
     26       inbox: [],
     27       postingEnabled: false,
     28       messagingEnabled: false,
     29       operatorDenylist: []
     30     })
     31   );
     32   assert.ok(policy);
     33   const windowDescriptor = Object.getOwnPropertyDescriptor(
     34     globalThis,
     35     'window'
     36   );
     37   const originalSocket = globalThis.WebSocket;
     38   const originalFetch = globalThis.fetch;
     39   assert.equal(windowDescriptor, undefined);
     40   await t.test(
     41     'SSR import and acquisition perform no browser or socket work',
     42     () => {
     43       assert.equal(getPublicPool(policy), undefined);
     44     }
     45   );
     46   const server = new WebSocketServer({
     47     host: '127.0.0.1',
     48     port: 0,
     49     maxPayload: 4096
     50   });
     51   const frames: unknown[][] = [];
     52   const sockets: WebSocket[] = [];
     53   server.on('connection', (socket) => {
     54     sockets.push(socket);
     55     socket.send(JSON.stringify(['AUTH', 'unsolicited-test-challenge']));
     56     socket.on('message', (bytes) => {
     57       const buffer = Array.isArray(bytes)
     58         ? Buffer.concat(bytes)
     59         : Buffer.isBuffer(bytes)
     60           ? bytes
     61           : Buffer.from(bytes);
     62       const frame: unknown = JSON.parse(buffer.toString('utf8'));
     63       assert.ok(Array.isArray(frame));
     64       frames.push(frame);
     65       if (frame[0] === 'REQ') socket.send(JSON.stringify(['EOSE', frame[1]]));
     66     });
     67   });
     68   await once(server, 'listening');
     69   const address = server.address();
     70   assert.ok(address && typeof address !== 'string');
     71   const fixturePort = address.port;
     72   let constructed = 0;
     73   let extensionCalls = 0;
     74   class FixtureSocket extends WebSocket {
     75     constructor(url: string | URL) {
     76       assert.ok(origins.includes(String(url).replace(/\/$/, '')));
     77       constructed++;
     78       super(`ws://127.0.0.1:${fixturePort}`);
     79     }
     80   }
     81   Object.defineProperty(globalThis, 'window', {
     82     configurable: true,
     83     value: {
     84       nostr: {
     85         getPublicKey() {
     86           extensionCalls++;
     87           throw new Error('Unexpected identity');
     88         },
     89         signEvent() {
     90           extensionCalls++;
     91           throw new Error('Unexpected signing');
     92         }
     93       }
     94     }
     95   });
     96   globalThis.WebSocket =
     97     FixtureSocket as unknown as typeof globalThis.WebSocket;
     98   globalThis.fetch = () =>
     99     Promise.reject(new Error('Unexpected relay information fetch'));
    100   let pool: NonNullable<ReturnType<typeof getPublicPool>> | undefined;
    101   const stops: Array<() => void> = [];
    102   try {
    103     await t.test(
    104       'repeated acquisition shares an opaque fixed-origin pool',
    105       () => {
    106         pool = getPublicPool(policy);
    107         assert.ok(pool);
    108         assert.equal(getPublicPool(policy), pool);
    109         assert.deepEqual(Object.keys(pool), []);
    110         assert.ok(Object.isFrozen(pool));
    111         assert.deepEqual(publicPoolOrigins(pool), origins);
    112         assert.equal(constructed, 0);
    113         const detached = publicPoolOrigins(pool) as string[];
    114         detached.push('wss://unapproved.example.org');
    115         assert.deepEqual(publicPoolOrigins(pool), origins);
    116       }
    117     );
    118     assert.ok(pool);
    119     await t.test(
    120       'two scopes reuse sockets and unsolicited AUTH never signs',
    121       async () => {
    122         const eose = () =>
    123           new Promise<void>((resolve, reject) => {
    124             const seen = new Set<string>();
    125             stops.push(
    126               subscribePublicPool(
    127                 pool!,
    128                 [{ kinds: [30402], limit: 1 }],
    129                 (message) => {
    130                   if (message.type === 'ERROR')
    131                     reject(
    132                       message.error instanceof Error
    133                         ? message.error
    134                         : new Error('Fixture relay request failed')
    135                     );
    136                   if (message.type === 'EOSE') {
    137                     seen.add(message.from);
    138                     if (seen.size === origins.length) resolve();
    139                   }
    140                 }
    141               )
    142             );
    143           });
    144         await eose();
    145         await eose();
    146         assert.equal(constructed, 2);
    147         assert.equal(server.clients.size, 2);
    148         assert.equal(extensionCalls, 0);
    149         assert.equal(frames.filter((frame) => frame[0] === 'REQ').length, 4);
    150         assert.ok(
    151           frames.every((frame) => frame[0] !== 'AUTH' && frame[0] !== 'EVENT')
    152         );
    153         assert.throws(
    154           () => subscribePublicPool(pool!, (() => []) as never, () => {}),
    155           /public_pool_filters_invalid/
    156         );
    157         assert.throws(
    158           () => publicPoolOrigins({} as never),
    159           /public_pool_invalid/
    160         );
    161       }
    162     );
    163     await t.test(
    164       'terminal shutdown closes owned sockets and rejects stale use',
    165       async () => {
    166         const closed = sockets.map((socket) => once(socket, 'close'));
    167         closePublicPool(pool!);
    168         await Promise.all(closed);
    169         assert.equal(server.clients.size, 0);
    170         assert.ok(
    171           sockets.every((socket) => socket.readyState === WebSocket.CLOSED)
    172         );
    173         for (const stop of stops) stop();
    174         closePublicPool(pool!);
    175         assert.throws(() => getPublicPool(policy), /public_pool_closed/);
    176         assert.throws(
    177           () => subscribePublicPool(pool!, [{}], () => {}),
    178           /public_pool_closed/
    179         );
    180         assert.equal(constructed, 2);
    181         assert.equal(extensionCalls, 0);
    182       }
    183     );
    184   } finally {
    185     if (pool) closePublicPool(pool);
    186     for (const socket of server.clients) socket.terminate();
    187     await new Promise<void>((resolve, reject) =>
    188       server.close((error) => (error ? reject(error) : resolve()))
    189     );
    190     globalThis.WebSocket = originalSocket;
    191     globalThis.fetch = originalFetch;
    192     Reflect.deleteProperty(globalThis, 'window');
    193   }
    194 });
    195 
    196 // Actual SDK lifecycle with an inert socket, not real relay qualification.
    197 await test('callback and failed-close cleanup preserve pool ownership', async (t) => {
    198   const originalSocket = globalThis.WebSocket;
    199   const policy = validateRelayPolicy(
    200     JSON.stringify({
    201       schemaVersion: 1,
    202       public: [
    203         {
    204           origin: 'wss://relay.example.org',
    205           read: true,
    206           write: false,
    207           nip50: false
    208         }
    209       ],
    210       inbox: [],
    211       postingEnabled: false,
    212       messagingEnabled: false,
    213       operatorDenylist: []
    214     })
    215   );
    216   assert.ok(policy);
    217   class InertSocket {
    218     static OPEN = 1;
    219     static CLOSED = 3;
    220     readyState = 0;
    221     onopen?: () => void;
    222     onclose?: (event: { wasClean: boolean }) => void;
    223     readonly timer: ReturnType<typeof setTimeout>;
    224     constructor(url: string) {
    225       assert.equal(new URL(url).origin, 'wss://relay.example.org');
    226       this.timer = setTimeout(() => {
    227         this.readyState = 1;
    228         this.onopen?.();
    229       }, 0);
    230     }
    231     send() {}
    232     close() {
    233       clearTimeout(this.timer);
    234       this.readyState = 3;
    235       this.onclose?.({ wasClean: true });
    236     }
    237   }
    238   Object.defineProperty(globalThis, 'window', {
    239     configurable: true,
    240     value: {}
    241   });
    242   globalThis.WebSocket = InertSocket as unknown as typeof globalThis.WebSocket;
    243   try {
    244     await t.test(
    245       'synchronous OPEN shutdown retains no group subscriber',
    246       async () => {
    247         const adapter = (await import(
    248           new URL('../../src/lib/nostr/public-pool.ts', import.meta.url).href +
    249             '?hcp028-reentrant'
    250         )) as typeof import('../../src/lib/nostr/public-pool.ts');
    251         const groups: ReturnType<RelayPool['group']>[] = [];
    252         const group = Reflect.get<RelayPool, 'group'>(
    253           RelayPool.prototype,
    254           'group'
    255         );
    256         RelayPool.prototype.group = function (
    257           this: RelayPool,
    258           ...args: Parameters<RelayPool['group']>
    259         ) {
    260           const value = group.apply(this, args);
    261           groups.push(value);
    262           return value;
    263         };
    264         let stop: (() => void) | undefined;
    265         try {
    266           const pool = adapter.getPublicPool(policy);
    267           assert.ok(pool);
    268           let opens = 0;
    269           stop = adapter.subscribePublicPool(
    270             pool,
    271             [{ limit: 1 }],
    272             (message) => {
    273               if (message.type === 'OPEN') {
    274                 opens++;
    275                 adapter.closePublicPool(pool);
    276               }
    277             }
    278           );
    279           assert.equal(opens, 1);
    280           assert.equal(groups.length, 1);
    281           // Test-only inspection of the actual SDK's retained subscription.
    282           const stream = (groups[0] as unknown as { readonly relays$: unknown })
    283             .relays$;
    284           assert.ok(
    285             stream &&
    286               typeof stream === 'object' &&
    287               'observers' in stream &&
    288               Array.isArray(stream.observers)
    289           );
    290           assert.equal(stream.observers.length, 0);
    291         } finally {
    292           stop?.();
    293           RelayPool.prototype.group = group;
    294         }
    295       }
    296     );
    297     await t.test(
    298       'failed SDK shutdown stays closed to traffic and can retry cleanup',
    299       async () => {
    300         const adapter = (await import(
    301           new URL('../../src/lib/nostr/public-pool.ts', import.meta.url).href +
    302             '?hcp028-close-retry'
    303         )) as typeof import('../../src/lib/nostr/public-pool.ts');
    304         const close = Reflect.get<RelayPool, 'close'>(
    305           RelayPool.prototype,
    306           'close'
    307         );
    308         let calls = 0;
    309         const instances: RelayPool[] = [];
    310         RelayPool.prototype.close = function (this: RelayPool) {
    311           instances.push(this);
    312           calls++;
    313           if (calls === 1) throw new Error('HC_TEST_ONLY_SDK_CLOSE_FAILURE');
    314           close.call(this);
    315         };
    316         try {
    317           const pool = adapter.getPublicPool(policy);
    318           assert.ok(pool);
    319           const stop = adapter.subscribePublicPool(
    320             pool,
    321             [{ limit: 1 }],
    322             () => {}
    323           );
    324           assert.throws(
    325             () => adapter.closePublicPool(pool),
    326             /public_pool_close_failed/
    327           );
    328           assert.throws(
    329             () => adapter.getPublicPool(policy),
    330             /public_pool_closed/
    331           );
    332           assert.throws(
    333             () => adapter.subscribePublicPool(pool, [{}], () => {}),
    334             /public_pool_closed/
    335           );
    336           adapter.closePublicPool(pool);
    337           stop();
    338           assert.equal(calls, 2);
    339           assert.equal(instances[0]?.relays.size, 0);
    340           assert.equal(instances[1], instances[0]);
    341         } finally {
    342           RelayPool.prototype.close = close;
    343           if (instances[0]) close.call(instances[0]);
    344         }
    345       }
    346     );
    347   } finally {
    348     globalThis.WebSocket = originalSocket;
    349     Reflect.deleteProperty(globalThis, 'window');
    350   }
    351 });