import { describe, expect, it } from 'vitest'; import { ed25519 } from '@noble/curves/ed25519'; import { bytesToHex } from '@noble/hashes/utils'; import { base64UrlEncode, verifyLicense } from '../src/license'; // Test-only signing key generated from fixed bytes (never used for real licenses). const signingKey = new Uint8Array(32).fill(42); const publicKeyHex = bytesToHex(ed25519.getPublicKey(signingKey)); function issue(payload: object): string { const body = new TextEncoder().encode(JSON.stringify(payload)); const sig = ed25519.sign(body, signingKey); return `${base64UrlEncode(body)}.${base64UrlEncode(sig)}`; } describe('verifyLicense', () => { const good = issue({ licensee: 'Acme Store', issued_at: '2026-07-08', expires_updates_at: '2027-07-08' }); it('accepts a correctly signed license', () => { const result = verifyLicense(good, publicKeyHex); expect(result.valid).toBe(true); if (result.valid) expect(result.payload.licensee).toBe('Acme Store'); }); it('rejects tampered payloads', () => { const [payload, sig] = good.split('.'); const forged = `${base64UrlEncode(new TextEncoder().encode('{"licensee":"Mallory","issued_at":"2026-01-01","expires_updates_at":"2099-01-01"}'))}.${sig}`; expect(verifyLicense(forged, publicKeyHex).valid).toBe(false); expect(verifyLicense(`${payload}.${payload}`, publicKeyHex).valid).toBe(false); }); it('rejects licenses signed by a different key', () => { const otherKey = new Uint8Array(32).fill(7); const body = new TextEncoder().encode(JSON.stringify({ licensee: 'X', issued_at: 'y', expires_updates_at: 'z' })); const sig = ed25519.sign(body, otherKey); expect(verifyLicense(`${base64UrlEncode(body)}.${base64UrlEncode(sig)}`, publicKeyHex).valid).toBe(false); }); it('handles garbage and missing keys gracefully', () => { expect(verifyLicense('not-a-license', publicKeyHex).valid).toBe(false); expect(verifyLicense('a.b.c', publicKeyHex).valid).toBe(false); expect(verifyLicense(good, '').valid).toBe(false); }); it('rejects incomplete payloads even when correctly signed', () => { const incomplete = issue({ licensee: 'Acme Store' }); const result = verifyLicense(incomplete, publicKeyHex); expect(result.valid).toBe(false); }); });