diff --git a/packages/app/src/lib/unlock-crypto.ts b/packages/app/src/lib/unlock-crypto.ts new file mode 100644 index 00000000..17921973 --- /dev/null +++ b/packages/app/src/lib/unlock-crypto.ts @@ -0,0 +1,108 @@ +const KEY_BYTES = 32; +const NONCE_BYTES = 12; +const VERSION = 1 as const; +const KEY_PREFIX = "fzk1."; +const SALT = new TextEncoder().encode("factorize.unlock-key.v1"); +const INFO = new TextEncoder().encode("factorize.record.aes-256-gcm.v1"); + +export type RecordBinding = { + ownerId: string; + recordId: string; + recordType: string; + destination: string; + revision: number; +}; + +export type EncryptedEnvelopeV1 = { + version: 1; + algorithm: "A256GCM"; + nonce: string; + ciphertext: string; +}; + +const encoder = new TextEncoder(); + +function toArrayBuffer(bytes: Uint8Array): ArrayBuffer { + const copy = new Uint8Array(bytes.byteLength); + copy.set(bytes); + return copy.buffer; +} + +function encodeBase64Url(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, ""); +} + +function decodeBase64Url(value: unknown, label: string): Uint8Array { + if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value)) throw new TypeError(`Malformed ${label}`); + try { + const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - value.length % 4) % 4)); + const result = Uint8Array.from(binary, character => character.charCodeAt(0)); + if (encodeBase64Url(result) !== value) throw new TypeError(`Malformed ${label}`); + return result; + } catch { + throw new TypeError(`Malformed ${label}`); + } +} + +function validateBinding(binding: RecordBinding): Uint8Array { + if (!binding || typeof binding !== "object" || + [binding.ownerId, binding.recordId, binding.recordType, binding.destination].some(value => typeof value !== "string" || value.length === 0) || + !Number.isSafeInteger(binding.revision) || binding.revision < 0) { + throw new TypeError("Malformed record binding"); + } + // Fixed-position JSON prevents property order or extra fields changing the AAD representation. + return encoder.encode(JSON.stringify(["factorize-record-v1", binding.ownerId, binding.recordId, binding.recordType, binding.destination, binding.revision])); +} + +function decodeKey(key: string): Uint8Array { + if (typeof key !== "string" || !key.startsWith(KEY_PREFIX)) throw new TypeError("Malformed unlock key"); + const bytes = decodeBase64Url(key.slice(KEY_PREFIX.length), "unlock key"); + if (bytes.byteLength !== KEY_BYTES) throw new TypeError("Malformed unlock key"); + return bytes; +} + +async function deriveAesKey(key: string, usages: KeyUsage[]): Promise { + const bytes = decodeKey(key); + try { + const material = await crypto.subtle.importKey("raw", toArrayBuffer(bytes), "HKDF", false, ["deriveKey"]); + return await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: SALT, info: INFO }, material, + { name: "AES-GCM", length: 256 }, false, usages); + } finally { + bytes.fill(0); + } +} + +/** Generate a 256-bit user-held key encoded as `fzk1.` plus unpadded base64url. */ +export function generateUnlockKey(): string { + const bytes = crypto.getRandomValues(new Uint8Array(KEY_BYTES)); + return KEY_PREFIX + encodeBase64Url(bytes); +} + +/** Encrypt UTF-8 bytes with AES-256-GCM and bind all record identity fields as AAD. */ +export async function encryptRecord(plaintext: Uint8Array, key: string, binding: RecordBinding): Promise { + if (!(plaintext instanceof Uint8Array)) throw new TypeError("Plaintext must be bytes"); + const aad = validateBinding(binding); + const nonce = crypto.getRandomValues(new Uint8Array(NONCE_BYTES)); + const aesKey = await deriveAesKey(key, ["encrypt"]); + const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv: toArrayBuffer(nonce), additionalData: toArrayBuffer(aad), tagLength: 128 }, aesKey, toArrayBuffer(plaintext)); + return { version: VERSION, algorithm: "A256GCM", nonce: encodeBase64Url(nonce), ciphertext: encodeBase64Url(new Uint8Array(ciphertext)) }; +} + +/** Decrypt a supported envelope; malformed metadata, bindings and authentication fail closed. */ +export async function decryptRecord(envelope: unknown, key: string, binding: RecordBinding): Promise { + if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) throw new TypeError("Malformed encrypted envelope"); + const value = envelope as Record; + if (value.version !== VERSION) throw new TypeError("Unsupported encrypted envelope version"); + if (value.algorithm !== "A256GCM" || Object.keys(value).sort().join(",") !== "algorithm,ciphertext,nonce,version") { + throw new TypeError("Malformed encrypted envelope"); + } + const nonce = decodeBase64Url(value.nonce, "envelope nonce"); + const ciphertext = decodeBase64Url(value.ciphertext, "envelope ciphertext"); + if (nonce.byteLength !== NONCE_BYTES || ciphertext.byteLength < 16) throw new TypeError("Malformed encrypted envelope"); + const aad = validateBinding(binding); + const aesKey = await deriveAesKey(key, ["decrypt"]); + const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer(nonce), additionalData: toArrayBuffer(aad), tagLength: 128 }, aesKey, toArrayBuffer(ciphertext)); + return new Uint8Array(plaintext); +} diff --git a/packages/app/test/functional/unlock-crypto.spec.mjs b/packages/app/test/functional/unlock-crypto.spec.mjs new file mode 100644 index 00000000..dc99b318 --- /dev/null +++ b/packages/app/test/functional/unlock-crypto.spec.mjs @@ -0,0 +1,49 @@ +import { test, expect } from "@playwright/test"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import ts from "typescript"; + +let server; +let origin; +const sourceUrl = new URL("../../src/lib/unlock-crypto.ts", import.meta.url); + +test.beforeAll(async () => { + const source = await readFile(sourceUrl, "utf8"); + const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText; + server = createServer(async (req, res) => { + if (new URL(req.url, "http://fixture").pathname === "/unlock-crypto.js") { + res.setHeader("Content-Type", "text/javascript; charset=utf-8"); + res.end(javascript); + return; + } + try { + res.setHeader("Content-Type", "text/html; charset=utf-8"); + res.end(await readFile(new URL("../../dist/index.html", import.meta.url))); + } catch { res.statusCode = 404; res.end(); } + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + origin = `http://127.0.0.1:${server.address().port}`; +}); + +test.afterAll(async () => { + if (server) await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); +}); + +test("versioned unlock-key vector and encryption round-trip work in Chromium", async ({ page }) => { + await page.goto(origin); + const result = await page.evaluate(async () => { + const { decryptRecord, encryptRecord, generateUnlockKey } = await import("/unlock-crypto.js"); + const key = "fzk1.AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"; + const binding = { ownerId: "owner-vector", recordId: "record-vector", recordType: "integration", destination: "https://api.example.test", revision: 7 }; + const vector = { version: 1, algorithm: "A256GCM", nonce: "oKGio6Slpqeoqaqr", ciphertext: "zD4d7Hr-kv60Kj8vOX_XeLVnruqK8LoNWu2elYJASCVrEhv7qecotw" }; + const decoded = new TextDecoder().decode(await decryptRecord(vector, key, binding)); + const generated = generateUnlockKey(); + const envelope = await encryptRecord(new TextEncoder().encode("browser round trip"), generated, binding); + const roundTrip = new TextDecoder().decode(await decryptRecord(envelope, generated, binding)); + return { decoded, roundTrip, nonceLength: atob(envelope.nonce.replaceAll("-", "+").replaceAll("_", "/")).length }; + }); + expect(result).toEqual({ decoded: "synthetic vector payload", roundTrip: "browser round trip", nonceLength: 12 }); +}); diff --git a/packages/app/test/unlock-crypto.test.mjs b/packages/app/test/unlock-crypto.test.mjs new file mode 100644 index 00000000..bed77ff1 --- /dev/null +++ b/packages/app/test/unlock-crypto.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { decryptRecord, encryptRecord, generateUnlockKey } from "../src/lib/unlock-crypto.ts"; + +const key = "fzk1.AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"; +const binding = { ownerId: "owner-vector", recordId: "record-vector", recordType: "integration", destination: "https://api.example.test", revision: 7 }; +const vector = { version: 1, algorithm: "A256GCM", nonce: "oKGio6Slpqeoqaqr", ciphertext: "zD4d7Hr-kv60Kj8vOX_XeLVnruqK8LoNWu2elYJASCVrEhv7qecotw" }; +const encoder = new TextEncoder(); +const text = bytes => new TextDecoder().decode(bytes); + +test("fixed version 1 envelope decrypts in Node and generated keys round-trip", async () => { + assert.equal(text(await decryptRecord(vector, key, binding)), "synthetic vector payload"); + const generated = generateUnlockKey(); + assert.match(generated, /^fzk1\.[A-Za-z0-9_-]{43}$/u); + const envelope = await encryptRecord(encoder.encode("round trip"), generated, binding); + assert.equal(text(await decryptRecord(envelope, generated, binding)), "round trip"); +}); + +test("fresh nonces make repeated encryptions differ", async () => { + const [first, second] = await Promise.all([ + encryptRecord(encoder.encode("same"), key, binding), + encryptRecord(encoder.encode("same"), key, binding), + ]); + assert.notEqual(first.nonce, second.nonce); + assert.notEqual(first.ciphertext, second.ciphertext); +}); + +test("wrong key and every authenticated binding change fail closed", async () => { + await assert.rejects(decryptRecord(vector, "fzk1.AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", binding)); + for (const field of Object.keys(binding)) { + const changed = { ...binding, [field]: field === "revision" ? binding.revision + 1 : `${binding[field]}-changed` }; + await assert.rejects(decryptRecord(vector, key, changed), { name: "OperationError" }); + } +}); + +test("malformed keys and envelopes and unsupported versions are rejected", async () => { + for (const malformedKey of ["", "fzk1.AA", "fzk1.A".repeat(43), `fzk1.${"A".repeat(42)}!`]) { + await assert.rejects(encryptRecord(encoder.encode("x"), malformedKey, binding)); + } + for (const malformed of [null, [], { ...vector, nonce: "***" }, { ...vector, nonce: "AA" }, { ...vector, ciphertext: "AA" }, { ...vector, extra: true }]) { + await assert.rejects(decryptRecord(malformed, key, binding)); + } + await assert.rejects(decryptRecord({ ...vector, version: 2 }, key, binding), /Unsupported/u); +});