request-result.test.ts (15580B)
1 import { describe, expect, it } from 'vitest'; 2 import { readFileSync } from 'node:fs'; 3 import { EventStore } from 'applesauce-core'; 4 import { getSeenRelays } from 'applesauce-core/helpers'; 5 import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; 6 import { 7 createPublicIngress, 8 publicIngressStats 9 } from '../../src/lib/nostr/ingress.ts'; 10 import { 11 verifyEnvelope, 12 verifiedEnvelopeSnapshot 13 } from '../../src/lib/nostr/verified-envelope.ts'; 14 import { 15 createObservationJournal, 16 createObservationContext, 17 recordPublicObservation, 18 exactPublicObservation, 19 publicObservations, 20 observationJournalStats, 21 closeObservationJournal 22 } from '../../src/lib/catalog/observations.ts'; 23 import { 24 createPublicRequestResult, 25 handlePublicRequestMessage, 26 publicRequestSnapshot, 27 disposePublicRequestResult 28 } from '../../src/lib/nostr/request-result.ts'; 29 const origins = ['wss://one.example.org', 'wss://two.example.org']; 30 const policy = validateRelayPolicy( 31 JSON.stringify({ 32 schemaVersion: 1, 33 public: origins.map((origin) => ({ 34 origin, 35 read: true, 36 write: false, 37 nip50: false 38 })), 39 inbox: [], 40 postingEnabled: false, 41 messagingEnabled: false, 42 operatorDenylist: [] 43 }) 44 )!; 45 const corpus = JSON.parse( 46 readFileSync( 47 new URL( 48 '../../../contracts/interop/food_availability/corpus.v1.json', 49 import.meta.url 50 ), 51 'utf8' 52 ) 53 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 54 const wires = corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires; 55 function proof(raw: string) { 56 const result = verifyEnvelope(raw); 57 if (!result.ok) throw new Error('Invalid signed test vector'); 58 return result.value; 59 } 60 const current = proof(wires.current); 61 const previous = proof(wires.previous); 62 const currentEvent = () => 63 JSON.parse(wires.current) as NonNullable< 64 ReturnType<typeof verifiedEnvelopeSnapshot> 65 >; 66 function setup() { 67 const journal = createObservationJournal(policy); 68 const ingress = createPublicIngress(); 69 const result = createPublicRequestResult(policy, ingress, journal); 70 return { journal, ingress, result }; 71 } 72 describe('exact public source observations', () => { 73 it('binds every request in a journal to one shared admission owner', () => { 74 const { journal, ingress } = setup(); 75 expect(() => 76 createPublicRequestResult(policy, createPublicIngress(), journal) 77 ).toThrow('public_request_ingress_changed'); 78 expect(publicIngressStats(ingress).deliveries).toBe(0); 79 expect(observationJournalStats(journal).rows).toBe(0); 80 }); 81 it('rejects a different source manifest before request observation creation', () => { 82 const { journal, ingress } = setup(); 83 const different = validateRelayPolicy( 84 JSON.stringify({ 85 schemaVersion: 1, 86 public: [ 87 { origin: origins[0], read: true, write: false, nip50: false } 88 ], 89 inbox: [], 90 postingEnabled: false, 91 messagingEnabled: false, 92 operatorDenylist: [] 93 }) 94 )!; 95 expect(() => 96 createPublicRequestResult(different, ingress, journal) 97 ).toThrow('request_observation_policy_changed'); 98 expect(publicIngressStats(ingress).deliveries).toBe(0); 99 expect(observationJournalStats(journal).rows).toBe(0); 100 }); 101 it('does not cache authentic events outside the shared approved public inventory', () => { 102 const { journal, ingress, result } = setup(); 103 const raw = corpus.vectors.find((row) => row.id.endsWith('_019'))! 104 .signed_wires.event; 105 expect(verifyEnvelope(raw).ok).toBe(true); 106 expect( 107 handlePublicRequestMessage(result, { 108 type: 'EVENT', 109 from: origins[0], 110 id: 'a', 111 event: JSON.parse(raw) as ReturnType<typeof currentEvent> 112 }).status 113 ).toBe('not_public'); 114 expect( 115 handlePublicRequestMessage(result, { 116 type: 'EVENT', 117 from: origins[0], 118 id: 'a', 119 event: currentEvent() 120 }).status 121 ).toBe('accepted'); 122 expect( 123 publicObservations(journal, publicRequestSnapshot(result).context) 124 ).toHaveLength(1); 125 expect(publicIngressStats(ingress).deliveries).toBe(2); 126 }); 127 it('deduplicates only the exact event/source/request tuple', () => { 128 const journal = createObservationJournal(policy); 129 const first = createObservationContext(journal); 130 const second = createObservationContext(journal); 131 expect(recordPublicObservation(journal, first, origins[0], current)).toBe( 132 true 133 ); 134 expect(recordPublicObservation(journal, first, origins[0], current)).toBe( 135 true 136 ); 137 expect(recordPublicObservation(journal, first, origins[1], current)).toBe( 138 true 139 ); 140 expect(recordPublicObservation(journal, second, origins[0], current)).toBe( 141 true 142 ); 143 expect(publicObservations(journal, first)).toHaveLength(2); 144 expect(publicObservations(journal, second)).toHaveLength(1); 145 expect(observationJournalStats(journal).rows).toBe(3); 146 (publicObservations(journal, first) as unknown as unknown[]).pop(); 147 expect(publicObservations(journal, first)).toHaveLength(2); 148 }); 149 it('never derives exact receipt from actual SDK cross-version seen metadata', () => { 150 const journal = createObservationJournal(policy); 151 const context = createObservationContext(journal); 152 const sdk = new EventStore({ keepOldVersions: false }); 153 const newer = currentEvent(); 154 const older = JSON.parse(wires.previous) as typeof newer; 155 sdk.add(newer, origins[0]); 156 sdk.add(older, origins[1]); 157 expect(getSeenRelays(newer)?.has(origins[1])).toBe(true); 158 recordPublicObservation(journal, context, origins[0], current); 159 recordPublicObservation(journal, context, origins[1], previous); 160 expect(exactPublicObservation(journal, context, newer.id, origins[0])).toBe( 161 true 162 ); 163 expect(exactPublicObservation(journal, context, newer.id, origins[1])).toBe( 164 false 165 ); 166 expect(exactPublicObservation(journal, context, older.id, origins[1])).toBe( 167 true 168 ); 169 sdk.dispose(); 170 }); 171 it('rejects forged proof, unapproved source and another journal context', () => { 172 const journal = createObservationJournal(policy); 173 const context = createObservationContext(journal); 174 expect( 175 recordPublicObservation( 176 journal, 177 context, 178 origins[0], 179 {} as typeof current 180 ) 181 ).toBe(false); 182 expect( 183 recordPublicObservation( 184 journal, 185 context, 186 'wss://hint.example.org', 187 current 188 ) 189 ).toBe(false); 190 const other = createObservationJournal(policy); 191 const alien = createObservationContext(other); 192 expect(() => 193 recordPublicObservation(journal, alien, origins[0], current) 194 ).toThrow('observation_context_invalid'); 195 expect(() => publicObservations({} as typeof journal, context)).toThrow( 196 'observation_journal_invalid' 197 ); 198 expect(observationJournalStats(journal).rows).toBe(0); 199 }); 200 it('charges duplicates while retaining their freshly verified exact source proof before store dedup', () => { 201 const { journal, ingress, result } = setup(); 202 const first = handlePublicRequestMessage(result, { 203 type: 'EVENT', 204 from: origins[0], 205 id: 'a', 206 event: currentEvent() 207 }); 208 const second = handlePublicRequestMessage(result, { 209 type: 'EVENT', 210 from: origins[1] + '/', 211 id: 'b', 212 event: currentEvent() 213 }); 214 expect(first.status).toBe('accepted'); 215 expect(second.status).toBe('duplicate'); 216 if (second.status === 'duplicate') 217 expect(verifiedEnvelopeSnapshot(second.value)?.id).toBe( 218 currentEvent().id 219 ); 220 const context = publicRequestSnapshot(result).context; 221 expect( 222 exactPublicObservation(journal, context, currentEvent().id, origins[0]) 223 ).toBe(true); 224 expect( 225 exactPublicObservation(journal, context, currentEvent().id, origins[1]) 226 ).toBe(true); 227 expect(publicIngressStats(ingress).deliveries).toBe(2); 228 expect(publicIngressStats(ingress).chargedBytes).toBeGreaterThan(0); 229 }); 230 it('retains valid evidence across a malformed candidate and failing source', () => { 231 const { journal, ingress, result } = setup(); 232 expect( 233 handlePublicRequestMessage(result, { 234 type: 'EVENT', 235 from: origins[0], 236 id: 'a', 237 event: { ...currentEvent(), sig: '0'.repeat(128) } 238 }).status 239 ).toBe('rejected'); 240 expect( 241 handlePublicRequestMessage(result, { 242 type: 'EVENT', 243 from: origins[0], 244 id: 'a', 245 event: currentEvent() 246 }).status 247 ).toBe('accepted'); 248 handlePublicRequestMessage(result, { 249 type: 'EOSE', 250 from: origins[0], 251 id: 'a' 252 }); 253 handlePublicRequestMessage(result, { 254 type: 'ERROR', 255 from: origins[1], 256 error: new Error('HC_TEST_ONLY_RAW_PRIVATE_ERROR') 257 }); 258 const snapshot = publicRequestSnapshot(result); 259 expect(snapshot.coverage).toBe('partial'); 260 expect(snapshot.definitiveAbsence).toBe(false); 261 expect(publicObservations(journal, snapshot.context)).toHaveLength(1); 262 expect(publicIngressStats(ingress).deliveries).toBe(2); 263 expect(JSON.stringify(snapshot)).not.toContain( 264 'HC_TEST_ONLY_RAW_PRIVATE_ERROR' 265 ); 266 }); 267 it('does not inspect or expose arbitrary relay reasons or error objects', () => { 268 const { result } = setup(); 269 let reads = 0; 270 handlePublicRequestMessage(result, { 271 type: 'CLOSED', 272 from: origins[0], 273 id: 'a', 274 get reason(): string { 275 reads++; 276 throw new Error('Untrusted relay text'); 277 } 278 }); 279 handlePublicRequestMessage(result, { 280 type: 'ERROR', 281 from: origins[1], 282 get error() { 283 reads++; 284 throw new Error('Untrusted error object'); 285 } 286 }); 287 expect(reads).toBe(0); 288 const snapshot = publicRequestSnapshot(result); 289 expect(snapshot.sources.map((row) => row.state)).toEqual([ 290 'closed', 291 'error' 292 ]); 293 expect(JSON.stringify(snapshot)).not.toContain('Untrusted'); 294 }); 295 it('ignores unknown source hints without letting them become observation authority', () => { 296 const { journal, ingress, result } = setup(); 297 expect( 298 handlePublicRequestMessage(result, { 299 type: 'EVENT', 300 from: 'wss://hint.example.org', 301 id: 'a', 302 event: currentEvent() 303 }).status 304 ).toBe('source_unknown'); 305 const snapshot = publicRequestSnapshot(result); 306 expect(publicObservations(journal, snapshot.context)).toEqual([]); 307 expect(publicIngressStats(ingress).deliveries).toBe(1); 308 expect(JSON.stringify(snapshot)).not.toContain('hint.example.org'); 309 }); 310 it('bounds journal rows across all request contexts at the approved delivery cap', () => { 311 const journal = createObservationJournal(policy); 312 for (let i = 0; i < 2000; i++) 313 expect( 314 recordPublicObservation( 315 journal, 316 createObservationContext(journal), 317 origins[0], 318 current 319 ) 320 ).toBe(true); 321 expect( 322 recordPublicObservation( 323 journal, 324 createObservationContext(journal), 325 origins[0], 326 current 327 ) 328 ).toBe(false); 329 expect(observationJournalStats(journal)).toEqual({ 330 rows: 2000, 331 closed: false 332 }); 333 }); 334 it('cannot turn a degraded empty request or bounded EOSE into definitive absence', () => { 335 const { result } = setup(); 336 handlePublicRequestMessage(result, { 337 type: 'EOSE', 338 from: origins[0], 339 id: 'a' 340 }); 341 expect(publicRequestSnapshot(result).coverage).toBe('partial'); 342 handlePublicRequestMessage(result, { 343 type: 'EOSE', 344 from: origins[1], 345 id: 'b' 346 }); 347 expect(publicRequestSnapshot(result).coverage).toBe('bounded-eose'); 348 expect(publicRequestSnapshot(result).definitiveAbsence).toBe(false); 349 }); 350 it('disposes only its request and preserves another request and valid observations', () => { 351 const { journal, ingress, result } = setup(); 352 const other = createPublicRequestResult(policy, ingress, journal); 353 handlePublicRequestMessage(result, { 354 type: 'EVENT', 355 from: origins[0], 356 id: 'a', 357 event: currentEvent() 358 }); 359 const context = publicRequestSnapshot(result).context; 360 disposePublicRequestResult(result); 361 expect( 362 handlePublicRequestMessage(result, { 363 type: 'EVENT', 364 from: origins[1], 365 id: 'b', 366 event: currentEvent() 367 }).status 368 ).toBe('inactive'); 369 expect(publicObservations(journal, context)).toHaveLength(1); 370 expect( 371 handlePublicRequestMessage(other, { 372 type: 'EVENT', 373 from: origins[1], 374 id: 'b', 375 event: currentEvent() 376 }).status 377 ).toBe('duplicate'); 378 expect( 379 publicObservations(journal, publicRequestSnapshot(other).context) 380 ).toHaveLength(1); 381 }); 382 it('keeps snapshots detached and explicit journal closure terminal', () => { 383 const { journal, result } = setup(); 384 handlePublicRequestMessage(result, { 385 type: 'EVENT', 386 from: origins[0], 387 id: 'a', 388 event: currentEvent() 389 }); 390 const snapshot = publicRequestSnapshot(result); 391 (snapshot.sources as unknown as unknown[]).pop(); 392 expect(publicRequestSnapshot(result).sources).toHaveLength(2); 393 closeObservationJournal(journal); 394 expect(publicObservations(journal, snapshot.context)).toEqual([]); 395 expect( 396 recordPublicObservation(journal, snapshot.context, origins[0], current) 397 ).toBe(false); 398 expect(() => createObservationContext(journal)).toThrow( 399 'observations_closed' 400 ); 401 }); 402 }); 403 404 describe('qualified sample observation scope', () => { 405 const samplePolicy = validateRelayPolicy( 406 JSON.stringify({ 407 schemaVersion: 1, 408 public: origins.map((origin, index) => ({ 409 origin, 410 read: true, 411 write: false, 412 nip50: index === 0 413 })), 414 inbox: [], 415 postingEnabled: false, 416 messagingEnabled: false, 417 operatorDenylist: [] 418 }) 419 )!; 420 it('bounds observations to the selected qualified source while charging unexpected deliveries', () => { 421 const journal = createObservationJournal(samplePolicy), 422 ingress = createPublicIngress(); 423 const result = createPublicRequestResult( 424 samplePolicy, 425 ingress, 426 journal, 427 origins[0] 428 ); 429 expect( 430 handlePublicRequestMessage(result, { 431 type: 'EVENT', 432 id: 'sample', 433 from: origins[1], 434 event: currentEvent() 435 }).status 436 ).toBe('source_unknown'); 437 expect(publicIngressStats(ingress).deliveries).toBe(1); 438 expect(publicRequestSnapshot(result).sources).toHaveLength(1); 439 expect(observationJournalStats(journal).rows).toBe(0); 440 handlePublicRequestMessage(result, { 441 type: 'EOSE', 442 id: 'sample', 443 from: origins[0] 444 }); 445 expect(publicRequestSnapshot(result).coverage).toBe('bounded-eose'); 446 disposePublicRequestResult(result); 447 closeObservationJournal(journal); 448 }); 449 it('rejects an unqualified source before observation context allocation', () => { 450 const journal = createObservationJournal(samplePolicy), 451 ingress = createPublicIngress(), 452 before = observationJournalStats(journal); 453 expect(() => 454 createPublicRequestResult(samplePolicy, ingress, journal, origins[1]) 455 ).toThrow('nip50_source_unqualified'); 456 expect(observationJournalStats(journal)).toEqual(before); 457 expect(publicIngressStats(ingress).deliveries).toBe(0); 458 closeObservationJournal(journal); 459 }); 460 });