diff --git a/build.js b/build.js index 54e9b06..540739a 100644 --- a/build.js +++ b/build.js @@ -9,7 +9,8 @@ const read = (p) => readFileSync(join(root, 'src', p), 'utf8'); // Function replacers avoid '$' pattern interpretation in replacement text. const out = read('index.html') .replace('/*__CSS__*/', () => read('style.css')) - .replace('/*__JS__*/', () => read('app.js')) + // Plain-script bundle: drop ES `export` so modules concatenate into one scope. + .replace('/*__JS__*/', () => [read('crypto.js').replace(/^export /gm, ''), read('app.js')].join('\n')) .replace('/*__PAYLOAD__*/', () => ''); mkdirSync(join(root, 'dist'), { recursive: true }); diff --git a/src/crypto.js b/src/crypto.js new file mode 100644 index 0000000..e52786c --- /dev/null +++ b/src/crypto.js @@ -0,0 +1,94 @@ +// Passphrase encryption: PBKDF2-SHA256 -> AES-256-GCM, WebCrypto only. +// Runs unchanged in browsers and Node 20+. build.js strips the `export` +// keywords when inlining this into the single-file bundle. +// +// Blob layout (base64 of): "FW" 0x01 | iterations u32be | salt 16 | iv 12 | ciphertext+tag +// The 7-byte header + salt + iv are bound in as GCM additional data, so any +// tampering with them fails authentication just like tampering with the ciphertext. + +const MAGIC = [0x46, 0x57, 0x01]; // "FW" version 1 +const SALT_LEN = 16; +const IV_LEN = 12; +const HEADER_LEN = MAGIC.length + 4; +const DEFAULT_ITERATIONS = 600000; // OWASP 2023 guidance for PBKDF2-SHA256 +const MAX_ITERATIONS = 10000000; // refuse absurd values from a hostile blob + +export class DecryptError extends Error { + constructor(message) { + super(message); + this.name = 'DecryptError'; + } +} + +function toBase64(bytes) { + let s = ''; + for (let i = 0; i < bytes.length; i += 0x8000) { + s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + } + return btoa(s); +} + +function fromBase64(str) { + try { + const s = atob(str.trim()); + const out = new Uint8Array(s.length); + for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i); + return out; + } catch { + throw new DecryptError('Not a valid encrypted file.'); + } +} + +async function deriveKey(passphrase, salt, iterations) { + const base = await crypto.subtle.importKey( + 'raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, ['deriveKey']); + return crypto.subtle.deriveKey( + { name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, + base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']); +} + +// Returns a base64 string. `iterations` is overridable for fast tests only. +export async function encrypt(plaintext, passphrase, iterations = DEFAULT_ITERATIONS) { + if (!passphrase) throw new Error('A passphrase is required.'); + const salt = crypto.getRandomValues(new Uint8Array(SALT_LEN)); + const iv = crypto.getRandomValues(new Uint8Array(IV_LEN)); + const head = new Uint8Array(HEADER_LEN + SALT_LEN + IV_LEN); + head.set(MAGIC, 0); + new DataView(head.buffer).setUint32(MAGIC.length, iterations); + head.set(salt, HEADER_LEN); + head.set(iv, HEADER_LEN + SALT_LEN); + + const key = await deriveKey(passphrase, salt, iterations); + const ct = new Uint8Array(await crypto.subtle.encrypt( + { name: 'AES-GCM', iv, additionalData: head }, key, new TextEncoder().encode(plaintext))); + + const out = new Uint8Array(head.length + ct.length); + out.set(head, 0); + out.set(ct, head.length); + return toBase64(out); +} + +// Throws DecryptError for a wrong passphrase, corruption, or tampering +// (these are deliberately indistinguishable). +export async function decrypt(blob, passphrase) { + const bytes = fromBase64(blob); + const preamble = HEADER_LEN + SALT_LEN + IV_LEN; + if (bytes.length < preamble + 16 || MAGIC.some((b, i) => bytes[i] !== b)) { + throw new DecryptError('Not a valid encrypted file.'); + } + const iterations = new DataView(bytes.buffer, bytes.byteOffset).getUint32(MAGIC.length); + if (iterations < 1 || iterations > MAX_ITERATIONS) { + throw new DecryptError('Not a valid encrypted file.'); + } + const head = bytes.slice(0, preamble); + const salt = bytes.slice(HEADER_LEN, HEADER_LEN + SALT_LEN); + const iv = bytes.slice(HEADER_LEN + SALT_LEN, preamble); + try { + const key = await deriveKey(passphrase || '', salt, iterations); + const pt = await crypto.subtle.decrypt( + { name: 'AES-GCM', iv, additionalData: head }, key, bytes.slice(preamble)); + return new TextDecoder().decode(pt); + } catch { + throw new DecryptError('Wrong passphrase, or the file is damaged.'); + } +} diff --git a/test/crypto.test.js b/test/crypto.test.js new file mode 100644 index 0000000..b9060ad --- /dev/null +++ b/test/crypto.test.js @@ -0,0 +1,43 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { encrypt, decrypt, DecryptError } from '../src/crypto.js'; + +const FAST = 1000; // iterations; production default is 600000 +const text = JSON.stringify({ note: 'ünïcødé ✓ secret 7419', big: 'x'.repeat(200000) }); + +test('round trip', async () => { + const blob = await encrypt(text, 'correct horse', FAST); + assert.equal(await decrypt(blob, 'correct horse'), text); +}); + +test('same input encrypts differently each time (random salt/iv)', async () => { + assert.notEqual(await encrypt('a', 'p', FAST), await encrypt('a', 'p', FAST)); +}); + +test('wrong passphrase fails cleanly', async () => { + const blob = await encrypt(text, 'right', FAST); + await assert.rejects(decrypt(blob, 'wrong'), DecryptError); + await assert.rejects(decrypt(blob, ''), DecryptError); +}); + +test('tampering with any region is detected', async () => { + const blob = await encrypt('hello', 'p', FAST); + const bytes = Uint8Array.from(atob(blob), (c) => c.charCodeAt(0)); + // header iterations, salt, iv, ciphertext, final tag byte + for (const i of [4, 8, 20, 35, bytes.length - 1]) { + const t = bytes.slice(); + t[i] ^= 1; + await assert.rejects(decrypt(btoa(String.fromCharCode(...t)), 'p'), DecryptError, 'byte ' + i); + } +}); + +test('garbage and truncated input rejected', async () => { + await assert.rejects(decrypt('not base64!!', 'p'), DecryptError); + await assert.rejects(decrypt('', 'p'), DecryptError); + const blob = await encrypt('hello', 'p', FAST); + await assert.rejects(decrypt(blob.slice(0, 20), 'p'), DecryptError); +}); + +test('empty passphrase refused on encrypt', async () => { + await assert.rejects(encrypt('x', ''), /passphrase/); +});