giftwrap-builder.test.ts (9903B)
1 import { afterEach, expect, it, vi } from 'vitest'; 2 import { nip44 } from 'applesauce-core/helpers/encryption'; 3 import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts'; 4 import type { PrivateRecipientSeal } from '../../src/lib/nostr/seal-builder.ts'; 5 const state = vi.hoisted(() => ({ 6 seals: new WeakMap<object, Record<string, unknown>>(), 7 keys: [] as Uint8Array[], 8 fixtureKeys: [] as Uint8Array[], 9 conversations: [] as Uint8Array[], 10 fail: false, 11 response: 'normal' 12 })); 13 vi.mock('../../src/lib/nostr/seal-builder.ts', () => ({ 14 privateSealSnapshot: (token: object) => state.seals.get(token), 15 inboxProbeSealSnapshot: () => undefined 16 })); 17 vi.mock('applesauce-core/helpers', async (original) => { 18 const sdk = await original<typeof import('applesauce-core/helpers')>(); 19 return { 20 ...sdk, 21 generateSecretKey: () => { 22 const key = sdk.generateSecretKey(); 23 state.keys.push(key); 24 return key; 25 }, 26 finalizeEvent: (...args: Parameters<typeof sdk.finalizeEvent>) => { 27 if (state.fail) throw Error('secret exception must not escape'); 28 const signed = sdk.finalizeEvent(...args); 29 if (state.response === 'extra') 30 return { 31 ...signed, 32 plaintext: 'private helper sentinel', 33 toJSON: () => { 34 throw Error('unexpected object conversion'); 35 } 36 }; 37 if (state.response === 'wrong_target') 38 return sdk.finalizeEvent( 39 { ...args[0], tags: [['p', signed.pubkey]] }, 40 args[1] 41 ); 42 if (state.response === 'cached_bad_id') 43 return { ...signed, id: '0'.repeat(64), [sdk.verifiedSymbol]: true }; 44 return signed; 45 } 46 }; 47 }); 48 vi.mock('applesauce-core/helpers/encryption', async (original) => { 49 const sdk = 50 await original<typeof import('applesauce-core/helpers/encryption')>(); 51 return { 52 ...sdk, 53 nip44: { 54 ...sdk.nip44, 55 v2: { 56 ...sdk.nip44.v2, 57 utils: { 58 ...sdk.nip44.v2.utils, 59 getConversationKey: ( 60 ...args: Parameters<typeof sdk.nip44.v2.utils.getConversationKey> 61 ) => { 62 const key = sdk.nip44.v2.utils.getConversationKey(...args); 63 state.conversations.push(key); 64 return key; 65 } 66 } 67 } 68 } 69 }; 70 }); 71 import { generateSecretKey, getPublicKey } from 'applesauce-core/helpers'; 72 import { 73 buildPrivateGiftwrap, 74 privateGiftwrapSnapshot, 75 type PrivateGiftwrap 76 } from '../../src/lib/nostr/giftwrap-builder.ts'; 77 // Unit-only input port substitution checks crypto cleanup; real genuine token 78 // admission and nested decryption are separately exercised in Chromium. 79 function fixture(role: 'peer' | 'self' = 'peer') { 80 const key = generateSecretKey(), 81 owner = getPublicKey(key), 82 peerKey = generateSecretKey(), 83 peer = getPublicKey(peerKey); 84 state.fixtureKeys.push(key, peerKey); 85 const seal = Object.freeze({}) as PrivateRecipientSeal; 86 const record = { 87 owner, 88 peer, 89 destination: role === 'self' ? owner : peer, 90 role, 91 command: 'local intent', 92 rumorHash: 'a'.repeat(64), 93 wire: '{"encryptedSeal":"unit input port only"}' 94 }; 95 state.seals.set(seal, record); 96 state.keys.length = 0; 97 return { seal, record, key }; 98 } 99 afterEach(() => { 100 for (const key of [ 101 ...state.keys, 102 ...state.fixtureKeys, 103 ...state.conversations 104 ]) 105 key.fill(0); 106 state.fixtureKeys.length = 0; 107 state.conversations.length = 0; 108 state.keys.length = 0; 109 state.fail = false; 110 state.response = 'normal'; 111 vi.unstubAllGlobals(); 112 }); 113 it('requires genuine seal ownership and literal review before generating a key', () => { 114 vi.stubGlobal('window', {}); 115 expect( 116 buildPrivateGiftwrap({} as PrivateRecipientSeal, 'reviewed_private_wrap') 117 ).toBeUndefined(); 118 const f = fixture(); 119 expect(buildPrivateGiftwrap(f.seal, 'connect')).toBeUndefined(); 120 expect(state.keys).toHaveLength(0); 121 f.key.fill(0); 122 expect(privateGiftwrapSnapshot({} as PrivateGiftwrap)).toBeUndefined(); 123 }); 124 it('does not construct browser wrappers during SSR', () => { 125 const f = fixture(); 126 expect(buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap')).toBeUndefined(); 127 expect(state.keys).toHaveLength(0); 128 f.key.fill(0); 129 }); 130 it('uses a fresh disposable author and exact one-target1059 with only signed fields', () => { 131 vi.stubGlobal('window', {}); 132 const f = fixture('self'), 133 token = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); 134 expect(token).toBeDefined(); 135 const saved = privateGiftwrapSnapshot(token!), 136 event = JSON.parse(saved!.wire) as { 137 kind: number; 138 tags: string[][]; 139 pubkey: string; 140 created_at: number; 141 content: string; 142 }; 143 expect(event.kind).toBe(1059); 144 expect(event.tags).toEqual([['p', f.record.owner]]); 145 expect(event.pubkey).not.toBe(f.record.owner); 146 expect(event.pubkey).not.toBe(f.record.peer); 147 expect(Object.keys(event).sort()).toEqual([ 148 'content', 149 'created_at', 150 'id', 151 'kind', 152 'pubkey', 153 'sig', 154 'tags' 155 ]); 156 expect(verifyEnvelope(saved!.wire).ok).toBe(true); 157 expect(event.created_at).toBeLessThanOrEqual(Math.floor(Date.now() / 1000)); 158 expect(event.created_at).toBeGreaterThanOrEqual( 159 Math.floor(Date.now() / 1000) - 3600 160 ); 161 expect(saved!.wire).not.toContain('encryptedSeal'); 162 expect(state.keys).toHaveLength(1); 163 expect(state.keys[0].every((x) => x === 0)).toBe(true); 164 expect(state.conversations).toHaveLength(1); 165 expect(state.conversations[0].every((x) => x === 0)).toBe(true); 166 f.key.fill(0); 167 }); 168 it('clears the directly owned ephemeral key even when the SDK signer throws', () => { 169 vi.stubGlobal('window', {}); 170 const f = fixture(); 171 state.fail = true; 172 expect(buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap')).toBeUndefined(); 173 expect(state.keys).toHaveLength(1); 174 expect(state.keys[0].every((x) => x === 0)).toBe(true); 175 expect(state.conversations).toHaveLength(1); 176 expect(state.conversations[0].every((x) => x === 0)).toBe(true); 177 f.key.fill(0); 178 }); 179 it('does not return a wrapper after original ownership changes inside SDK key generation', () => { 180 vi.stubGlobal('window', {}); 181 const f = fixture(); 182 const random = crypto.getRandomValues.bind(crypto); 183 let calls = 0; 184 const spy = vi.spyOn(crypto, 'getRandomValues').mockImplementation((( 185 v: Uint8Array<ArrayBuffer> 186 ) => { 187 calls++; 188 if (calls === 2) state.seals.delete(f.seal); 189 return random(v); 190 }) as typeof crypto.getRandomValues); 191 try { 192 expect( 193 buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap') 194 ).toBeUndefined(); 195 expect(state.keys.every((k) => k.every((x) => x === 0))).toBe(true); 196 } finally { 197 spy.mockRestore(); 198 f.key.fill(0); 199 } 200 }); 201 it('detached wrapper metadata and casts cannot mint tokens; invalidation removes snapshot access', () => { 202 vi.stubGlobal('window', {}); 203 const f = fixture(), 204 token = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); 205 expect(token).toBeDefined(); 206 const saved = privateGiftwrapSnapshot(token!); 207 expect( 208 privateGiftwrapSnapshot(saved as unknown as PrivateGiftwrap) 209 ).toBeUndefined(); 210 state.seals.delete(f.seal); 211 expect(privateGiftwrapSnapshot(token!)).toBeUndefined(); 212 f.key.fill(0); 213 }); 214 it('fresh peer wrappers have distinct authors and ciphertext without exposing key material', () => { 215 vi.stubGlobal('window', {}); 216 const f = fixture(), 217 first = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'), 218 second = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); 219 const a = JSON.parse(privateGiftwrapSnapshot(first!)!.wire) as { 220 pubkey: string; 221 content: string; 222 }, 223 b = JSON.parse(privateGiftwrapSnapshot(second!)!.wire) as { 224 pubkey: string; 225 content: string; 226 }; 227 expect(a.pubkey).not.toBe(b.pubkey); 228 expect(a.content).not.toBe(b.content); 229 expect(state.keys).toHaveLength(2); 230 expect(state.keys.every((k) => k.every((x) => x === 0))).toBe(true); 231 // Both peer payloads use actual stock SDK NIP44; inner proof belongs077. 232 expect(typeof nip44.v2.decrypt).toBe('function'); 233 f.key.fill(0); 234 }); 235 236 it('discards SDK extra plaintext and hostile conversion rather than spreading the returned object', () => { 237 vi.stubGlobal('window', {}); 238 const f = fixture(); 239 state.response = 'extra'; 240 const token = buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap'); 241 expect(token).toBeDefined(); 242 const wire = privateGiftwrapSnapshot(token!)!.wire; 243 expect(wire).not.toContain('sentinel'); 244 expect(Object.keys(JSON.parse(wire) as Record<string, unknown>)).toHaveLength( 245 7 246 ); 247 f.key.fill(0); 248 }); 249 for (const response of ['wrong_target', 'cached_bad_id'] as const) 250 it(`rejects actual SDK ${response} response despite valid signature or cached verification`, () => { 251 vi.stubGlobal('window', {}); 252 const f = fixture(); 253 state.response = response; 254 expect( 255 buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap') 256 ).toBeUndefined(); 257 expect(state.keys).toHaveLength(1); 258 expect(state.keys[0].every((x) => x === 0)).toBe(true); 259 expect(state.conversations[0].every((x) => x === 0)).toBe(true); 260 f.key.fill(0); 261 }); 262 for (const fault of ['mismatch', 'exception'] as const) 263 it(`outer roundtrip ${fault} clears directly owned buffers and grants no wrapper`, () => { 264 vi.stubGlobal('window', {}); 265 const f = fixture(); 266 const spy = vi.spyOn(nip44.v2, 'decrypt').mockImplementation(() => { 267 if (fault === 'exception') throw Error('SDK roundtrip fault'); 268 return 'substitute signed seal'; 269 }); 270 try { 271 expect( 272 buildPrivateGiftwrap(f.seal, 'reviewed_private_wrap') 273 ).toBeUndefined(); 274 expect(state.keys).toHaveLength(1); 275 expect(state.keys[0].every((x) => x === 0)).toBe(true); 276 expect(state.conversations[0].every((x) => x === 0)).toBe(true); 277 } finally { 278 spy.mockRestore(); 279 f.key.fill(0); 280 } 281 });