app

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

hostile-relay.test.ts (4054B)


      1 import test from 'node:test';
      2 import assert from 'node:assert/strict';
      3 import { once } from 'node:events';
      4 import { readFile } from 'node:fs/promises';
      5 import WebSocket, { WebSocketServer } from 'ws';
      6 import { validateRelayPolicy } from '../../src/lib/config/relays.ts';
      7 import {
      8   getPublicPool,
      9   subscribePublicPool,
     10   closePublicPool
     11 } from '../../src/lib/nostr/public-pool.ts';
     12 import {
     13   createPublicIngress,
     14   admitPublicEvent,
     15   publicIngressStats
     16 } from '../../src/lib/nostr/ingress.ts';
     17 
     18 // HC_TEST_ONLY_RELAY: actual SDK sockets map only to an isolated loopback server.
     19 await test('actual relay batch isolates hostile candidates before trusted projection', async () => {
     20   const corpus = JSON.parse(
     21     await readFile(
     22       new URL(
     23         '../../../contracts/interop/food_availability/corpus.v1.json',
     24         import.meta.url
     25       ),
     26       'utf8'
     27     )
     28   ) as { vectors: { id: string; signed_wires: Record<string, string> }[] };
     29   const raw = corpus.vectors.find((row) => row.id.endsWith('_014'))!
     30     .signed_wires.event;
     31   const valid = JSON.parse(raw) as Record<string, unknown>;
     32   const candidates = [
     33     { ...valid, sig: '0'.repeat(128) },
     34     { ...valid, content: 'untrusted mutation' },
     35     { ...valid, created_at: Number.MAX_SAFE_INTEGER + 1 },
     36     valid,
     37     valid,
     38     { ...valid, tags: [['d', 'a'], {}] }
     39   ];
     40   const server = new WebSocketServer({
     41     host: '127.0.0.1',
     42     port: 0,
     43     maxPayload: 4096
     44   });
     45   server.on('connection', (socket) =>
     46     socket.on('message', (bytes) => {
     47       const buffer = Array.isArray(bytes)
     48         ? Buffer.concat(bytes)
     49         : Buffer.isBuffer(bytes)
     50           ? bytes
     51           : Buffer.from(bytes);
     52       const frame: unknown = JSON.parse(buffer.toString('utf8'));
     53       assert.ok(Array.isArray(frame));
     54       if (frame[0] !== 'REQ') return;
     55       for (const event of candidates)
     56         socket.send(JSON.stringify(['EVENT', frame[1], event]));
     57       socket.send(JSON.stringify(['EOSE', frame[1]]));
     58     })
     59   );
     60   await once(server, 'listening');
     61   const address = server.address();
     62   assert.ok(address && typeof address !== 'string');
     63   const port = address.port;
     64   const originalSocket = globalThis.WebSocket;
     65   assert.equal(
     66     Object.getOwnPropertyDescriptor(globalThis, 'window'),
     67     undefined
     68   );
     69   class FixtureSocket extends WebSocket {
     70     constructor(url: string | URL) {
     71       assert.equal(String(url).replace(/\/$/, ''), 'wss://hostile.example.org');
     72       super(`ws://127.0.0.1:${port}`);
     73     }
     74   }
     75   Object.defineProperty(globalThis, 'window', {
     76     configurable: true,
     77     value: {}
     78   });
     79   globalThis.WebSocket =
     80     FixtureSocket as unknown as typeof globalThis.WebSocket;
     81   const policy = validateRelayPolicy(
     82     JSON.stringify({
     83       schemaVersion: 1,
     84       public: [
     85         {
     86           origin: 'wss://hostile.example.org',
     87           read: true,
     88           write: false,
     89           nip50: false
     90         }
     91       ],
     92       inbox: [],
     93       postingEnabled: false,
     94       messagingEnabled: false,
     95       operatorDenylist: []
     96     })
     97   );
     98   assert.ok(policy);
     99   const pool = getPublicPool(policy)!;
    100   const owner = createPublicIngress();
    101   const outcomes: string[] = [];
    102   try {
    103     await new Promise<void>((resolve) =>
    104       subscribePublicPool(pool, [{ kinds: [30402], limit: 200 }], (message) => {
    105         if (message.type === 'EVENT')
    106           outcomes.push(admitPublicEvent(owner, message.event).status);
    107         if (message.type === 'EOSE') resolve();
    108       })
    109     );
    110     assert.deepEqual(outcomes, [
    111       'rejected',
    112       'rejected',
    113       'rejected',
    114       'accepted',
    115       'duplicate',
    116       'rejected'
    117     ]);
    118     assert.equal(publicIngressStats(owner).deliveries, 6);
    119     assert.ok(publicIngressStats(owner).chargedBytes > 0);
    120     assert.equal(publicIngressStats(owner).stopped, false);
    121   } finally {
    122     closePublicPool(pool);
    123     await new Promise<void>((resolve, reject) =>
    124       server.close((error) => (error ? reject(error) : resolve()))
    125     );
    126     globalThis.WebSocket = originalSocket;
    127     Reflect.deleteProperty(globalThis, 'window');
    128   }
    129 });