// All message encryption happens in the browser. The AES-GCM key is carried in // the secret link's #fragment and never sent to the server. The server only // ever stores/relays the opaque blobs produced here. export function b64urlToBytes(s) { s = s.replace(/-/g, "+").replace(/_/g, "/"); while (s.length % 4) s += "="; const bin = atob(s); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } export function bytesToB64url(bytes) { let bin = ""; for (const b of bytes) bin += String.fromCharCode(b); return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } export async function generateKey() { const key = await crypto.subtle.generateKey( { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); const raw = new Uint8Array(await crypto.subtle.exportKey("raw", key)); return { key, b64: bytesToB64url(raw) }; } export async function importKey(b64) { return crypto.subtle.importKey( "raw", b64urlToBytes(b64), "AES-GCM", true, ["encrypt", "decrypt"] ); } // encrypt returns base64url( iv(12) || ciphertext ). export async function encrypt(key, obj) { const iv = crypto.getRandomValues(new Uint8Array(12)); const pt = new TextEncoder().encode(JSON.stringify(obj)); const ct = new Uint8Array( await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, pt) ); const combined = new Uint8Array(iv.length + ct.length); combined.set(iv, 0); combined.set(ct, iv.length); return bytesToB64url(combined); } export async function decrypt(key, blob) { const data = b64urlToBytes(blob); const iv = data.slice(0, 12); const ct = data.slice(12); const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct); return JSON.parse(new TextDecoder().decode(pt)); } // Binary variants for file/image uploads. Returns/accepts raw iv(12)||ciphertext // bytes (Uint8Array) so attachments upload as octet-stream, not base64. export async function encryptBytes(key, bytes) { const iv = crypto.getRandomValues(new Uint8Array(12)); const ct = new Uint8Array( await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, bytes) ); const out = new Uint8Array(iv.length + ct.length); out.set(iv, 0); out.set(ct, iv.length); return out; } export async function decryptBytes(key, bytes) { const iv = bytes.slice(0, 12); const ct = bytes.slice(12); const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct); return new Uint8Array(pt); } // ---- invite key-wrapping (see docs/invite-redesign.md) ------------------ // The invite secret T (base64url) derives a server lookup id + an AES wrapping // key via HKDF. The server only ever stores the id and the wrapped key — never // T — so it can't recover the group key. // A fresh 128-bit invite secret. export function randomSecret() { return bytesToB64url(crypto.getRandomValues(new Uint8Array(16))); } async function hkdf(tB64, info) { return crypto.subtle.importKey("raw", b64urlToBytes(tB64), "HKDF", false, ["deriveBits", "deriveKey"]).then((ikm) => ({ ikm, params: { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: new TextEncoder().encode(info) }, })); } // sha256hex is the lowercase hex SHA-256 of a string's UTF-8 bytes — it matches // the server's hashToken, so a claimHash computed here verifies against the // claimSecret presented at claim time. async function sha256hex(str) { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); } // deriveInvite returns { id, wrapKey, claimSecret, claimHash, bindKey } from the // secret T, each domain-separated. claimSecret proves knowledge of T when // claiming; claimHash is what the inviter hands the server to store. bindKey is // the key-transparency binding key (#573): the joiner MACs its published public // key under it so a T-holder (the inviter) can verify the roster key wasn't // substituted (bindMac / verifyBindMac). The server keeps only id + claimHash, // so reading the DB isn't enough to claim OR to forge a bind-MAC — both need T. export async function deriveInvite(tB64) { const idd = await hkdf(tB64, "lchat-invite-id"); const idBits = await crypto.subtle.deriveBits(idd.params, idd.ikm, 256); const wkd = await hkdf(tB64, "lchat-invite-wrap"); const wrapKey = await crypto.subtle.deriveKey( wkd.params, wkd.ikm, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); const cld = await hkdf(tB64, "lchat-invite-claim"); const claimBits = await crypto.subtle.deriveBits(cld.params, cld.ikm, 256); const claimSecret = bytesToB64url(new Uint8Array(claimBits)); const claimHash = await sha256hex(claimSecret); const bkd = await hkdf(tB64, "lchat-invite-bind"); const bindBits = await crypto.subtle.deriveBits(bkd.params, bkd.ikm, 256); const bindKey = bytesToB64url(new Uint8Array(bindBits)); return { id: bytesToB64url(new Uint8Array(idBits)), wrapKey, claimSecret, claimHash, bindKey }; } // bindMac / verifyBindMac — the key-transparency binding (#573, // docs/tamper-evidence.md). The joiner signs its published public key string // with HMAC-SHA256 under bindKey (derived from the invite secret T); the server // stores the MAC beside the key and serves it in the roster. A client that // holds T for that invite (the inviter) recomputes and verifies before it // trusts/wraps to the member — catching a server that substituted its own key. // MAC over the DECODED public-key bytes, not its base64url string: the wrap path // only ever uses the raw key bytes, so a server that re-encodes the roster string // (padding, +/- vs -/_ — all tolerated by b64urlToBytes) changes the string but // not the key. MAC'ing the string would let that re-encoding break an honest // member's verification (a false-alarm / cry-wolf primitive); MAC'ing the bytes // makes the binding canonical. export async function bindMac(bindKeyB64, pubB64) { const key = await crypto.subtle.importKey("raw", b64urlToBytes(bindKeyB64), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const sig = await crypto.subtle.sign("HMAC", key, b64urlToBytes(pubB64)); return bytesToB64url(new Uint8Array(sig)); } export async function verifyBindMac(bindKeyB64, pubB64, macB64) { if (!bindKeyB64 || !pubB64 || !macB64) return false; try { const key = await crypto.subtle.importKey("raw", b64urlToBytes(bindKeyB64), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); return await crypto.subtle.verify("HMAC", key, b64urlToBytes(macB64), b64urlToBytes(pubB64)); } catch { return false; // malformed MAC/key never throws — a bad MAC is a "false", surfaced by the caller } } // wrap/unwrap the group key (base64url) under a derived wrapping CryptoKey. export async function wrapGroupKey(groupKeyB64, wrapKey) { return bytesToB64url(await encryptBytes(wrapKey, b64urlToBytes(groupKeyB64))); } export async function unwrapGroupKey(wrappedB64, wrapKey) { return bytesToB64url(await decryptBytes(wrapKey, b64urlToBytes(wrappedB64))); } // ---- user keypairs + thread-key wrapping (see docs/threads-and-dms.md) -- // Each person has an ECDH P-256 keypair; the public key lives in the roster. A // thread's AES key is wrapped to each member's user public key (ECIES: ephemeral // ECDH -> HKDF -> AES-GCM), so the server stores only blobs it can't open. The // private key exports as pkcs8 so it can ride an add-device link to a new device. const EC = { name: "ECDH", namedCurve: "P-256" }; // generateUserKeypair returns { publicKey, privateKey } as base64url // (raw point / pkcs8). The public key goes in the roster; the private key stays // in the session (and is shipped, wrapped, when adding a device). export async function generateUserKeypair() { const kp = await crypto.subtle.generateKey(EC, true, ["deriveBits"]); const pub = new Uint8Array(await crypto.subtle.exportKey("raw", kp.publicKey)); const priv = new Uint8Array(await crypto.subtle.exportKey("pkcs8", kp.privateKey)); return { publicKey: bytesToB64url(pub), privateKey: bytesToB64url(priv) }; } // Derive the AES-GCM wrapping key shared by one ECDH private + one public key. async function eciesKey(privKey, pubKey) { const bits = await crypto.subtle.deriveBits({ name: "ECDH", public: pubKey }, privKey, 256); const ikm = await crypto.subtle.importKey("raw", bits, "HKDF", false, ["deriveKey"]); return crypto.subtle.deriveKey( { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: new TextEncoder().encode("lchat-thread-wrap") }, ikm, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"] ); } // wrapThreadKey wraps a thread's AES key (base64url raw) to a recipient's user // public key. Returns base64url( ephPub(65) || iv(12) || ciphertext ). export async function wrapThreadKey(threadKeyB64, recipientPubB64) { const recipient = await crypto.subtle.importKey("raw", b64urlToBytes(recipientPubB64), EC, false, []); const eph = await crypto.subtle.generateKey(EC, true, ["deriveBits"]); const aes = await eciesKey(eph.privateKey, recipient); const body = await encryptBytes(aes, b64urlToBytes(threadKeyB64)); // iv||ct const ephPub = new Uint8Array(await crypto.subtle.exportKey("raw", eph.publicKey)); const out = new Uint8Array(ephPub.length + body.length); out.set(ephPub, 0); out.set(body, ephPub.length); return bytesToB64url(out); } // unwrapThreadKey recovers the thread key (base64url raw) using your user // private key (base64url pkcs8). export async function unwrapThreadKey(wrappedB64, privKeyB64) { const buf = b64urlToBytes(wrappedB64); const ephPub = await crypto.subtle.importKey("raw", buf.slice(0, 65), EC, false, []); const priv = await crypto.subtle.importKey("pkcs8", b64urlToBytes(privKeyB64), EC, false, ["deriveBits"]); const aes = await eciesKey(priv, ephPub); return bytesToB64url(await decryptBytes(aes, buf.slice(65))); } // ---- capability grants (see docs/connected-services.md) ----------------- // sealForPub / openSealed are wrapThreadKey's sibling for arbitrary JSON: the // same ECIES-to-a-public-key wire shape (ephPub(65) || iv(12) || ciphertext), // but the sealed payload is a small object rather than a bare key. Binding // metadata *inside* the seal (e.g. an `exp` expiry) means the relaying server // can't extend or alter it — it only ever holds the opaque blob. Used to hand a // bot a time-boxed capability (a third-party token, or a data key) that only // that bot's private key can open. // sealForPub seals `obj` (JSON-serialisable) to a recipient's user public key. export async function sealForPub(recipientPubB64, obj) { const recipient = await crypto.subtle.importKey("raw", b64urlToBytes(recipientPubB64), EC, false, []); const eph = await crypto.subtle.generateKey(EC, true, ["deriveBits"]); const aes = await eciesKey(eph.privateKey, recipient); const body = await encryptBytes(aes, new TextEncoder().encode(JSON.stringify(obj))); // iv||ct const ephPub = new Uint8Array(await crypto.subtle.exportKey("raw", eph.publicKey)); const out = new Uint8Array(ephPub.length + body.length); out.set(ephPub, 0); out.set(body, ephPub.length); return bytesToB64url(out); } // openSealed opens a sealForPub blob with your user private key (base64url // pkcs8), returning the object. Throws if it wasn't sealed to your key. export async function openSealed(sealedB64, privKeyB64) { const buf = b64urlToBytes(sealedB64); const ephPub = await crypto.subtle.importKey("raw", buf.slice(0, 65), EC, false, []); const priv = await crypto.subtle.importKey("pkcs8", b64urlToBytes(privKeyB64), EC, false, ["deriveBits"]); const aes = await eciesKey(priv, ephPub); const pt = await decryptBytes(aes, buf.slice(65)); return JSON.parse(new TextDecoder().decode(pt)); } // ---- OAuth PKCE (see docs/connected-services.md) ------------------------ // pkcePair mints a one-time PKCE verifier + its S256 challenge for an OAuth // authorization-code flow with a *public* client (no client secret). The // verifier stays in the browser and is presented only at the token exchange; // the challenge rides in the authorize URL. This is what lets a connected // service be authorized with no pasted key and no stored secret. export async function pkcePair() { const verifier = bytesToB64url(crypto.getRandomValues(new Uint8Array(32))); // 43-char base64url const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))); return { verifier, challenge: bytesToB64url(digest) }; } // ---- the branding key (docs/no-plaintext.md) ------------------------------ // // A per-instance key B, one trust rung below the instance key: it rides share // links' #fragments (never sent to the server) and unlocks the sealed branding // blob — the space's name, description, photo, and admin identity. B is short // by design (bulk-exposure protection, not targeted secrecy — the doc has the // honest math), so derivation is deliberately stretched with PBKDF2, the one // stretching KDF native to both WebCrypto and CommonCrypto (no-build-step rule // rules out WASM Argon2). Clients cache the derived key per session. export const BRANDING_KEY_CHARS = 10; // lowercase base32 → 50 bits export const BRANDING_KDF_ITERATIONS = 600_000; // mintBrandingKey() -> e.g. "k3m7p2qx4f". Uniform over the base32 alphabet // via rejection sampling (no modulo bias). export function mintBrandingKey() { const alphabet = "abcdefghijklmnopqrstuvwxyz234567"; let out = ""; while (out.length < BRANDING_KEY_CHARS) { const [byte] = crypto.getRandomValues(new Uint8Array(1)); if (byte < 224) out += alphabet[byte % 32]; // 224 = 7×32: reject the biased tail } return out; } // deriveBrandingKey(b, saltB64) -> AES-GCM CryptoKey usable with the // encrypt/decrypt/encryptBytes/decryptBytes helpers above. export async function deriveBrandingKey(b, saltB64) { const ikm = await crypto.subtle.importKey("raw", new TextEncoder().encode(b), "PBKDF2", false, [ "deriveKey", ]); return crypto.subtle.deriveKey( { name: "PBKDF2", hash: "SHA-256", salt: b64urlToBytes(saltB64), iterations: BRANDING_KDF_ITERATIONS }, ikm, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"], ); }