import { describe, expect, it, vi } from 'vitest' import type { AeadKey, E2EEnvelope, ReplayKeyParams } from 'relay-contracts' import { createReplaySealer, type ReplayCrypto } from '../src/e2e/replaySeal.js' /** Fake AEAD: key = tagged secret‖sessionId; ciphertext = plaintext XOR keyByte (marker hidden). */ function fakeCrypto(): ReplayCrypto & { derivations: ReplayKeyParams[] } { const derivations: ReplayKeyParams[] = [] return { derivations, deriveContentKey(params: ReplayKeyParams): AeadKey { derivations.push(params) const tag = new TextEncoder().encode(`${Buffer.from(params.hostContentSecret).toString('hex')}:${params.sessionId}`) return tag as unknown as AeadKey }, sealReplayFrame(key: AeadKey, seq: bigint, plaintext: Uint8Array): E2EEnvelope { const kb = (key as unknown as Uint8Array)[0] ?? 0x5a const ciphertext = plaintext.map((b) => b ^ kb) return { seq, nonce: new Uint8Array([Number(seq & 0xffn)]), ciphertext, tag: new Uint8Array([0xaa]) } }, } } const SECRET = new Uint8Array([1, 2, 3, 4]) describe('createReplaySealer (T19, FIX 3)', () => { it('derives K_content deterministically from (secret, sessionId, alg)', () => { const c1 = fakeCrypto() createReplaySealer(SECRET, 'sess-1', 'aes-256-gcm', c1) const c2 = fakeCrypto() createReplaySealer(SECRET, 'sess-1', 'aes-256-gcm', c2) expect(c1.derivations[0]).toEqual(c2.derivations[0]) }) it('a different sessionId → a different key (per-session separation)', () => { const c = fakeCrypto() createReplaySealer(SECRET, 'sess-1', 'aes-256-gcm', c) createReplaySealer(SECRET, 'sess-2', 'aes-256-gcm', c) expect(c.derivations[0]!.sessionId).not.toBe(c.derivations[1]!.sessionId) }) it('emits a monotonic seq (INV13) and never leaks the plaintext marker (INV2)', () => { const sealer = createReplaySealer(SECRET, 'sess-1', 'aes-256-gcm', fakeCrypto()) const marker = new TextEncoder().encode('SECRET-MARKER') const e0 = sealer.seal(marker) const e1 = sealer.seal(marker) expect(e0.seq).toBe(0n) expect(e1.seq).toBe(1n) expect(Buffer.from(e0.ciphertext).includes(Buffer.from(marker))).toBe(false) }) it('replay seal is DISTINCT from a live h2c seal for the same plaintext (FIX 3)', () => { const replay = createReplaySealer(SECRET, 'sess-1', 'aes-256-gcm', fakeCrypto()) // model a live seal with a different key byte const liveKey = new Uint8Array([0x11]) as unknown as AeadKey const live = fakeCrypto().sealReplayFrame(liveKey, 0n, new Uint8Array([0x41, 0x42])) const rep = replay.seal(new Uint8Array([0x41, 0x42])) expect(Buffer.from(rep.ciphertext).equals(Buffer.from(live.ciphertext))).toBe(false) }) it('the hostContentSecret is never mutated', () => { const secret = new Uint8Array([9, 9, 9]) const spy = vi.fn() createReplaySealer(secret, 's', 'aes-256-gcm', { deriveContentKey: (p) => { spy(p.hostContentSecret) return new Uint8Array([1]) as unknown as AeadKey }, sealReplayFrame: (_k, seq, pt) => ({ seq, nonce: new Uint8Array(), ciphertext: pt, tag: new Uint8Array() }), }) expect([...secret]).toEqual([9, 9, 9]) }) })