inbox-discovery.test.ts (7341B)
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 { finalizeEvent } from 'applesauce-core/helpers'; 6 import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; 7 import { 8 createPublicRuntimeContext, 9 mountPublicRuntime, 10 createPublicView, 11 beginPublicViewRun, 12 subscribePublicView, 13 closePublicRuntime 14 } from '../../src/lib/runtime/public-runtime.ts'; 15 import { 16 resolveInboxPreference, 17 inboxResolutionSnapshot 18 } from '../../src/lib/messaging/resolve-inbox.ts'; 19 import { inboxPreferenceWire } from '../../src/lib/nostr/inbox-preferences.ts'; 20 import { publicRunSnapshot } from '../../src/lib/nostr/request-scope.ts'; 21 22 void test('actual anonymous SDK discovers only fixed recipient10050 sources and preserves decoded extras independently of public catalog', async () => { 23 const origins = ['wss://one.example.org', 'wss://two.example.org']; 24 const key = crypto.getRandomValues(new Uint8Array(32)); 25 let old, newer, profile; 26 try { 27 old = finalizeEvent( 28 { 29 kind: 10050, 30 created_at: 100, 31 tags: [ 32 ['relay', origins[0]], 33 ['unknown', 'keep'] 34 ], 35 content: 'original' 36 }, 37 key 38 ); 39 newer = finalizeEvent( 40 { kind: 10050, created_at: 200, tags: [['relay']], content: '' }, 41 key 42 ); 43 profile = finalizeEvent( 44 { kind: 0, created_at: 100, tags: [], content: '{}' }, 45 key 46 ); 47 } finally { 48 key.fill(0); 49 } 50 const servers = origins.map( 51 () => new WebSocketServer({ host: '127.0.0.1', port: 0, maxPayload: 8192 }) 52 ); 53 const sockets: WebSocket[] = [], 54 requests: { origin: string; filter: unknown }[] = []; 55 let closed = 0, 56 catalogSeen = () => {}, 57 allClosed = () => {}, 58 nextClosed = () => {}; 59 const seen = [0, 0]; 60 const catalog = new Promise<void>((resolve) => { 61 catalogSeen = resolve; 62 }), 63 finished = new Promise<void>((resolve) => { 64 allClosed = resolve; 65 }), 66 nextFinished = new Promise<void>((resolve) => { 67 nextClosed = resolve; 68 }); 69 for (let index = 0; index < servers.length; index++) 70 servers[index].on('connection', (socket) => { 71 sockets.push(socket); 72 socket.on('message', (bytes) => { 73 const buffer = Array.isArray(bytes) 74 ? Buffer.concat(bytes) 75 : Buffer.isBuffer(bytes) 76 ? bytes 77 : Buffer.from(bytes); 78 const frame = JSON.parse(buffer.toString('utf8')) as unknown[]; 79 if (frame[0] === 'REQ') { 80 const filter = frame[2] as { 81 kinds: number[]; 82 authors?: string[]; 83 limit: number; 84 }; 85 requests.push({ origin: origins[index], filter }); 86 const id = String(frame[1]); 87 if (filter.kinds[0] === 10050) { 88 seen[index]++; 89 assert.deepEqual(filter, { 90 kinds: [10050], 91 authors: [old.pubkey], 92 limit: 200 93 }); 94 socket.send( 95 JSON.stringify([ 96 'EVENT', 97 id, 98 seen[index] > 1 || index === 0 99 ? { ...old, extra: { items: ['keep', null, true] } } 100 : newer 101 ]) 102 ); 103 socket.send(JSON.stringify(['EOSE', id])); 104 } else { 105 socket.send(JSON.stringify(['EVENT', id, profile])); 106 } 107 } else if (frame[0] === 'CLOSE') { 108 closed++; 109 if (closed === 2) allClosed(); 110 if (closed === 4) nextClosed(); 111 } 112 assert.notEqual(frame[0], 'AUTH'); 113 assert.notEqual(frame[0], 'EVENT'); 114 }); 115 }); 116 await Promise.all(servers.map((server) => once(server, 'listening'))); 117 const ports = servers.map((server) => { 118 const address = server.address(); 119 assert.ok(address && typeof address !== 'string'); 120 return address.port; 121 }); 122 const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'), 123 oldSocket = globalThis.WebSocket; 124 class FixtureSocket extends WebSocket { 125 constructor(url: string | URL) { 126 const index = origins.indexOf(String(url).replace(/\/$/, '')); 127 assert.ok(index >= 0); 128 super(`ws://127.0.0.1:${ports[index]}`); 129 } 130 } 131 Object.defineProperty(globalThis, 'window', { 132 configurable: true, 133 value: {} 134 }); 135 globalThis.WebSocket = 136 FixtureSocket as unknown as typeof globalThis.WebSocket; 137 const policy = validateRelayPolicy( 138 JSON.stringify({ 139 schemaVersion: 1, 140 public: origins.map((origin) => ({ 141 origin, 142 read: true, 143 write: false, 144 nip50: false 145 })), 146 inbox: [{ origin: 'wss://archive.example.org', read: true, write: true }], 147 postingEnabled: false, 148 messagingEnabled: false, 149 operatorDenylist: [] 150 }) 151 )!; 152 const context = createPublicRuntimeContext(), 153 runtime = mountPublicRuntime(context, policy)!, 154 view = createPublicView(runtime), 155 run = beginPublicViewRun(view), 156 catalogView = createPublicView(runtime), 157 catalogRun = beginPublicViewRun(catalogView); 158 try { 159 subscribePublicView( 160 catalogView, 161 catalogRun, 162 'profile', 163 [{ kinds: [0], authors: [old.pubkey], limit: 200 }], 164 () => catalogSeen() 165 ); 166 const resolver = resolveInboxPreference(view, run, old.pubkey); 167 await Promise.all([finished, catalog]); 168 const result = inboxResolutionSnapshot(resolver); 169 assert.equal(result.status, 'unsupported'); 170 assert.equal(result.knownBase?.id, newer.id); 171 assert.equal(result.coverage, 'bounded-eose'); 172 assert.equal(result.sources.length, 2); 173 assert.equal(publicRunSnapshot(run).ingress.deliveries, 2); 174 assert.ok(publicRunSnapshot(catalogRun).active); 175 const another = beginPublicViewRun(view); 176 assert.equal(inboxResolutionSnapshot(resolver).status, 'inconclusive'); 177 assert.ok(publicRunSnapshot(another).active); 178 const compatible = resolveInboxPreference(view, another, old.pubkey); 179 assert.equal(resolveInboxPreference(view, another, old.pubkey), compatible); 180 await nextFinished; 181 const compatibleResult = inboxResolutionSnapshot(compatible); 182 assert.equal(compatibleResult.status, 'ready'); 183 assert.equal(compatibleResult.knownBase?.id, old.id); 184 const preserved: unknown = JSON.parse( 185 inboxPreferenceWire(compatibleResult.head!)! 186 ); 187 assert.deepEqual(preserved, { 188 ...(JSON.parse(JSON.stringify(old)) as object), 189 extra: { items: ['keep', null, true] } 190 }); 191 assert.equal( 192 requests.filter( 193 (row) => (row.filter as { kinds: number[] }).kinds[0] === 10050 194 ).length, 195 4 196 ); 197 assert.equal(result.wireProvenance, 'decoded-sdk-json'); 198 assert.ok(inboxPreferenceWire(result.head!)?.includes('"relay"')); 199 } finally { 200 closePublicRuntime(context); 201 for (const socket of sockets) socket.terminate(); 202 await Promise.all( 203 servers.map( 204 (server) => 205 new Promise<void>((resolve, reject) => 206 server.close((error) => (error ? reject(error) : resolve())) 207 ) 208 ) 209 ); 210 globalThis.WebSocket = oldSocket; 211 if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); 212 else Reflect.deleteProperty(globalThis, 'window'); 213 } 214 });