source-observations.test.ts (6584B)
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 getPublicStore, 14 insertPublicEnvelope, 15 closePublicStore, 16 publicStoreEnvelope 17 } from '../../src/lib/nostr/public-store.ts'; 18 import { 19 createPublicIngress, 20 publicIngressStats 21 } from '../../src/lib/nostr/ingress.ts'; 22 import { 23 createObservationJournal, 24 publicObservations, 25 exactPublicObservation 26 } from '../../src/lib/catalog/observations.ts'; 27 import { 28 createPublicRequestResult, 29 handlePublicRequestMessage, 30 publicRequestSnapshot, 31 disposePublicRequestResult 32 } from '../../src/lib/nostr/request-result.ts'; 33 await test('actual SDK sources retain exact observations before store dedup and sanitize partial outcomes', async () => { 34 const corpus = JSON.parse( 35 await readFile( 36 new URL( 37 '../../../contracts/interop/food_availability/corpus.v1.json', 38 import.meta.url 39 ), 40 'utf8' 41 ) 42 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 43 const wires = corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires; 44 const current = JSON.parse(wires.current) as { id: string; sig: string }; 45 const previous = JSON.parse(wires.previous) as { id: string }; 46 const origins = ['wss://one.example.org', 'wss://two.example.org']; 47 const servers = origins.map( 48 () => new WebSocketServer({ host: '127.0.0.1', port: 0, maxPayload: 4096 }) 49 ); 50 const sockets: WebSocket[] = []; 51 for (const [index, server] of servers.entries()) { 52 server.on('connection', (socket) => { 53 sockets.push(socket); 54 socket.on('message', (bytes) => { 55 const buffer = Array.isArray(bytes) 56 ? Buffer.concat(bytes) 57 : Buffer.isBuffer(bytes) 58 ? bytes 59 : Buffer.from(bytes); 60 const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; 61 if (frame[0] !== 'REQ') return; 62 const id = frame[1]; 63 if (index === 0) { 64 socket.send(JSON.stringify(['EVENT', id, current])); 65 socket.send(JSON.stringify(['EVENT', id, current])); 66 socket.send( 67 JSON.stringify(['EVENT', id, { ...current, sig: '0'.repeat(128) }]) 68 ); 69 socket.send(JSON.stringify(['EOSE', id])); 70 } else { 71 socket.send(JSON.stringify(['EVENT', id, previous])); 72 socket.send( 73 JSON.stringify([ 74 'CLOSED', 75 id, 76 'HC_TEST_ONLY_PRIVATE_RAW_REASON <script>unsafe</script>' 77 ]) 78 ); 79 } 80 }); 81 }); 82 } 83 await Promise.all(servers.map((server) => once(server, 'listening'))); 84 const ports = servers.map((server) => { 85 const address = server.address(); 86 assert.ok(address && typeof address !== 'string'); 87 return address.port; 88 }); 89 const windowDescriptor = Object.getOwnPropertyDescriptor( 90 globalThis, 91 'window' 92 ); 93 const originalSocket = globalThis.WebSocket; 94 class FixtureSocket extends WebSocket { 95 constructor(url: string | URL) { 96 const origin = String(url).replace(/\/$/, ''); 97 const index = origins.indexOf(origin); 98 assert.notEqual(index, -1); 99 super(`ws://127.0.0.1:${ports[index]}`); 100 } 101 } 102 Object.defineProperty(globalThis, 'window', { 103 configurable: true, 104 value: {} 105 }); 106 globalThis.WebSocket = 107 FixtureSocket as unknown as typeof globalThis.WebSocket; 108 const policy = validateRelayPolicy( 109 JSON.stringify({ 110 schemaVersion: 1, 111 public: origins.map((origin) => ({ 112 origin, 113 read: true, 114 write: false, 115 nip50: false 116 })), 117 inbox: [], 118 postingEnabled: false, 119 messagingEnabled: false, 120 operatorDenylist: [] 121 }) 122 ); 123 assert.ok(policy); 124 const pool = getPublicPool(policy)!; 125 const store = getPublicStore()!; 126 const ingress = createPublicIngress(); 127 const journal = createObservationJournal(policy); 128 const result = createPublicRequestResult(policy, ingress, journal); 129 const statuses: string[] = []; 130 try { 131 await new Promise<void>((resolve) => 132 subscribePublicPool(pool, [{ kinds: [30402], limit: 200 }], (message) => { 133 const outcome = handlePublicRequestMessage(result, message); 134 if (message.type === 'EVENT') statuses.push(outcome.status); 135 if (outcome.status === 'accepted' || outcome.status === 'duplicate') 136 insertPublicEnvelope(store, outcome.value); 137 if ( 138 publicRequestSnapshot(result).sources.every( 139 (row) => row.state === 'eose' || row.state === 'closed' 140 ) 141 ) 142 resolve(); 143 }) 144 ); 145 const snapshot = publicRequestSnapshot(result); 146 assert.equal(snapshot.coverage, 'partial'); 147 assert.equal(snapshot.definitiveAbsence, false); 148 assert.equal(publicObservations(journal, snapshot.context).length, 2); 149 assert.equal( 150 exactPublicObservation(journal, snapshot.context, current.id, origins[0]), 151 true 152 ); 153 assert.equal( 154 exactPublicObservation(journal, snapshot.context, current.id, origins[1]), 155 false 156 ); 157 assert.equal( 158 exactPublicObservation( 159 journal, 160 snapshot.context, 161 previous.id, 162 origins[1] 163 ), 164 true 165 ); 166 assert.ok(publicStoreEnvelope(store, current.id)); 167 assert.ok(publicStoreEnvelope(store, previous.id)); 168 assert.equal(publicIngressStats(ingress).deliveries, 4); 169 assert.equal(statuses.filter((x) => x === 'accepted').length, 2); 170 assert.equal(statuses.filter((x) => x === 'duplicate').length, 1); 171 assert.equal(statuses.filter((x) => x === 'rejected').length, 1); 172 assert.doesNotMatch( 173 JSON.stringify(snapshot), 174 /HC_TEST_ONLY_PRIVATE_RAW_REASON|script|unsafe/ 175 ); 176 } finally { 177 disposePublicRequestResult(result); 178 closePublicStore(store); 179 closePublicPool(pool); 180 for (const socket of sockets) socket.terminate(); 181 await Promise.all( 182 servers.map( 183 (server) => 184 new Promise<void>((resolve, reject) => 185 server.close((error) => (error ? reject(error) : resolve())) 186 ) 187 ) 188 ); 189 globalThis.WebSocket = originalSocket; 190 if (windowDescriptor) 191 Object.defineProperty(globalThis, 'window', windowDescriptor); 192 else Reflect.deleteProperty(globalThis, 'window'); 193 } 194 });