import test from 'node:test'; import assert from 'node:assert/strict'; import { createIdentity, hello, signIdentity, verifyIdentity, parseHello, type IdentityContext } from '../src/lib/identity.ts'; const fingerprint = (byte: string) => Array(32).fill(byte).join(' '); async function setup() { const first = await createIdentity(), second = await createIdentity(); const context: IdentityContext = { offer: hello(first), answer: hello(second), offerFingerprint: fingerprint('AA'), answerFingerprint: fingerprint('BB') }; return { first, second, context }; } test('device proof binds both keys, fresh nonces, roles, and both DTLS fingerprints', async () => { const { first, second, context } = await setup(); const proof = await signIdentity(first, context, true); await verifyIdentity(proof, context, true); await verifyIdentity(await signIdentity(second, context, false), context, false); await assert.rejects(verifyIdentity(proof, context, false)); for (const changed of [ { ...context, offer: hello(first) }, { ...context, answer: hello(second) }, { ...context, offer: hello(second) }, { ...context, answer: hello(first) }, { ...context, offerFingerprint: fingerprint('CC') }, { ...context, answerFingerprint: fingerprint('CC') }, ]) await assert.rejects(verifyIdentity(proof, changed, true)); const imposter = await createIdentity(); await assert.rejects(signIdentity(imposter, context, true)); await assert.rejects(verifyIdentity('00'.repeat(64), context, true)); }); test('identity input is bounded', async () => { const identity = await createIdentity(); assert.throws(() => parseHello({ key: identity.publicKey, nonce: 'bad' })); assert.throws(() => parseHello({ key: 'ff'.repeat(65), nonce: '00'.repeat(32) })); }); test('device private keys cannot be extracted and still sign after storage cloning', async () => { const { first, context } = await setup(); const stored = structuredClone(first); assert.equal(stored.privateKey.extractable, false); await assert.rejects(crypto.subtle.exportKey('jwk', stored.privateKey)); await verifyIdentity(await signIdentity(stored, context, true), context, true); });