rumor-plan.test.ts (11435B)
1 import { afterEach, expect, it, vi } from 'vitest'; 2 import { finalizeEvent, getEventHash } from 'applesauce-core/helpers'; 3 import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; 4 import { 5 captureEnquiryContext, 6 enquiryContextSnapshot, 7 type EnquiryContext 8 } from '../../src/lib/messaging/enquiry-context.ts'; 9 import { 10 createIdentitySession, 11 connectIdentity, 12 probeIdentityMessaging, 13 disconnectIdentity, 14 type IdentitySession 15 } from '../../src/lib/runtime/identity-session.ts'; 16 import { 17 captureEnquiryRumor, 18 captureReplyRumor, 19 rumorPlanSnapshot, 20 rumorEnvelopePlan, 21 stopRumorPlan, 22 bindFirstRumorReservation, 23 rumorReservationCommand, 24 type RumorPlan 25 } from '../../src/lib/messaging/rumor-plan.ts'; 26 const buyer = 27 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', 28 outsider = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; 29 const sessions: IdentitySession[] = []; 30 afterEach(() => { 31 for (const session of sessions) disconnectIdentity(session); 32 sessions.length = 0; 33 vi.unstubAllGlobals(); 34 }); 35 function food() { 36 const key = crypto.getRandomValues(new Uint8Array(32)); 37 try { 38 const event = finalizeEvent( 39 { 40 kind: 30402, 41 created_at: 1700000060, 42 content: 'Public carrots', 43 tags: [ 44 ['d', 'carrots'], 45 ['title', 'Carrots'], 46 ['summary', 'Fresh carrots'], 47 ['published_at', '1700000000'], 48 ['location', 'Victoria'], 49 ['price', '3.5', 'CAD'], 50 ['radroots:price_unit', 'lb'], 51 ['status', 'active'] 52 ] 53 }, 54 key 55 ); 56 const proof = verifyEnvelope(JSON.stringify(event)); 57 if (!proof.ok) throw Error('invalid public test fixture'); 58 const context = captureEnquiryContext(proof.value); 59 if (!context) throw Error('invalid Food context'); 60 return { event, context }; 61 } finally { 62 key.fill(0); 63 } 64 } 65 async function identity(owner = buyer) { 66 let encrypts = 0, 67 decrypts = 0, 68 signs = 0; 69 vi.stubGlobal('window', { 70 nostr: { 71 getPublicKey: () => Promise.resolve(owner), 72 signEvent: () => { 73 signs++; 74 return Promise.reject(Error('unexpected sign')); 75 }, 76 nip44: { 77 encrypt: (_peer: string, text: string) => { 78 encrypts++; 79 return Promise.resolve('fixture:' + text); 80 }, 81 decrypt: (_peer: string, text: string) => { 82 decrypts++; 83 return Promise.resolve(text.slice(8)); 84 } 85 } 86 } 87 }); 88 const session = createIdentitySession(); 89 sessions.push(session); 90 await connectIdentity(session); 91 await probeIdentityMessaging(session, 'reviewed_self_copy'); 92 return { session, counts: () => ({ encrypts, decrypts, signs }) }; 93 } 94 function required(value: RumorPlan | undefined) { 95 if (!value) throw Error('expected local rumor plan'); 96 return value; 97 } 98 it('binds current observed owner and genuine Food seller without signing/encrypting or persisting', async () => { 99 const f = food(), 100 owner = await identity(), 101 before = owner.counts(); 102 const plan = required( 103 captureEnquiryRumor(owner.session, f.context, 'Tomorrow?', 1700000100) 104 ); 105 const snapshot = rumorPlanSnapshot(plan)!, 106 wire = JSON.parse(snapshot.wire) as { 107 pubkey: string; 108 tags: string[][]; 109 id: string; 110 kind: number; 111 created_at: number; 112 content: string; 113 }; 114 expect(snapshot.owner).toBe(buyer); 115 expect(snapshot.peer).toBe(f.event.pubkey); 116 expect(wire.pubkey).toBe(buyer); 117 expect(wire.tags).toEqual([['p', f.event.pubkey]]); 118 expect(wire.id).toBe(getEventHash(wire)); 119 expect(wire).not.toHaveProperty('sig'); 120 expect(wire.created_at).toBe(1700000100); 121 expect(owner.counts()).toEqual(before); 122 }); 123 it('exactly peer and self destinations share one immutable rumor including its original p', async () => { 124 const f = food(), 125 owner = await identity(), 126 plan = required(captureEnquiryRumor(owner.session, f.context, '', 100)); 127 const copies = rumorEnvelopePlan(plan)!; 128 expect(copies.map((row) => [row.role, row.recipient])).toEqual([ 129 ['peer', f.event.pubkey], 130 ['self_archive', buyer] 131 ]); 132 expect(copies[0].rumorWire).toBe(copies[1].rumorWire); 133 for (const row of copies) 134 expect((JSON.parse(row.rumorWire) as { tags: string[][] }).tags).toEqual([ 135 ['p', f.event.pubkey] 136 ]); 137 const detached = copies as { recipient: string; rumorWire: string }[]; 138 detached[0].recipient = outsider; 139 detached[0].rumorWire = '{}'; 140 expect(rumorEnvelopePlan(plan)![0].recipient).toBe(f.event.pubkey); 141 expect(rumorEnvelopePlan(plan)![0].rumorWire).toBe(copies[1].rumorWire); 142 }); 143 it('body and detached display/context cannot redirect actual recipient', async () => { 144 const f = food(), 145 owner = await identity(), 146 copy = enquiryContextSnapshot(f.context)! as { peer: string }; 147 copy.peer = outsider; 148 const plan = required( 149 captureEnquiryRumor(owner.session, f.context, 'Send to ' + outsider, 100) 150 ); 151 expect(rumorPlanSnapshot(plan)!.peer).toBe(f.event.pubkey); 152 expect( 153 captureEnquiryRumor( 154 owner.session, 155 copy as unknown as EnquiryContext, 156 '', 157 100 158 ) 159 ).toBeUndefined(); 160 }); 161 it('rejects own listing, guest/forged identity, forged context and invalid time', async () => { 162 const f = food(), 163 seller = await identity(f.event.pubkey); 164 expect( 165 captureEnquiryRumor(seller.session, f.context, '', 100) 166 ).toBeUndefined(); 167 const guest = createIdentitySession(); 168 sessions.push(guest); 169 expect(captureEnquiryRumor(guest, f.context, '', 100)).toBeUndefined(); 170 expect( 171 captureEnquiryRumor({} as IdentitySession, f.context, '', 100) 172 ).toBeUndefined(); 173 const owner = await identity(); 174 expect( 175 captureEnquiryRumor(owner.session, {} as EnquiryContext, '', 100) 176 ).toBeUndefined(); 177 expect(captureEnquiryRumor(owner.session, f.context, '', -0)).toBeUndefined(); 178 }); 179 it('reply derives opposite participant and direct rumor parent, never the public listing event', async () => { 180 const f = food(), 181 owner = await identity(), 182 parent = required(captureEnquiryRumor(owner.session, f.context, '', 100)); 183 const parentId = rumorPlanSnapshot(parent)!.id, 184 seller = await identity(f.event.pubkey); 185 const reply = required( 186 captureReplyRumor(seller.session, parent, 'Yes, tomorrow works.', 101) 187 ), 188 snapshot = rumorPlanSnapshot(reply)!; 189 const wire = JSON.parse(snapshot.wire) as { 190 pubkey: string; 191 tags: string[][]; 192 }; 193 expect(snapshot.owner).toBe(f.event.pubkey); 194 expect(snapshot.peer).toBe(buyer); 195 expect(wire.pubkey).toBe(f.event.pubkey); 196 expect(wire.tags).toEqual([ 197 ['p', buyer], 198 ['e', parentId] 199 ]); 200 expect(parentId).not.toBe(f.event.id); 201 expect(rumorEnvelopePlan(reply)!.map((row) => row.recipient)).toEqual([ 202 buyer, 203 f.event.pubkey 204 ]); 205 }); 206 it('same-owner followup keeps the opposite peer and rejects nonmember or injected parent IDs', async () => { 207 const f = food(), 208 owner = await identity(), 209 parent = required(captureEnquiryRumor(owner.session, f.context, '', 100)); 210 const followup = required( 211 captureReplyRumor(owner.session, parent, 'Another question', 101) 212 ); 213 expect(rumorPlanSnapshot(followup)!.peer).toBe(f.event.pubkey); 214 expect( 215 captureReplyRumor( 216 owner.session, 217 f.event.id as unknown as RumorPlan, 218 'Injected parent', 219 101 220 ) 221 ).toBeUndefined(); 222 expect( 223 captureReplyRumor( 224 owner.session, 225 rumorPlanSnapshot(parent) as unknown as RumorPlan, 226 'Detached parent', 227 101 228 ) 229 ).toBeUndefined(); 230 const other = await identity(outsider); 231 expect( 232 captureReplyRumor(other.session, parent, 'Not a room member', 101) 233 ).toBeUndefined(); 234 }); 235 it('detached plan data and forged token cannot change or acquire plaintext ownership', async () => { 236 const f = food(), 237 owner = await identity(), 238 plan = required(captureEnquiryRumor(owner.session, f.context, '', 100)); 239 const before = rumorPlanSnapshot(plan)!; 240 const copy = rumorPlanSnapshot(plan)! as { 241 owner: string; 242 peer: string; 243 wire: string; 244 }; 245 copy.owner = outsider; 246 copy.peer = buyer; 247 copy.wire = '{}'; 248 expect(rumorPlanSnapshot(plan)).toEqual(before); 249 expect(rumorPlanSnapshot({} as RumorPlan)).toBeUndefined(); 250 expect(rumorEnvelopePlan(copy as unknown as RumorPlan)).toBeUndefined(); 251 }); 252 it('explicit release and identity invalidation erase reachable plan plaintext and reject further replies', async () => { 253 const f = food(), 254 owner = await identity(), 255 first = required(captureEnquiryRumor(owner.session, f.context, '', 100)), 256 second = required( 257 captureEnquiryRumor(owner.session, f.context, 'Other', 101) 258 ); 259 stopRumorPlan(first); 260 stopRumorPlan(first); 261 expect(rumorPlanSnapshot(first)).toBeUndefined(); 262 expect(rumorEnvelopePlan(first)).toBeUndefined(); 263 disconnectIdentity(owner.session); 264 expect(rumorPlanSnapshot(second)).toBeUndefined(); 265 expect(rumorEnvelopePlan(second)).toBeUndefined(); 266 expect( 267 captureReplyRumor(owner.session, second, 'After disconnect', 102) 268 ).toBeUndefined(); 269 }); 270 it('memory-only first reservation timing advances once and freezes the original command/hash/wire', async () => { 271 const f = food(), 272 actor = await identity(), 273 plan = required( 274 captureEnquiryRumor(actor.session, f.context, 'Original body', 100) 275 ); 276 const before = rumorPlanSnapshot(plan)!, 277 counts = actor.counts(); 278 const command = '12345678-1234-4234-8234-123456789abc'; 279 const bound = bindFirstRumorReservation(plan, command, 105)!; 280 expect(bound.createdAt).toBe(105); 281 expect(bound.id).not.toBe(before.id); 282 const old = JSON.parse(before.wire) as Record<string, unknown>, 283 fresh = JSON.parse(bound.wire) as Record<string, unknown>; 284 expect(fresh).toEqual({ ...old, id: bound.id, created_at: 105 }); 285 expect(rumorReservationCommand(plan)).toBe(command); 286 expect(bindFirstRumorReservation(plan, command, 110)).toEqual(bound); 287 expect( 288 bindFirstRumorReservation(plan, '12345678-1234-4234-8234-123456789abd', 110) 289 ).toBeUndefined(); 290 expect(rumorPlanSnapshot(plan)).toEqual(bound); 291 expect(actor.counts()).toEqual(counts); 292 stopRumorPlan(plan); 293 expect(rumorReservationCommand(plan)).toBeUndefined(); 294 expect(bindFirstRumorReservation(plan, command, 111)).toBeUndefined(); 295 }); 296 it('invalid or backwards initial reservation observations cannot rewrite a plan', async () => { 297 const f = food(), 298 actor = await identity(), 299 plan = required(captureEnquiryRumor(actor.session, f.context, 'Body', 100)); 300 const before = rumorPlanSnapshot(plan)!; 301 for (const seconds of [ 302 99, 303 -1, 304 NaN, 305 Infinity, 306 1.5, 307 '101', 308 Number.MAX_SAFE_INTEGER + 1 309 ]) 310 expect( 311 bindFirstRumorReservation( 312 plan, 313 '12345678-1234-4234-8234-123456789abc', 314 seconds 315 ) 316 ).toBeUndefined(); 317 expect(rumorPlanSnapshot(plan)).toEqual(before); 318 expect(rumorReservationCommand(plan)).toBeUndefined(); 319 }); 320 it('reply body objects cannot execute conversion or become trusted plain text', async () => { 321 const f = food(), 322 owner = await identity(); 323 const parent = required( 324 captureEnquiryRumor(owner.session, f.context, '', 100) 325 ); 326 const toJSON = vi.fn(() => 'Object-supplied private body'); 327 expect( 328 captureReplyRumor(owner.session, parent, { toJSON }, 101) 329 ).toBeUndefined(); 330 expect(toJSON).not.toHaveBeenCalled(); 331 });