diff --git a/apps/pwa/src/lib/vault-recovery.mjs b/apps/pwa/src/lib/vault-recovery.mjs new file mode 100644 index 00000000..e1368061 --- /dev/null +++ b/apps/pwa/src/lib/vault-recovery.mjs @@ -0,0 +1,455 @@ +// Vault email recovery (opt-in, $5 lifetime per user) for the personal vault. +// +// The CLI (packages/opencreds/src/email-recovery.ts) encrypts the vault's user +// key K under a random key E and splits E = S XOR U. This module keeps: +// +// escrow_blob / escrow_iv AES-GCM(K) under E: useless without E +// server_share_ct / _iv S, AES-GCM under VAULT_ESCROW_KEY (versioned) +// +// and never U. U arrives once, at enrollment, is rendered as a recovery code +// into an email to the account, and is dropped. A stolen database plus this +// server's env yields K only with the enrollment email as well. A live server +// compromise during enrollment or recovery, or the mailbox plus a live server, +// can: docs/opencreds/security.md says so plainly. +// +// Recovering releases S only against a fresh 8-digit code mailed at that time +// (15 minutes, 5 tries, single use, 3 per hour), and every claim is audited and +// announced by email. +import crypto from "node:crypto"; +import { readWebhook } from "@profullstack/coinpay-onboard"; +import { get, all, run, batch } from "../db.mjs"; +import { config } from "../config.mjs"; +import { id } from "./crypto.mjs"; +import { coinpayClient, PROPERTY } from "./auto-rotation.mjs"; + +export const PURPOSE = "vault_recovery"; +export const CODE_TTL_MS = 15 * 60 * 1000; +export const CODE_MAX_ATTEMPTS = 5; +export const STARTS_PER_HOUR = 3; +export const HOUR_MS = 60 * 60 * 1000; +export const SHARE_BYTES = 32; +export const IV_BYTES = 12; +/** AES-GCM of a 32-byte key: 32 bytes of ciphertext + a 16-byte tag. */ +export const ESCROW_BLOB_BYTES = 48; + +/** $5 unless VAULT_RECOVERY_PRICE_USD says otherwise. Read per call, so it follows the env. */ +export const priceUsd = (env = process.env) => { + const n = Number(env.VAULT_RECOVERY_PRICE_USD || 5); + return Number.isFinite(n) && n > 0 ? n : 5; +}; + +// ---------------------------------------------------------------- keys ---- + +/** + * The server escrow keyring. VAULT_ESCROW_KEY is the current key (32 bytes, + * base64) at version VAULT_ESCROW_KEY_VERSION (default 1). To rotate: move the + * old key to VAULT_ESCROW_KEY_V, set the new key and bump the + * version; old rows keep decrypting, new enrollments use the new key. + */ +export function escrowKeyring(env = process.env) { + const version = Number.parseInt(env.VAULT_ESCROW_KEY_VERSION || "1", 10) || 1; + const keys = new Map(); + const parse = (value, name) => { + const key = Buffer.from(String(value).trim(), "base64"); + if (key.length !== 32) throw new Error(`${name} must be 32 random bytes, base64-encoded (got ${key.length} bytes)`); + return key; + }; + for (const [name, value] of Object.entries(env)) { + const m = /^VAULT_ESCROW_KEY_V(\d+)$/.exec(name); + if (m && value) keys.set(Number(m[1]), parse(value, name)); + } + if (env.VAULT_ESCROW_KEY) keys.set(version, parse(env.VAULT_ESCROW_KEY, "VAULT_ESCROW_KEY")); + return { version, current: keys.get(version) || null, get: (v) => keys.get(Number(v)) || null }; +} + +export const recoveryConfigured = (env = process.env) => { + try { + return Boolean(escrowKeyring(env).current); + } catch { + return false; + } +}; + +const shareAad = (userId) => Buffer.from(`logicsrc:vault-escrow:server-share:v1:${userId}`); + +/** Encrypt S under the current escrow key, bound to the user. */ +export function sealServerShare(share, userId, ring = escrowKeyring()) { + if (!ring.current) throw new Error("VAULT_ESCROW_KEY is not configured"); + const iv = crypto.randomBytes(IV_BYTES); + const cipher = crypto.createCipheriv("aes-256-gcm", ring.current, iv); + cipher.setAAD(shareAad(userId)); + const ct = Buffer.concat([cipher.update(share), cipher.final(), cipher.getAuthTag()]); + return { ct: ct.toString("base64"), iv: iv.toString("base64"), version: ring.version }; +} + +export function openServerShare(row, ring = escrowKeyring()) { + const key = ring.get(row.key_version); + if (!key) throw new Error(`No escrow key for version ${row.key_version} (set VAULT_ESCROW_KEY_V${row.key_version})`); + const data = Buffer.from(row.server_share_ct, "base64"); + const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(row.server_share_iv, "base64")); + decipher.setAAD(shareAad(row.user_id)); + decipher.setAuthTag(data.subarray(data.length - 16)); + return Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]); +} + +// -------------------------------------------------------- recovery code --- +// Mirrors formatRecoveryCode in packages/opencreds/src/email-recovery.ts (a +// test pins that the two agree): 55 Crockford base32 characters of U (256 bits +// plus 19 zero bits) and a 5-character check group, in twelve groups of five. + +const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +export const RECOVERY_CODE_CHECK_PREFIX = "opencreds:email-recovery-code:v1"; + +function encodeBits(bytes, chars) { + let out = ""; + for (let i = 0; i < chars; i++) { + let v = 0; + for (let b = 0; b < 5; b++) { + const bit = i * 5 + b; + const byte = bit >> 3; + v = (v << 1) | (byte < bytes.length ? (bytes[byte] >> (7 - (bit & 7))) & 1 : 0); + } + out += ALPHABET[v]; + } + return out; +} + +export function renderRecoveryCode(userShare) { + if (userShare.length !== SHARE_BYTES) throw new Error("The user share must be 32 bytes"); + const check = crypto.createHash("sha256").update(RECOVERY_CODE_CHECK_PREFIX).update(userShare).digest(); + const text = encodeBits(userShare, 55) + encodeBits(check, 5); + return text.match(/.{1,5}/g).join("-"); +} + +// ---------------------------------------------------------------- misc ---- + +/** a***@example.com: enough to recognise, not enough to harvest. */ +export function maskEmail(email) { + const [local, domain] = String(email || "").split("@"); + if (!local || !domain) return null; + return `${local[0]}***@${domain}`; +} + +const affected = (r) => Number(r?.rowsAffected ?? r?.changes ?? r?.rowCount ?? 0); + +/** Plain-text mail through Resend; false when it is not configured or did not send. */ +export async function sendMail(to, subject, text) { + if (!config.resend.apiKey || !to) return false; + const response = await fetch("https://api.resend.com/emails", { + method: "POST", + headers: { authorization: `Bearer ${config.resend.apiKey}`, "content-type": "application/json" }, + body: JSON.stringify({ from: config.resend.from, to, subject, text }), + }).catch(() => null); + return Boolean(response && response.ok); +} + +export async function audit(userId, action, { ip = null, userAgent = null, detail = null } = {}, now = Date.now()) { + await run( + `INSERT INTO vault_recovery_audit (id, user_id, action, detail, ip, user_agent, created_at) VALUES (?,?,?,?,?,?,?)`, + [id(), userId, action, detail, ip, userAgent, now], + ); +} + +// ------------------------------------------------------------- payments --- + +export async function isEntitled(userId) { + return Boolean(await get(`SELECT 1 AS ok FROM vault_recovery_payments WHERE user_id = ? AND status = 'settled' LIMIT 1`, [userId])); +} + +/** Open a CoinPay checkout for email recovery and record it as pending. */ +export async function createRecoveryCheckout({ user, client, origin = config.origin, now = Date.now() }) { + if (!user?.id || !user?.email) throw new Error("A signed-in user with an email is required"); + const paymentRef = id(); + const back = `${origin}/settings`; + const session = await (client || coinpayClient()).createCheckoutSession({ + amount: priceUsd(), + currency: "USD", + description: "LogicSRC vault email recovery (lifetime)", + customerEmail: user.email, + accountId: user.id, + property: PROPERTY, + metadata: { purpose: PURPOSE, user_id: user.id, payment_ref: paymentRef }, + successUrl: `${back}?vault_recovery=paid&session_id={CHECKOUT_SESSION_ID}#vault-recovery`, + cancelUrl: `${back}?vault_recovery=cancelled#vault-recovery`, + expiresInMinutes: 60, + }); + await run( + `INSERT INTO vault_recovery_payments (checkout_session_id, payment_ref, user_id, status, created_at) VALUES (?,?,?,?,?) ON CONFLICT (checkout_session_id) DO NOTHING`, + [session.id, paymentRef, user.id, "pending", now], + ); + return session; +} + +/** + * Mark a checkout paid. Idempotent on the checkout session (or payment) id: the + * first settle wins, a replayed webhook or the return check changes nothing. + */ +export async function settleVaultRecovery({ checkoutSessionId, paymentId, userId, amountUsd = null, method = null }, now = Date.now()) { + const key = checkoutSessionId || paymentId; + if (!key) return { handled: false, reason: "no checkout session or payment id" }; + const existing = await get(`SELECT * FROM vault_recovery_payments WHERE checkout_session_id = ?`, [key]); + if (existing) { + const r = await run( + `UPDATE vault_recovery_payments SET status = 'settled', settled_at = ?, payment_id = COALESCE(payment_id, ?), amount_usd = ?, method = ? WHERE checkout_session_id = ? AND status <> 'settled'`, + [now, paymentId || null, amountUsd, method, key], + ); + if (!affected(r)) return { handled: true, purpose: PURPOSE, duplicate: true, userId: existing.user_id }; + // The row we wrote at checkout names the buyer; metadata is only a fallback. + await audit(existing.user_id, "purchase", { detail: key }, now).catch(() => {}); + return { handled: true, purpose: PURPOSE, action: "settled", userId: existing.user_id }; + } + if (!userId) return { handled: false, reason: "no user_id" }; + if (!(await get(`SELECT id FROM users WHERE id = ?`, [userId]))) return { handled: false, reason: "unknown user" }; + const r = await run( + `INSERT INTO vault_recovery_payments (checkout_session_id, payment_id, user_id, amount_usd, method, status, created_at, settled_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT (checkout_session_id) DO NOTHING`, + [key, paymentId || null, userId, amountUsd, method, "settled", now, now], + ); + if (!affected(r)) return { handled: true, purpose: PURPOSE, duplicate: true, userId }; + await audit(userId, "purchase", { detail: key }, now).catch(() => {}); + return { handled: true, purpose: PURPOSE, action: "settled", userId }; +} + +/** Is this (verified) webhook for email recovery? The dispatcher routes on it. */ +export function isVaultRecoveryEvent(payload) { + try { + return readWebhook(payload).metadata?.purpose === PURPOSE; + } catch { + return false; + } +} + +/** Settle from a verified webhook payload. */ +export async function settleVaultRecoveryWebhook(payload, now = Date.now()) { + const event = readWebhook(payload); + if (!event.paid) return { handled: false, purpose: PURPOSE, type: event.type, status: event.status }; + if (event.property && event.property !== PROPERTY) return { handled: false, purpose: PURPOSE, reason: "other property" }; + const meta = event.metadata || {}; + return settleVaultRecovery({ + checkoutSessionId: event.checkoutSessionId, + paymentId: event.paymentId, + userId: meta.user_id || event.accountId, + amountUsd: event.amountUsd, + method: event.method, + }, now); +} + +/** The Settings page's return check: settle now if CoinPay already says paid. */ +export async function reconcileRecoveryReturn(sessionId, user, client, now = Date.now()) { + if (!sessionId || !/^cs_[A-Za-z0-9_-]+$/.test(sessionId)) return null; + const session = await (client || coinpayClient()).checkoutSession(sessionId); + const meta = session.metadata || {}; + if (meta.purpose !== PURPOSE || meta.user_id !== user.id) return null; + if (session.status === "paid") { + await settleVaultRecovery({ + checkoutSessionId: session.id, + paymentId: session.paymentId || null, + userId: user.id, + amountUsd: session.amount, + method: session.paidMethod || null, + }, now); + } + return session.status; +} + +// ----------------------------------------------------------- enrollment --- + +export const activeEnrollment = (userId) => + get(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active' ORDER BY enrolled_at DESC LIMIT 1`, [userId]); + +export async function recoveryStatus(user) { + const [row, purchased] = await Promise.all([activeEnrollment(user.id), isEntitled(user.id)]); + return { + enrolled: Boolean(row), + enrolledAt: row ? new Date(Number(row.enrolled_at)).toISOString() : null, + email: maskEmail(user.email), + purchased, + priceUsd: priceUsd(), + configured: recoveryConfigured(), + }; +} + +const b64 = (value, bytes) => { + if (typeof value !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null; + const buf = Buffer.from(value, "base64"); + return buf.length === bytes ? buf : null; +}; + +/** Validate an enroll body; returns the parsed shares or an error string. */ +export function parseEnrollment(body) { + const blob = b64(body?.escrowBlob, ESCROW_BLOB_BYTES); + const iv = b64(body?.escrowIv, IV_BYTES); + const serverShare = b64(body?.serverShare, SHARE_BYTES); + const userShare = b64(body?.userShare, SHARE_BYTES); + const createdAt = typeof body?.vaultCreatedAt === "string" && body.vaultCreatedAt.length > 0 && body.vaultCreatedAt.length <= 64 ? body.vaultCreatedAt : null; + if (!blob || !iv || !serverShare || !userShare || !createdAt) { + return { error: "Expected { escrowBlob, escrowIv, serverShare, userShare, vaultCreatedAt } (base64; 48, 12, 32 and 32 bytes)." }; + } + return { escrowBlob: body.escrowBlob, escrowIv: body.escrowIv, serverShare, userShare, vaultCreatedAt: createdAt }; +} + +export function enrollmentEmail(code) { + return { + subject: "Your LogicSRC vault email-recovery code — keep this email", + text: + "You turned on email recovery for your LogicSRC personal vault.\n\n" + + "Your recovery code:\n\n" + + ` ${code}\n\n` + + "Keep this email. If you ever lose your master password, run\n\n" + + " logicsrc vault recover --email\n\n" + + "and type this code when it asks. We will also email you a one-time code at that moment.\n\n" + + "LogicSRC does not store this code. It is one half of the key to your vault: the other half is on our " + + "server, and neither half opens anything alone. Someone who has this email AND can sign in to your " + + "LogicSRC account could recover your vault, so keep this mailbox secure.\n\n" + + "Turning email recovery off, or enabling it again, makes this code stop working.\n\n" + + "If you did not turn this on, sign in, disable it (Settings, or `logicsrc vault recovery disable`) and change your password.", + }; +} + +/** + * Enroll: store the blob and the sealed S as pending, mail U, then activate + * (replacing any prior enrollment). If the mail does not go out, the pending + * row is deleted and the prior enrollment, if any, is untouched. + */ +export async function enroll(user, parsed, ctx = {}, now = Date.now()) { + const sealed = sealServerShare(parsed.serverShare, user.id); + parsed.serverShare.fill(0); + const rowId = id(); + await run( + `INSERT INTO vault_recovery_enrollments (id, user_id, status, escrow_blob, escrow_iv, server_share_ct, server_share_iv, key_version, vault_created_at, enrolled_at) VALUES (?,?,?,?,?,?,?,?,?,?)`, + [rowId, user.id, "pending", parsed.escrowBlob, parsed.escrowIv, sealed.ct, sealed.iv, sealed.version, parsed.vaultCreatedAt, now], + ); + let sent = false; + try { + const mail = enrollmentEmail(renderRecoveryCode(parsed.userShare)); + sent = await sendMail(user.email, mail.subject, mail.text); + } finally { + parsed.userShare.fill(0); + } + if (!sent) { + await run(`DELETE FROM vault_recovery_enrollments WHERE id = ?`, [rowId]); + await audit(user.id, "enroll_failed", { ...ctx, detail: "email not sent" }, now).catch(() => {}); + return { ok: false }; + } + await batch([ + { + sql: `UPDATE vault_recovery_enrollments SET status = 'revoked', revoked_at = ?, escrow_blob = NULL, escrow_iv = NULL, server_share_ct = NULL, server_share_iv = NULL WHERE user_id = ? AND status = 'active'`, + args: [now, user.id], + }, + { sql: `UPDATE vault_recovery_enrollments SET status = 'active' WHERE id = ?`, args: [rowId] }, + { sql: `UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, args: [now, user.id] }, + ]); + await audit(user.id, "enroll", ctx, now); + return { ok: true }; +} + +/** Turn it off: the escrow material is deleted, live codes die. */ +export async function disable(userId, ctx = {}, now = Date.now()) { + const r = await run( + `UPDATE vault_recovery_enrollments SET status = 'revoked', revoked_at = ?, escrow_blob = NULL, escrow_iv = NULL, server_share_ct = NULL, server_share_iv = NULL WHERE user_id = ? AND status IN ('active', 'pending')`, + [now, userId], + ); + await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, [now, userId]); + const disabled = affected(r) > 0; + if (disabled) await audit(userId, "disable", ctx, now); + return { disabled }; +} + +// ------------------------------------------------------------- recovery --- + +/** HMAC under the escrow key, so a database dump alone cannot brute-force a live 8-digit code. */ +function codeHash(userId, codeId, code, ring = escrowKeyring()) { + return crypto.createHmac("sha256", ring.current).update(`vault-recovery-otp:v1:${userId}:${codeId}:${code}`).digest("hex"); +} + +export class RecoveryError extends Error { + constructor(status, code, message, extra = {}) { + super(message); + this.status = status; + this.code = code; + this.extra = extra; + } +} + +/** Mail a fresh one-time code. */ +export async function startRecovery(user, ctx = {}, now = Date.now()) { + if (!(await activeEnrollment(user.id))) { + throw new RecoveryError(404, "not_enrolled", "Email recovery is not enabled for this account."); + } + if (!user.email) throw new RecoveryError(422, "no_email", "This account has no email address."); + const recent = await all(`SELECT created_at FROM vault_recovery_codes WHERE user_id = ? AND created_at > ? ORDER BY created_at`, [user.id, now - HOUR_MS]); + if (recent.length >= STARTS_PER_HOUR) { + const retryAfter = Math.max(1, Math.ceil((Number(recent[0].created_at) + HOUR_MS - now) / 1000)); + throw new RecoveryError(429, "rate_limited", `Too many recovery attempts. Try again in ${Math.ceil(retryAfter / 60)} minute(s).`, { retryAfter }); + } + await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, [now, user.id]); + const codeId = id(); + const code = String(crypto.randomInt(0, 100_000_000)).padStart(8, "0"); + await run( + `INSERT INTO vault_recovery_codes (id, user_id, code_hash, attempts, created_at, expires_at) VALUES (?,?,?,?,?,?)`, + [codeId, user.id, codeHash(user.id, codeId, code), 0, now, now + CODE_TTL_MS], + ); + const sent = await sendMail( + user.email, + "Your LogicSRC vault recovery code", + `Someone (hopefully you) is recovering your LogicSRC personal vault through email recovery.\n\n` + + `One-time code: ${code}\n\nIt expires in 15 minutes and works once.\n\n` + + `If this was not you, someone can sign in to your LogicSRC account: change your password now, and turn email recovery off (Settings, or \`logicsrc vault recovery disable\`). ` + + `They also need the recovery code from your enrollment email, so if anyone else can read this mailbox, secure your email account first.`, + ); + if (!sent) { + await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ?`, [now, codeId]); + throw new RecoveryError(502, "email_failed", "Could not send the one-time code email. Try again in a minute."); + } + await audit(user.id, "start", ctx, now); + return { sent: true, email: maskEmail(user.email) }; +} + +/** Spend a one-time code; on success release the escrow material with S decrypted. */ +export async function claimRecovery(user, code, ctx = {}, now = Date.now()) { + const entered = String(code ?? "").replace(/\s+/g, ""); + const row = await get(`SELECT * FROM vault_recovery_codes WHERE user_id = ? AND used_at IS NULL ORDER BY created_at DESC LIMIT 1`, [user.id]); + if (!row || Number(row.expires_at) <= now) { + if (row) await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ?`, [now, row.id]); + throw new RecoveryError(410, "code_expired", "No live one-time code. Start the recovery again to get a new one."); + } + if (Number(row.attempts) >= CODE_MAX_ATTEMPTS) { + await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ?`, [now, row.id]); + throw new RecoveryError(429, "too_many_attempts", "Too many wrong codes. Start the recovery again."); + } + const expected = Buffer.from(row.code_hash, "hex"); + const got = Buffer.from(codeHash(user.id, row.id, entered), "hex"); + if (!/^\d{8}$/.test(entered) || !crypto.timingSafeEqual(expected, got)) { + const attempts = Number(row.attempts) + 1; + await run( + `UPDATE vault_recovery_codes SET attempts = ?, used_at = ? WHERE id = ?`, + [attempts, attempts >= CODE_MAX_ATTEMPTS ? now : null, row.id], + ); + await audit(user.id, "claim_failed", { ...ctx, detail: `attempt ${attempts}` }, now).catch(() => {}); + const attemptsLeft = Math.max(0, CODE_MAX_ATTEMPTS - attempts); + throw new RecoveryError(401, "wrong_code", attemptsLeft ? `Wrong one-time code (${attemptsLeft} tries left).` : "Wrong one-time code. Start the recovery again.", { attemptsLeft }); + } + // Single use, even under a race: only the update that flips used_at wins. + const spent = await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE id = ? AND used_at IS NULL`, [now, row.id]); + if (!affected(spent)) throw new RecoveryError(410, "code_expired", "That one-time code was already used. Start the recovery again."); + + const enrollment = await activeEnrollment(user.id); + if (!enrollment) throw new RecoveryError(404, "not_enrolled", "Email recovery is not enabled for this account."); + const share = openServerShare(enrollment); + const material = { + escrowBlob: enrollment.escrow_blob, + escrowIv: enrollment.escrow_iv, + serverShare: share.toString("base64"), + vaultCreatedAt: enrollment.vault_created_at, + }; + share.fill(0); + await audit(user.id, "claim", ctx, now); + await sendMail( + user.email, + "Your LogicSRC vault email recovery was used", + `Email recovery for your LogicSRC personal vault was just used (${new Date(now).toISOString()}` + + `${ctx.ip ? `, from ${ctx.ip}` : ""}${ctx.userAgent ? `, ${ctx.userAgent}` : ""}).\n\n` + + `If that was you, there is nothing to do: the CLI sets a new master password and emails you a new recovery code.\n\n` + + `If it was not you, change your LogicSRC password now and turn email recovery off (Settings, or \`logicsrc vault recovery disable\`).`, + ).catch(() => false); + return material; +} diff --git a/apps/pwa/src/migrations-pg/014_vault_email_recovery.sql b/apps/pwa/src/migrations-pg/014_vault_email_recovery.sql new file mode 100644 index 00000000..dbdde585 --- /dev/null +++ b/apps/pwa/src/migrations-pg/014_vault_email_recovery.sql @@ -0,0 +1,50 @@ +-- Postgres copy of migrations/014_vault_email_recovery.sql (INTEGER -> bigint, REAL -> double precision). +-- Vault email recovery (opt-in, $5 lifetime): escrowed blob + server share S (encrypted +-- under VAULT_ESCROW_KEY); the user share U is emailed once and never stored (no column for it). +-- No inline comments: the pg shim joins lines. Additive only. +CREATE TABLE IF NOT EXISTS vault_recovery_enrollments ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + escrow_blob TEXT, + escrow_iv TEXT, + server_share_ct TEXT, + server_share_iv TEXT, + key_version bigint NOT NULL, + vault_created_at TEXT NOT NULL, + enrolled_at bigint NOT NULL, + revoked_at bigint +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_enrollments_user ON vault_recovery_enrollments(user_id, status); +CREATE TABLE IF NOT EXISTS vault_recovery_codes ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + code_hash TEXT NOT NULL, + attempts bigint NOT NULL DEFAULT 0, + created_at bigint NOT NULL, + expires_at bigint NOT NULL, + used_at bigint +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_codes_user ON vault_recovery_codes(user_id, created_at); +CREATE TABLE IF NOT EXISTS vault_recovery_payments ( + checkout_session_id TEXT PRIMARY KEY, + payment_ref TEXT, + payment_id TEXT, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + amount_usd double precision, + method TEXT, + status TEXT NOT NULL, + created_at bigint NOT NULL, + settled_at bigint +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_payments_user ON vault_recovery_payments(user_id, status); +CREATE TABLE IF NOT EXISTS vault_recovery_audit ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + action TEXT NOT NULL, + detail TEXT, + ip TEXT, + user_agent TEXT, + created_at bigint NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_audit_user ON vault_recovery_audit(user_id, created_at); diff --git a/apps/pwa/src/migrations/014_vault_email_recovery.sql b/apps/pwa/src/migrations/014_vault_email_recovery.sql new file mode 100644 index 00000000..f3ad3d5d --- /dev/null +++ b/apps/pwa/src/migrations/014_vault_email_recovery.sql @@ -0,0 +1,65 @@ +-- Vault email recovery (opt-in, $5 lifetime per user). See docs/opencreds/security.md. +-- +-- The CLI encrypts the personal vault's user key under a random key E and splits +-- E into two XOR shares. The server keeps the escrowed blob and share S, with S +-- encrypted under VAULT_ESCROW_KEY (key_version says which one, for rotation). +-- The other share, U, is emailed to the account once and NEVER stored: there is +-- deliberately no column for it. Neither the blob, S, nor this database plus the +-- server env opens a vault without the enrollment email. +-- +-- status: pending (enrollment email not yet confirmed sent) -> active -> revoked. +-- A revoked row keeps its timestamps for the audit trail; its escrow material is +-- set to NULL (deleted). Additive only. +CREATE TABLE IF NOT EXISTS vault_recovery_enrollments ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + escrow_blob TEXT, + escrow_iv TEXT, + server_share_ct TEXT, + server_share_iv TEXT, + key_version INTEGER NOT NULL, + vault_created_at TEXT NOT NULL, + enrolled_at INTEGER NOT NULL, + revoked_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_enrollments_user ON vault_recovery_enrollments(user_id, status); + +-- One-time codes for a recovery: 8 digits, HMAC'd at rest, 15 minutes, 5 tries, single use. +CREATE TABLE IF NOT EXISTS vault_recovery_codes ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + code_hash TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + used_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_codes_user ON vault_recovery_codes(user_id, created_at); + +-- The purchase ledger: one row per CoinPay checkout session; settled once. +-- Entitlement = any settled row for the user. +CREATE TABLE IF NOT EXISTS vault_recovery_payments ( + checkout_session_id TEXT PRIMARY KEY, + payment_ref TEXT, + payment_id TEXT, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + amount_usd REAL, + method TEXT, + status TEXT NOT NULL, + created_at INTEGER NOT NULL, + settled_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_payments_user ON vault_recovery_payments(user_id, status); + +-- Append-only trail of every enroll, start, claim, failure and disable. +CREATE TABLE IF NOT EXISTS vault_recovery_audit ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + action TEXT NOT NULL, + detail TEXT, + ip TEXT, + user_agent TEXT, + created_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_audit_user ON vault_recovery_audit(user_id, created_at); diff --git a/apps/pwa/src/routes/auto-rotation.mjs b/apps/pwa/src/routes/auto-rotation.mjs index 24558d93..b6626ee8 100644 --- a/apps/pwa/src/routes/auto-rotation.mjs +++ b/apps/pwa/src/routes/auto-rotation.mjs @@ -12,6 +12,7 @@ import { get } from "../db.mjs"; import { requireAuth } from "../lib/session.mjs"; import { api, requireMember } from "./credshare.mjs"; import { autoRotationState, createCheckout, settleWebhook, verifySignature, AUTO_ROTATION_PRICE_USD, AUTO_ROTATION_DAYS } from "../lib/auto-rotation.mjs"; +import { isVaultRecoveryEvent, settleVaultRecoveryWebhook } from "../lib/vault-recovery.mjs"; export const autoRotationRouter = Router(); @@ -49,10 +50,16 @@ autoRotationRouter.post("/api/credshare/teams/:slug/rotation/auto/checkout", api res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: AUTO_ROTATION_PRICE_USD, days: AUTO_ROTATION_DAYS }); })); +// The one CoinPay webhook for this app: the signature is verified once, then the +// event goes to its product by metadata.purpose. "vault_recovery" (email +// recovery, lib/vault-recovery.mjs) settles there; everything else goes to the +// automatic-rotation settler exactly as before. autoRotationRouter.post("/api/coinpay/webhook", async (req, res) => { if (!verifySignature(req.rawBody, req.get("x-coinpay-signature"))) return res.status(401).json({ error: "Invalid signature" }); try { - const result = await settleWebhook(req.body); + const result = isVaultRecoveryEvent(req.body) + ? await settleVaultRecoveryWebhook(req.body) + : await settleWebhook(req.body); console.log("coinpay webhook", JSON.stringify(result)); res.json({ received: true, ...result }); } catch (e) { diff --git a/apps/pwa/src/routes/pages.mjs b/apps/pwa/src/routes/pages.mjs index 8c90625f..418a5250 100644 --- a/apps/pwa/src/routes/pages.mjs +++ b/apps/pwa/src/routes/pages.mjs @@ -13,6 +13,7 @@ import { CLI_HINT } from "../lib/cli-hint.mjs"; import { bulkUnlockCard, vaultPageBody } from "../lib/vault-page.mjs"; import { keyFingerprint } from "../lib/keyfp.mjs"; import { teamAudit } from "./credshare.mjs"; +import { vaultRecoveryCard } from "./vault-recovery.mjs"; import { config } from "../config.mjs"; import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile"; import { profiles } from "../lib/profile.mjs"; @@ -313,6 +314,7 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => { if (recoveryToken) clearCeremony(res, "recovery"); const err = req.query.err ? String(req.query.err).slice(0, 200) : ""; const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `
no keys yet
`; + const recoveryCardHtml = await vaultRecoveryCard(req); const body = `${appBar(req)}

Settings

@@ -364,6 +366,7 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => { + ${recoveryCardHtml}
Emergency recovery

Create a single-use recovery token for your password manager. The server stores only a hash; if you lose the plaintext, it cannot be recovered. Creating a new token revokes older ones.

diff --git a/apps/pwa/src/routes/vault-recovery.mjs b/apps/pwa/src/routes/vault-recovery.mjs new file mode 100644 index 00000000..97db9e87 --- /dev/null +++ b/apps/pwa/src/routes/vault-recovery.mjs @@ -0,0 +1,201 @@ +// Vault email recovery (opt-in, $5 lifetime): lib/vault-recovery.mjs holds the logic. +// +// GET /api/opencreds/recovery status: {enrolled, enrolledAt, email (masked), purchased, priceUsd} +// POST /api/opencreds/recovery/checkout a CoinPay checkout: {url, sessionId, priceUsd} +// POST /api/opencreds/recovery/enroll {escrowBlob, escrowIv, serverShare, userShare, vaultCreatedAt} +// POST /api/opencreds/recovery/start mail a one-time code +// POST /api/opencreds/recovery/claim {code} -> {escrowBlob, escrowIv, serverShare, vaultCreatedAt} +// DELETE /api/opencreds/recovery disable: delete the escrow material +// POST /settings/vault-recovery/checkout the Settings page's Buy button (303 to CoinPay) +// POST /settings/vault-recovery/disable the Settings page's switch-off +// +// Auth as /api/opencreds: a browser session or a person's `Bearer lsk_…`; a +// machine key never reaches the personal vault. The webhook that settles a +// purchase is the shared /api/coinpay/webhook (routes/auto-rotation.mjs), which +// dispatches purpose "vault_recovery" here. +import { Router } from "express"; +import { get } from "../db.mjs"; +import { config } from "../config.mjs"; +import { bearer, keyForBearer } from "../lib/apikey.mjs"; +import { esc } from "../lib/html.mjs"; +import { csrfInput, requireAuth } from "../lib/session.mjs"; +import { + RecoveryError, + claimRecovery, + createRecoveryCheckout, + disable, + enroll, + isEntitled, + maskEmail, + parseEnrollment, + priceUsd, + reconcileRecoveryReturn, + recoveryConfigured, + recoveryStatus, + startRecovery, +} from "../lib/vault-recovery.mjs"; + +export const vaultRecoveryRouter = Router(); + +const userRow = (userId) => get(`SELECT id, email FROM users WHERE id = ?`, [userId]); + +function context(req) { + return { + ip: (req.ip || "").replace(/^::ffff:/, "") || null, + userAgent: String(req.get("user-agent") || "").slice(0, 300) || null, + }; +} + +function api(handler) { + return async (req, res) => { + let userId = req.user?.id; + if (!userId) { + const found = await keyForBearer(bearer(req)); + if (!found) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" }); + if (found.key.kind === "machine") { + return res.status(403).json({ error: "A machine API key cannot reach the personal vault.", code: "machine_key_forbidden" }); + } + userId = found.user.id; + } + res.set("Cache-Control", "no-store"); + try { + const user = await userRow(userId); + if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" }); + await handler(req, res, user); + } catch (e) { + if (e instanceof RecoveryError) { + if (e.extra?.retryAfter) res.set("Retry-After", String(e.extra.retryAfter)); + return res.status(e.status).json({ error: e.message, code: e.code, ...e.extra }); + } + // Never the body: it can carry key shares. + console.error("vault-recovery:", e?.message || e); + res.status(500).json({ error: "Email recovery failed on the server." }); + } + }; +} + +const notConfigured = (res) => + res.status(503).json({ error: "Email recovery is not configured on this server.", code: "not_configured" }); + +/** A checkout link to put in a 402, when CoinPay is reachable; else the Settings page. */ +async function checkoutHint(user) { + try { + return (await createRecoveryCheckout({ user })).url; + } catch { + return `${config.origin}/settings#vault-recovery`; + } +} + +vaultRecoveryRouter.get("/api/opencreds/recovery", api(async (_req, res, user) => { + res.json(await recoveryStatus(user)); +})); + +vaultRecoveryRouter.post("/api/opencreds/recovery/checkout", api(async (req, res, user) => { + if (!user.email) return res.status(422).json({ error: "Add an email to your account first: recovery codes are sent there." }); + if (await isEntitled(user.id)) return res.status(409).json({ error: "Email recovery is already purchased.", code: "already_purchased" }); + try { + const session = await createRecoveryCheckout({ user }); + res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: priceUsd() }); + } catch (e) { + console.error("vault-recovery checkout failed:", e.message); + res.status(502).json({ error: "Could not open the CoinPay checkout. Try again in a minute." }); + } +})); + +vaultRecoveryRouter.post("/api/opencreds/recovery/enroll", api(async (req, res, user) => { + if (!recoveryConfigured()) return notConfigured(res); + if (!user.email) return res.status(422).json({ error: "This account has no email address to send the recovery code to." }); + if (!(await isEntitled(user.id))) { + return res.status(402).json({ + error: `Email recovery is a $${priceUsd()} lifetime add-on and is not purchased yet.`, + code: "payment_required", + priceUsd: priceUsd(), + checkoutUrl: await checkoutHint(user), + }); + } + const parsed = parseEnrollment(req.body); + // Drop the request's copy of U as soon as it is parsed (a string cannot be zeroed; this is what is possible). + if (req.body && typeof req.body === "object") delete req.body.userShare; + if (parsed.error) return res.status(422).json({ error: parsed.error }); + const result = await enroll(user, parsed, context(req)); + if (!result.ok) { + return res.status(502).json({ error: "Could not send the enrollment email, so nothing was enrolled. Try again.", code: "email_failed" }); + } + res.status(201).json({ enrolled: true, email: maskEmail(user.email) }); +})); + +vaultRecoveryRouter.post("/api/opencreds/recovery/start", api(async (req, res, user) => { + if (!recoveryConfigured()) return notConfigured(res); + res.json(await startRecovery(user, context(req))); +})); + +vaultRecoveryRouter.post("/api/opencreds/recovery/claim", api(async (req, res, user) => { + if (!recoveryConfigured()) return notConfigured(res); + res.json(await claimRecovery(user, req.body?.code, context(req))); +})); + +vaultRecoveryRouter.delete("/api/opencreds/recovery", api(async (req, res, user) => { + res.json(await disable(user.id, context(req))); +})); + +// ---- the Settings page ---- + +vaultRecoveryRouter.post("/settings/vault-recovery/checkout", requireAuth, async (req, res) => { + const back = "/settings"; + const user = await userRow(req.user.id); + if (!user?.email) return res.redirect(`${back}?err=${encodeURIComponent("Add an email to your account first: recovery codes are sent there.")}`); + if (await isEntitled(user.id)) return res.redirect(`${back}#vault-recovery`); + try { + const session = await createRecoveryCheckout({ user }); + res.redirect(303, session.url); + } catch (e) { + console.error("vault-recovery checkout failed:", e.message); + res.redirect(`${back}?err=${encodeURIComponent("Could not open the CoinPay checkout. Try again in a minute.")}`); + } +}); + +vaultRecoveryRouter.post("/settings/vault-recovery/disable", requireAuth, async (req, res) => { + await disable(req.user.id, context(req)); + res.redirect("/settings?vault_recovery=disabled#vault-recovery"); +}); + +/** The Settings card. Never throws: a database without the tables shows the card as unavailable. */ +export async function vaultRecoveryCard(req) { + let status; + try { + if (req.query.vault_recovery === "paid" && req.query.session_id) { + await reconcileRecoveryReturn(String(req.query.session_id), req.user).catch(() => null); + } + status = await recoveryStatus(req.user); + } catch { + return ""; + } + const notice = + req.query.vault_recovery === "paid" + ? status.purchased + ? `
Payment received. Turn email recovery on from the CLI: logicsrc vault recovery enable.
` + : `
Thanks. CoinPay is confirming the payment; this page shows it as purchased once it lands.
` + : req.query.vault_recovery === "cancelled" + ? `
Checkout cancelled. Nothing was charged.
` + : req.query.vault_recovery === "disabled" + ? `
Email recovery is off. The server deleted its share; the emailed code is useless now.
` + : ""; + const pill = (on, yes, no) => `${on ? yes : no}`; + const action = !status.purchased + ? `
${csrfInput(req)}
` + : status.enrolled + ? `
${csrfInput(req)}
` + : `

Turn it on from the CLI (it needs your unlocked vault): logicsrc vault recovery enable

`; + return ` +
Vault email recovery — $${esc(String(status.priceUsd))} lifetime
+
+ ${notice} +

A second way into your personal vault if you lose the master password and the offline recovery key. We email you a recovery code once; on the day you need it, logicsrc vault recover --email asks for that code plus a fresh one-time code. We keep an encrypted half of the key and never the code, so our database alone cannot open your vault. Someone with your mailbox and a compromised LogicSRC server could, which is why it is opt-in. Without it, your vault stays zero-knowledge.

+
+ ${pill(status.purchased, "purchased", "not purchased")} + ${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")} + ${status.email ? `codes go to ${esc(status.email)}` : ""} +
+ ${status.configured ? action : `

Not available on this server yet.

`} +
`; +} diff --git a/apps/pwa/src/server.mjs b/apps/pwa/src/server.mjs index 79d3f78e..3a7deb12 100644 --- a/apps/pwa/src/server.mjs +++ b/apps/pwa/src/server.mjs @@ -16,6 +16,7 @@ import { autoRotationRouter } from "./routes/auto-rotation.mjs"; import { sweepAutoRotation } from "./lib/auto-rotation.mjs"; import { apiKeysRouter } from "./routes/apikeys.mjs"; import { opencredsRouter } from "./routes/opencreds.mjs"; +import { vaultRecoveryRouter } from "./routes/vault-recovery.mjs"; import { keyringRouter } from "./routes/keyring.mjs"; import { keyringShareRouter, publicKeysRouter } from "./routes/keyring-share.mjs"; import { cliRouter } from "./routes/cli.mjs"; @@ -97,6 +98,7 @@ app.use(autoRotationRouter); // paid automatic rotation: CoinPay checkout + /api app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values) app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key) app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer) +app.use(vaultRecoveryRouter); // /api/opencreds/recovery/* + /settings/vault-recovery/* — opt-in paid email recovery app.use(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key) app.use(keyringRouter); // /api/keyring/* + /keyring — SSH keys / key pairs, ciphertext only app.use(cliRouter); // /cli/authorize, /cli/token, /api/me diff --git a/apps/pwa/test/vault-recovery.test.mjs b/apps/pwa/test/vault-recovery.test.mjs new file mode 100644 index 00000000..a1ebe12e --- /dev/null +++ b/apps/pwa/test/vault-recovery.test.mjs @@ -0,0 +1,362 @@ +// Vault email recovery (lib/vault-recovery.mjs, routes/vault-recovery.mjs): a +// paid, opt-in escrow. What these pin: enrolling needs the purchase (402 with a +// checkout link otherwise); the user share U goes out in the email and is never +// written anywhere; a failed email leaves nothing enrolled; one-time codes have +// a TTL, an attempt cap, single use and a start rate limit; a claim returns S +// decrypted and, with U, reopens the vault key; disable deletes the material; +// the shared CoinPay webhook settles vault_recovery once and still settles +// auto_rotation; a machine key never gets in. +process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:"; +process.env.COINPAY_WEBHOOK_SECRET = "whsec_test"; +process.env.COINPAY_API_KEY = "cp_test"; +process.env.COINPAY_API_URL = "https://coinpay.test"; +process.env.RESEND_API_KEY = "re_test"; +process.env.VAULT_ESCROW_KEY = (await import("node:crypto")).randomBytes(32).toString("base64"); +delete process.env.VAULT_ESCROW_KEY_VERSION; + +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import express from "express"; +import { signWebhook } from "@profullstack/coinpay-onboard"; +import { + createVault, + formatRecoveryCode, + fromBase64, + parseRecoveryCode, + prepareEnrollment, + recoverUserKeyByEmail, +} from "@logicsrc/opencreds"; + +const here = dirname(fileURLToPath(import.meta.url)); +const { db, run, get, all, isPostgres } = await import("../src/db.mjs"); +const { vaultRecoveryRouter } = await import("../src/routes/vault-recovery.mjs"); +const { autoRotationRouter } = await import("../src/routes/auto-rotation.mjs"); +const { createApiKey } = await import("../src/lib/apikey.mjs"); +const vr = await import("../src/lib/vault-recovery.mjs"); + +const now = Date.now(); + +if (isPostgres) { + await db.execute("DROP SCHEMA public CASCADE"); + await db.execute("CREATE SCHEMA public"); +} +for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql", "010_rotation_runs.sql", "011_rotation_policy.sql", "012_auto_rotation_billing.sql", "014_vault_email_recovery.sql"]) { + const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8"); + for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement); +} + +// ---- outbound mail and CoinPay, intercepted; everything else (our own server) passes through ---- +const realFetch = globalThis.fetch; +const mail = []; +let mailFails = false; +let sessionSeq = 0; +const sessions = new Map(); +globalThis.fetch = async (url, init = {}) => { + const u = String(url); + if (u.startsWith("https://api.resend.com/")) { + const body = JSON.parse(init.body); + if (mailFails) return new Response(JSON.stringify({ message: "down" }), { status: 500 }); + mail.push(body); + return new Response(JSON.stringify({ id: `em_${mail.length}` }), { status: 200 }); + } + if (u.startsWith("https://coinpay.test/api/checkout/sessions")) { + if ((init.method || "GET") === "POST") { + const input = JSON.parse(init.body); + const id = `cs_vr${++sessionSeq}`; + const session = { id, url: `https://coinpay.test/pay/${id}`, status: "open", amount: input.amount, currency: "USD", metadata: input.metadata, account_id: input.account_id }; + sessions.set(id, session); + return new Response(JSON.stringify({ session }), { status: 201 }); + } + const id = decodeURIComponent(u.split("/").pop()); + return new Response(JSON.stringify({ session: sessions.get(id) }), { status: 200 }); + } + return realFetch(url, init); +}; +test.after(() => { globalThis.fetch = realFetch; }); + +// ---- people, keys and a team (for the auto-rotation dispatch check) ---- +const users = ["u_a", "u_b", "u_c", "u_d", "u_e", "u_owner"]; +for (const uid of users) await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, `${uid}@example.com`, now]); +const keys = {}; +for (const uid of users) keys[uid] = (await createApiKey(uid, "cli")).plaintext; +await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t_acme", "acme", "acme", "u_owner", now]); +await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t_acme", "u_owner", "u_owner@example.com", "owner", "active", now]); +const machine = (await createApiKey("u_a", "dev2-deploy", { kind: "machine", teamId: "t_acme", vaultScope: null, readOnly: true })).plaintext; + +const app = express(); +app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf.toString("utf8"); } })); +app.use(vaultRecoveryRouter); +app.use(autoRotationRouter); +const server = app.listen(0); +await new Promise((r) => server.once("listening", r)); +const base = `http://127.0.0.1:${server.address().port}`; +test.after(() => new Promise((r) => server.close(r))); + +async function call(token, method, path, body, headers = {}) { + const raw = body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body); + const res = await realFetch(base + path, { + method, + headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(raw ? { "content-type": "application/json" } : {}), ...headers }, + body: raw, + }); + const text = await res.text(); + return { status: res.status, body: text ? JSON.parse(text) : null }; +} + +// One real vault for everything below (PBKDF2 at the floor, to keep this quick). +const vault = await createVault("old master password", { params: { kdf: "pbkdf2-sha256", iterations: 100_000 } }); + +async function enrollPayload() { + const prepared = await prepareEnrollment(vault.meta, vault.userKey); + return { ...prepared.payload }; +} +const grant = (uid, cs = `cs_grant_${uid}`) => + run(`INSERT INTO vault_recovery_payments (checkout_session_id, user_id, status, created_at, settled_at) VALUES (?,?,?,?,?)`, [cs, uid, "settled", now, now]); +const lastMailTo = (to) => [...mail].reverse().find((m) => m.to === to); +const codeIn = (text) => /\b([0-9A-Z]{5}(?:-[0-9A-Z]{5}){11})\b/.exec(text)?.[1]; +const otpIn = (text) => /One-time code: (\d{8})/.exec(text)?.[1]; + +async function enrolled(uid) { + await grant(uid); + const payload = await enrollPayload(); + const r = await call(keys[uid], "POST", "/api/opencreds/recovery/enroll", payload); + assert.equal(r.status, 201, JSON.stringify(r.body)); + return payload; +} + +test("no key: 401; a machine key is refused everywhere", async () => { + assert.equal((await call(null, "GET", "/api/opencreds/recovery")).status, 401); + for (const [method, path] of [["GET", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/enroll"], ["POST", "/api/opencreds/recovery/start"], ["POST", "/api/opencreds/recovery/claim"], ["DELETE", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/checkout"]]) { + const r = await call(machine, method, path, method === "POST" ? {} : undefined); + assert.equal(r.status, 403, `${method} ${path}`); + assert.equal(r.body.code, "machine_key_forbidden"); + } +}); + +test("enroll without the purchase: 402 with a checkout link, and nothing stored", async () => { + const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload()); + assert.equal(r.status, 402); + assert.equal(r.body.code, "payment_required"); + assert.equal(r.body.priceUsd, 5); + assert.match(r.body.checkoutUrl, /^https:\/\/coinpay\.test\/pay\/cs_vr\d+$/); + assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0); + const status = await call(keys.u_a, "GET", "/api/opencreds/recovery"); + assert.deepEqual({ ...status.body, enrolledAt: null }, { enrolled: false, enrolledAt: null, email: "u***@example.com", purchased: false, priceUsd: 5, configured: true }); +}); + +test("webhook: settles vault_recovery once (replay is a no-op) and still settles auto_rotation", async () => { + const checkout = await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout"); + assert.equal(checkout.status, 201); + const cs = checkout.body.sessionId; + const created = sessions.get(cs); + assert.equal(created.metadata.purpose, "vault_recovery"); + assert.equal(created.metadata.user_id, "u_a"); + assert.ok(created.metadata.payment_ref); + assert.equal((await get(`SELECT status FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs])).status, "pending"); + + const event = (id, data) => JSON.stringify({ id, type: "payment.confirmed", data: { payment_id: `pay_${id}`, status: "confirmed", amount_usd: 5, blockchain: "USDC_POL", property: "app.logicsrc.com", ...data } }); + const vrEvent = event("vr1", { checkout_session_id: cs, metadata: { purpose: "vault_recovery", user_id: "u_a", payment_ref: created.metadata.payment_ref } }); + assert.equal((await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": "t=1,v1=bad" })).status, 401); + const first = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") }); + assert.equal(first.status, 200); + assert.equal(first.body.purpose, "vault_recovery"); + assert.equal(first.body.action, "settled"); + const replay = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") }); + assert.equal(replay.body.duplicate, true); + const row = await get(`SELECT * FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs]); + assert.equal(row.status, "settled"); + assert.equal((await all(`SELECT * FROM vault_recovery_payments WHERE user_id = ? AND status = 'settled'`, ["u_a"])).length, 1); + assert.equal((await call(keys.u_a, "GET", "/api/opencreds/recovery")).body.purchased, true); + assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout")).status, 409); + + // The same endpoint, an auto-rotation purchase: routed to the old settler, unchanged. + const arEvent = event("ar1", { checkout_session_id: "cs_ar1", metadata: { purpose: "auto_rotation", team_id: "t_acme", user_id: "u_owner" } }); + const ar = await call(null, "POST", "/api/coinpay/webhook", arEvent, { "x-coinpay-signature": signWebhook(arEvent, "whsec_test") }); + assert.equal(ar.body.action, "activated"); + assert.equal(Number((await get(`SELECT rotation_auto_approve FROM credshare_teams WHERE id = ?`, ["t_acme"])).rotation_auto_approve), 1); + assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_payments WHERE checkout_session_id = ?`, ["cs_ar1"])).n), 0); + + // An unpaid vault_recovery event settles nothing. + const pending = JSON.stringify({ id: "vr2", type: "payment.pending", data: { status: "pending", metadata: { purpose: "vault_recovery", user_id: "u_b" } } }); + assert.equal((await call(null, "POST", "/api/coinpay/webhook", pending, { "x-coinpay-signature": signWebhook(pending, "whsec_test") })).body.handled, false); + assert.equal(await vr.isEntitled("u_b"), false); +}); + +test("enroll rolls back when the email does not send (a prior enrollment survives)", async () => { + mailFails = true; + try { + const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload()); + assert.equal(r.status, 502); + assert.equal(r.body.code, "email_failed"); + } finally { + mailFails = false; + } + assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0); + + await enrolled("u_c"); + const before = await get(`SELECT id FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_c"]); + mailFails = true; + try { + assert.equal((await call(keys.u_c, "POST", "/api/opencreds/recovery/enroll", await enrollPayload())).status, 502); + } finally { + mailFails = false; + } + const rows = await all(`SELECT id, status FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_c"]); + assert.deepEqual(rows.map((r) => [r.id, r.status]), [[before.id, "active"]]); +}); + +test("enroll emails U as a checksummed code and never stores it; a re-enroll replaces the old one", async () => { + const payload = await enrollPayload(); + const sent = mail.length; + const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", payload); + assert.equal(r.status, 201); + assert.deepEqual(r.body, { enrolled: true, email: "u***@example.com" }); + assert.ok(!JSON.stringify(r.body).includes(payload.userShare)); + + assert.equal(mail.length, sent + 1); + const email = mail.at(-1); + assert.equal(email.to, "u_a@example.com"); + assert.equal(email.subject, "Your LogicSRC vault email-recovery code — keep this email"); + const code = codeIn(email.text); + assert.ok(code, "a recovery code in the email"); + const U = fromBase64(payload.userShare); + // The server's renderer and the CLI's agree, and the CLI parses it back to U. + assert.equal(code, await formatRecoveryCode(U)); + assert.deepEqual(await parseRecoveryCode(code), U); + + // U is nowhere at rest: no column for it, and no value in any table holds it in any encoding. + const tables = ["vault_recovery_enrollments", "vault_recovery_codes", "vault_recovery_payments", "vault_recovery_audit", "users", "api_keys"]; + const needles = [payload.userShare, Buffer.from(U).toString("hex"), Buffer.from(U).toString("base64url"), code, code.replace(/-/g, "")]; + for (const table of tables) { + for (const row of await all(`SELECT * FROM ${table}`)) { + for (const [column, value] of Object.entries(row)) { + assert.ok(!/user_?share/i.test(column), `${table}.${column}`); + if (typeof value !== "string") continue; + for (const needle of needles) assert.ok(!value.includes(needle), `U found in ${table}.${column}`); + } + } + } + // S is stored only encrypted. + const active = await get(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_a"]); + assert.notEqual(active.server_share_ct, payload.serverShare); + assert.equal(Number(active.key_version), 1); + assert.equal(active.escrow_blob, payload.escrowBlob); + + // Re-enroll: a single active row, the old one revoked with its material deleted. + const again = await enrollPayload(); + assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", again)).status, 201); + const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? ORDER BY enrolled_at, status`, ["u_a"]); + assert.equal(rows.filter((x) => x.status === "active").length, 1); + const old = rows.find((x) => x.id === active.id); + assert.equal(old.status, "revoked"); + assert.equal(old.escrow_blob, null); + assert.equal(old.server_share_ct, null); +}); + +test("start + claim: emails a code, wrong code counts, the right one returns S decrypted and reopens K, once", async () => { + const payload = await enrolled("u_d"); + const U = await parseRecoveryCode(codeIn(lastMailTo("u_d@example.com").text)); + + const start = await call(keys.u_d, "POST", "/api/opencreds/recovery/start"); + assert.deepEqual(start.body, { sent: true, email: "u***@example.com" }); + const otp = otpIn(lastMailTo("u_d@example.com").text); + assert.match(otp, /^\d{8}$/); + const row = await get(`SELECT * FROM vault_recovery_codes WHERE user_id = ? AND used_at IS NULL`, ["u_d"]); + assert.ok(!row.code_hash.includes(otp)); + assert.equal(Number(row.expires_at) - Number(row.created_at), 15 * 60 * 1000); + + const wrong = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp === "00000000" ? "11111111" : "00000000" }); + assert.equal(wrong.status, 401); + assert.equal(wrong.body.attemptsLeft, 4); + + const notices = mail.length; + const claim = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp }); + assert.equal(claim.status, 200); + assert.deepEqual(claim.body, { escrowBlob: payload.escrowBlob, escrowIv: payload.escrowIv, serverShare: payload.serverShare, vaultCreatedAt: vault.meta.createdAt }); + assert.equal(mail.at(-1).subject, "Your LogicSRC vault email recovery was used"); + assert.equal(mail.length, notices + 1); + assert.ok((await all(`SELECT action FROM vault_recovery_audit WHERE user_id = ?`, ["u_d"])).some((a) => a.action === "claim")); + + // S from the server + U from the enrollment email = the vault's own key. + const K = await recoverUserKeyByEmail({ meta: vault.meta, material: claim.body, userShare: U }); + assert.deepEqual(K, vault.userKey); + + // Single use. + assert.equal((await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410); +}); + +test("codes expire after 15 minutes and die after 5 wrong tries", async () => { + await enrolled("u_e"); + await call(keys.u_e, "POST", "/api/opencreds/recovery/start"); + const expired = otpIn(lastMailTo("u_e@example.com").text); + await run(`UPDATE vault_recovery_codes SET expires_at = ? WHERE user_id = ? AND used_at IS NULL`, [Date.now() - 1, "u_e"]); + const late = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: expired }); + assert.equal(late.status, 410); + assert.equal(late.body.code, "code_expired"); + + await call(keys.u_e, "POST", "/api/opencreds/recovery/start"); + const otp = otpIn(lastMailTo("u_e@example.com").text); + const bad = otp === "99999999" ? "88888888" : "99999999"; + let r; + for (let i = 0; i < 5; i++) r = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: bad }); + assert.equal(r.status, 401); + assert.equal(r.body.attemptsLeft, 0); + const after = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: otp }); + assert.equal(after.status, 410, "the right code is dead after five wrong ones"); +}); + +test("start is rate limited to 3 per hour per user", async () => { + // u_e has used 2 starts above; one more is allowed, the next is not. + assert.equal((await call(keys.u_e, "POST", "/api/opencreds/recovery/start")).status, 200); + const limited = await call(keys.u_e, "POST", "/api/opencreds/recovery/start"); + assert.equal(limited.status, 429); + assert.equal(limited.body.code, "rate_limited"); + assert.ok(limited.body.retryAfter > 0); +}); + +test("start/claim need an active enrollment; disable deletes the material and kills live codes", async () => { + assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404); + + await enrolled("u_b"); + await call(keys.u_b, "POST", "/api/opencreds/recovery/start"); + const otp = otpIn(lastMailTo("u_b@example.com").text); + const off = await call(keys.u_b, "DELETE", "/api/opencreds/recovery"); + assert.deepEqual(off.body, { disabled: true }); + const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_b"]); + assert.ok(rows.every((x) => x.status === "revoked" && x.escrow_blob === null && x.escrow_iv === null && x.server_share_ct === null && x.server_share_iv === null)); + assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410); + assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404); + const status = (await call(keys.u_b, "GET", "/api/opencreds/recovery")).body; + assert.equal(status.enrolled, false); + assert.equal(status.purchased, true, "disabling does not burn the purchase"); + assert.deepEqual((await call(keys.u_b, "DELETE", "/api/opencreds/recovery")).body, { disabled: false }); +}); + +test("escrow keyring: a rotated key still opens rows sealed under the old version", () => { + const share = Buffer.alloc(32, 7); + const v1 = vr.escrowKeyring({ VAULT_ESCROW_KEY: process.env.VAULT_ESCROW_KEY }); + const sealed = vr.sealServerShare(share, "u_x", v1); + const rotated = vr.escrowKeyring({ VAULT_ESCROW_KEY: Buffer.alloc(32, 1).toString("base64"), VAULT_ESCROW_KEY_VERSION: "2", VAULT_ESCROW_KEY_V1: process.env.VAULT_ESCROW_KEY }); + assert.equal(rotated.version, 2); + const row = { user_id: "u_x", server_share_ct: sealed.ct, server_share_iv: sealed.iv, key_version: sealed.version }; + assert.deepEqual(vr.openServerShare(row, rotated), share); + // Bound to the user: the same ciphertext under another user id does not open. + assert.throws(() => vr.openServerShare({ ...row, user_id: "u_y" }, rotated)); + assert.throws(() => vr.escrowKeyring({ VAULT_ESCROW_KEY: "dG9vLXNob3J0" }), /32 random bytes/); +}); + +test("the Settings card: a Buy button before the purchase, the CLI hint after, a switch-off once enrolled", async () => { + const { vaultRecoveryCard } = await import("../src/routes/vault-recovery.mjs"); + const req = (uid) => ({ query: {}, user: { id: uid, email: `${uid}@example.com` }, csrfToken: "t" }); + const unpaid = await vaultRecoveryCard(req("u_owner")); + assert.match(unpaid, /Vault email recovery — \$5 lifetime/); + assert.match(unpaid, /action="\/settings\/vault-recovery\/checkout"/); + await grant("u_owner"); + assert.match(await vaultRecoveryCard(req("u_owner")), /logicsrc vault recovery enable/); + const on = await vaultRecoveryCard(req("u_a")); + assert.match(on, /action="\/settings\/vault-recovery\/disable"/); + assert.match(on, /u\*\*\*@example\.com/); +}); diff --git a/docs/opencreds/cli.md b/docs/opencreds/cli.md index c9660124..4f4b915c 100644 --- a/docs/opencreds/cli.md +++ b/docs/opencreds/cli.md @@ -52,6 +52,24 @@ opencreds recover # unlock with the recovery key, set a new password A password change re-wraps the user key. Not one item is re-encrypted, which is why it is instant on a vault of any size. +### Email recovery (`logicsrc vault` only) + +```bash +logicsrc vault recovery status [--json] # enrolled? since? email (masked)? purchased? +logicsrc vault recovery buy # CoinPay checkout link ($5, lifetime) +logicsrc vault recovery enable # enroll; emails a recovery code to keep +logicsrc vault recovery disable # server deletes its escrow share and blob +logicsrc vault recover --email # recovery code + fresh one-time code, then a new password +``` + +An opt-in, paid account feature; the standalone `opencreds` binary has no +account and exits 1 with a pointer to `logicsrc login`. `enable` exits 1 and +prints the checkout link when the purchase is missing. `recover --email` works +with the vault locked, exits 3 when the recovery code does not match, prints the +new offline recovery key once, and re-enrolls automatically (it warns loudly, +exit 0, if that last step fails). The trade-off is in +[security.md](./security.md#email-recovery-opt-in-paid). + ## Items ```bash diff --git a/docs/opencreds/crypto.md b/docs/opencreds/crypto.md index 5064778d..d31d4c70 100644 --- a/docs/opencreds/crypto.md +++ b/docs/opencreds/crypto.md @@ -122,6 +122,42 @@ rotating the key and re-encrypting, because the key they held is a key they may have kept. Partial sharing is not a feature of a shared key; it is a second vault. +## Email recovery escrow + +Email recovery (opt-in, paid) is a LogicSRC account feature, not part of the +format: a vault that never enrolls is untouched by it. The security trade-off is +in [security.md](./security.md#email-recovery-opt-in-paid); the construction is: + +``` +user key K (32 bytes) + │ + └─ AES-256-GCM(E, K, AAD = ":vault:email-escrow:v1|") → escrow blob + +E (32 random bytes, client-side, never sent whole) + ├─ S = 32 random bytes → server, AES-256-GCM under VAULT_ESCROW_KEY + │ (AAD binds the user id; key_version for rotation) + └─ U = E XOR S → emailed once as the recovery code, never stored +``` + +- **XOR, not a threshold scheme.** Two shares, both required: a 2-of-2 split is + XOR, and XOR with a uniformly random S makes U uniformly random too, so each + share alone carries no information about E. +- **The AAD carries `createdAt`.** It survives password changes and changes on + `init`, so an escrow blob cannot be replayed against a different vault. +- **The recovery code** is U in Crockford base32 (the alphabet of the offline + recovery key): 55 characters for 256 bits plus 19 zero bits, then a 5-character + check group, the first 25 bits of + `SHA-256("opencreds:email-recovery-code:v1" || U)`. Twelve groups of five. The + check group catches a typo before a one-time code is requested or spent; + a well-formed but wrong code fails the GCM tag on the escrow blob instead + ("recovery code doesn't match"). +- **After recovery** the client re-wraps K under the new password, replaces the + offline recovery key, and re-enrolls with a fresh E, S and U. K itself does not + change, so not one item is re-encrypted. +- **One-time codes** are 8 digits, stored as an HMAC under the server escrow key + (a dump of the codes table alone cannot brute-force a live one), 15 minutes, + 5 attempts, single use. + ## Randomness Every IV, salt, user key and recovery key MUST come from a cryptographic RNG diff --git a/docs/opencreds/security.md b/docs/opencreds/security.md index 4a410fbe..306c25cd 100644 --- a/docs/opencreds/security.md +++ b/docs/opencreds/security.md @@ -113,6 +113,56 @@ Consequences worth stating in a product's own docs: give them access, because it does not have the key. This is a feature, and it means a grant requires an authorized member to be online. +## Email recovery (opt-in, paid) + +The LogicSRC account service offers a second way back into a personal (`user` +profile) vault: `logicsrc vault recovery enable`, $5 once per account. It is off +unless the person turns it on, and it changes the threat model for those who +do. A vault that is never enrolled stays exactly as described above: the server +holds nothing that can open it. + +**What enrolling stores.** The client draws a random 32-byte escrow key E, +encrypts the user key under it, and splits E into two XOR shares, S and U. The +server stores the escrowed blob and S, with S encrypted under the server's own +escrow key (`VAULT_ESCROW_KEY`). U is rendered as a recovery code, emailed to +the account address once ("keep this email"), and dropped: no table has a +column for it. Each share alone is uniformly random and says nothing about E. +The crypto is in [crypto.md](./crypto.md#email-recovery-escrow). + +**What recovering needs.** `logicsrc vault recover --email` needs the recovery +code from the enrollment email (U) and a fresh 8-digit one-time code the server +mails at that moment (15 minutes, 5 tries, single use, 3 requests an hour), +plus a signed-in LogicSRC CLI. The server releases S only against that code, +logs the claim and mails a "your vault email recovery was used" notice. The +client recombines E, decrypts the user key, checks it opens an item, sets a new +master password, issues a new offline recovery key and re-enrolls with fresh +shares, so the code just used is dead. + +What this does and does not hold against, stated plainly: + +- **A stolen database, even with the server's environment (the escrow key):** + cannot open an enrolled vault. It yields the blob and S, and E also needs U, + which only the enrollment email has. +- **The enrollment email alone:** cannot open the vault. It is U without S, and + S is released only to a signed-in account that also receives a fresh code. +- **A live compromise of the server while a person enrolls or recovers:** can + open that vault. Enrollment hands U to the server in transit so it can be + mailed, and a claim hands S back out; code running on the server at that + moment sees what it needs. +- **Whoever controls the person's mailbox can open the vault.** The mailbox + holds U and receives the one-time code, and the LogicSRC account password + can itself be reset by email, so the mailbox alone is enough to sign in, claim + S and recombine E. The only defences are the notice emails (a claim and every + account-password reset are mailed, and the owner may see them first) and + disabling recovery. This is the reason the feature is opt-in: it moves the + vault's safety onto the security of an email account. Enable it only on an + email account with its own strong password and second factor. +- **The account operator** can see that a person enrolled, when, and when they + recovered; never the contents. + +Turning it off (`logicsrc vault recovery disable`, or Settings) deletes the +escrowed blob and S on the server, after which the emailed code is useless. + ## Reporting Security issues in the specification or the reference implementation: diff --git a/packages/cli/src/creds.ts b/packages/cli/src/creds.ts index 3bdfccf3..893ab9cb 100644 --- a/packages/cli/src/creds.ts +++ b/packages/cli/src/creds.ts @@ -1,6 +1,6 @@ import type { Command } from "commander"; import { registerCredsCommands } from "@logicsrc/opencreds/commands"; -import { accountRemoteFor } from "./vault-sync.js"; +import { accountRecoveryFor, accountRemoteFor } from "./vault-sync.js"; /** * `logicsrc vault …` @@ -53,6 +53,14 @@ gets it with: logicsrc login, then logicsrc vault sync. logicsrc vault sync --status what is synced, what is waiting LOGICSRC_VAULT_SYNC=off turn it off (a --home vault never syncs) +Lost the master password? The offline recovery key from init works: + logicsrc vault recover +Email recovery (opt-in, $5 lifetime) is a second way back in, through your account email: + logicsrc vault recovery buy CoinPay checkout link + logicsrc vault recovery enable emails you a recovery code to keep + logicsrc vault recover --email that code + a fresh emailed one-time code + logicsrc vault recovery status | disable + Help for any command: logicsrc vault --help (or: logicsrc vault help ) `; @@ -68,5 +76,5 @@ export function registerOpenCredsCommands(program: Command): void { .addHelpText("after", VAULT_GUIDE); // Logged in: the vault syncs to the account around every command. - registerCredsCommands(vault, { remote: accountRemoteFor }); + registerCredsCommands(vault, { remote: accountRemoteFor, emailRecovery: accountRecoveryFor }); } diff --git a/packages/cli/src/vault-recovery-client.test.ts b/packages/cli/src/vault-recovery-client.test.ts new file mode 100644 index 00000000..570df81b --- /dev/null +++ b/packages/cli/src/vault-recovery-client.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; +import { EmailRecoveryError } from "@logicsrc/opencreds"; +import { createRecoveryClient } from "./vault-sync.js"; + +type Call = { url: string; method: string; auth: string | null; body: unknown }; + +function fakeFetch(answers: Record) { + const calls: Call[] = []; + const impl = (async (url: string, init: RequestInit = {}) => { + const method = init.method ?? "GET"; + calls.push({ + url, + method, + auth: new Headers(init.headers).get("authorization"), + body: init.body ? JSON.parse(String(init.body)) : undefined, + }); + const answer = answers[`${method} ${new URL(url).pathname}`] ?? { status: 404, body: { error: "nope" } }; + return new Response(JSON.stringify(answer.body), { status: answer.status }); + }) as unknown as typeof fetch; + return { impl, calls }; +} + +describe("the email-recovery client", () => { + it("talks to /api/opencreds/recovery with the person's key", async () => { + const { impl, calls } = fakeFetch({ + "GET /api/opencreds/recovery": { status: 200, body: { enrolled: true, enrolledAt: "2026-11-30T00:00:00.000Z", email: "m***@x.test", purchased: true, priceUsd: 5 } }, + "POST /api/opencreds/recovery/claim": { status: 200, body: { escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" } }, + "DELETE /api/opencreds/recovery": { status: 200, body: { disabled: true } }, + }); + const client = createRecoveryClient("https://app.example/", "lsk_test", "me@x.test", impl); + expect(client.label).toBe("app.example (me@x.test)"); + expect((await client.status()).enrolled).toBe(true); + expect(await client.claim("12345678")).toEqual({ escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" }); + expect(await client.disable()).toEqual({ disabled: true }); + expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ + "GET https://app.example/api/opencreds/recovery", + "POST https://app.example/api/opencreds/recovery/claim", + "DELETE https://app.example/api/opencreds/recovery", + ]); + expect(calls.every((c) => c.auth === "Bearer lsk_test")).toBe(true); + expect(calls[1]!.body).toEqual({ code: "12345678" }); + }); + + it("surfaces a 402 with the checkout link", async () => { + const { impl } = fakeFetch({ + "POST /api/opencreds/recovery/enroll": { + status: 402, + body: { error: "Email recovery is a $5 lifetime add-on and is not purchased yet.", code: "payment_required", checkoutUrl: "https://coinpay.test/pay/cs_1" }, + }, + }); + const client = createRecoveryClient("https://app.example", "lsk_test", undefined, impl); + const err = await client + .enroll({ escrowBlob: "", escrowIv: "", serverShare: "", userShare: "", vaultCreatedAt: "" }) + .catch((e: unknown) => e); + expect(err).toBeInstanceOf(EmailRecoveryError); + expect((err as EmailRecoveryError).status).toBe(402); + expect((err as EmailRecoveryError).code).toBe("payment_required"); + expect((err as EmailRecoveryError).checkoutUrl).toBe("https://coinpay.test/pay/cs_1"); + }); +}); diff --git a/packages/cli/src/vault-sync.ts b/packages/cli/src/vault-sync.ts index b398c010..adbc13b5 100644 --- a/packages/cli/src/vault-sync.ts +++ b/packages/cli/src/vault-sync.ts @@ -1,6 +1,18 @@ import { join, resolve } from "node:path"; import { homedir } from "node:os"; -import type { Envelope, RemoteItem, RemoteVault, SyncRemote, VaultMeta, VaultStore } from "@logicsrc/opencreds"; +import { EmailRecoveryError } from "@logicsrc/opencreds"; +import type { + EmailRecoveryClient, + EmailRecoveryStatus, + Envelope, + EscrowEnrollment, + EscrowMaterial, + RemoteItem, + RemoteVault, + SyncRemote, + VaultMeta, + VaultStore, +} from "@logicsrc/opencreds"; import { readIdentity, resolveApiUrl } from "@logicsrc/plugin-credential-sharing"; /** @@ -92,3 +104,80 @@ export function createAccountRemote(apiUrl: string, token: string, email?: strin }, }; } + +/** + * Email recovery for the personal vault (`logicsrc vault recovery …`, + * `logicsrc vault recover --email`): apps/pwa /api/opencreds/recovery. + * + * Same scope rule as sync: it protects the account's vault, so a --home vault + * gets it only with LOGICSRC_VAULT_SYNC=on. Turning sync off does not turn + * recovery off; the two are independent. + */ +export function accountRecoveryFor(store: VaultStore): EmailRecoveryClient | undefined { + const setting = (process.env.LOGICSRC_VAULT_SYNC || "").toLowerCase(); + if (setting !== "on" && resolve(store.baseDir) !== resolve(defaultVaultDir())) return undefined; + const identity = readIdentity(); + if (!identity?.apiToken) return undefined; + return createRecoveryClient(resolveApiUrl(identity), identity.apiToken, identity.email); +} + +export function createRecoveryClient( + apiUrl: string, + token: string, + email?: string, + fetchImpl: typeof fetch = fetch, +): EmailRecoveryClient { + const base = apiUrl.replace(/\/+$/, ""); + const host = (() => { + try { + return new URL(base).host; + } catch { + return base; + } + })(); + + async function call(method: string, path: string, body?: unknown): Promise> { + const res = await fetchImpl(`${base}/api/opencreds/recovery${path}`, { + method, + headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(body ? { "content-type": "application/json" } : {}) }, + body: body ? JSON.stringify(body) : undefined, + signal: AbortSignal.timeout(30_000), + }); + const json = (await res.json().catch(() => ({}))) as Record; + if (!res.ok) { + throw new EmailRecoveryError( + String(json.error || `${host} answered HTTP ${res.status}`), + res.status, + typeof json.code === "string" ? json.code : undefined, + typeof json.checkoutUrl === "string" ? json.checkoutUrl : undefined, + ); + } + return json; + } + + return { + label: email ? `${host} (${email})` : host, + async status() { + return (await call("GET", "")) as unknown as EmailRecoveryStatus; + }, + async checkout() { + const body = await call("POST", "/checkout"); + return { url: String(body.url), priceUsd: Number(body.priceUsd) }; + }, + async enroll(payload: EscrowEnrollment) { + const body = await call("POST", "/enroll", payload); + return { enrolled: Boolean(body.enrolled), email: String(body.email ?? "") }; + }, + async start() { + const body = await call("POST", "/start"); + return { sent: Boolean(body.sent), email: typeof body.email === "string" ? body.email : undefined }; + }, + async claim(code: string) { + return (await call("POST", "/claim", { code })) as unknown as EscrowMaterial; + }, + async disable() { + const body = await call("DELETE", ""); + return { disabled: Boolean(body.disabled) }; + }, + }; +} diff --git a/packages/opencreds/src/cli.test.ts b/packages/opencreds/src/cli.test.ts index 25c196fc..0d2ccac3 100644 --- a/packages/opencreds/src/cli.test.ts +++ b/packages/opencreds/src/cli.test.ts @@ -285,3 +285,13 @@ describe("validate", () => { expect(result.code).toBe(2); }); }); + +describe("email recovery in the standalone binary", () => { + it("is an account feature: recover --email and recovery commands exit 1 and point at logicsrc login", async () => { + for (const args of [["recover", "--email"], ["recovery", "status"], ["recovery", "enable"]]) { + const result = await cli(args); + expect(result.code, args.join(" ")).toBe(1); + expect(result.stderr).toMatch(/logicsrc login/); + } + }); +}); diff --git a/packages/opencreds/src/commands.ts b/packages/opencreds/src/commands.ts index 87dc0dad..9be74075 100644 --- a/packages/opencreds/src/commands.ts +++ b/packages/opencreds/src/commands.ts @@ -58,6 +58,13 @@ import { createVault, resetRecoveryKey, rewrapUserKey, unlockVault, unlockWithRe import { formatDiagnostics, hasErrors, validateDocument } from "./validate.js"; import { DivergedVaultError, describeSync, pullVault, pushVault, readSyncState, syncVault, type SyncRemote } from "./sync.js"; import type { VaultStore } from "./store.js"; +import { + enrollEmailRecovery, + runEmailRecovery, + type EmailRecoveryClient, + type EmailRecoveryError, + type EmailRecoveryResult, +} from "./email-recovery.js"; /** Exit codes are part of the contract; see docs/opencreds/cli.md. */ export const EXIT = { @@ -302,6 +309,12 @@ export interface RegisterOptions { * `opencreds` binary passes nothing, so it never syncs. */ remote?: (store: VaultStore) => SyncRemote | undefined; + /** + * The account's email-recovery endpoints, if any (opt-in, paid). Called per + * command; return undefined when there is no logged-in account. Without it, + * `recover --email` and `recovery …` explain that they need `logicsrc login`. + */ + emailRecovery?: (store: VaultStore) => EmailRecoveryClient | undefined; } // Commands that never touch a vault on disk, plus `sync`, which syncs itself. @@ -474,12 +487,33 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions }); }); + const recoveryClient = (store: VaultStore): EmailRecoveryClient => { + const client = options.emailRecovery?.(store); + if (!client) { + fail( + options.emailRecovery + ? "Email recovery needs your account: run `logicsrc login` first. It protects the default vault only." + : "Email recovery is an account feature: use `logicsrc vault` after `logicsrc login`.", + EXIT.USAGE, + ); + } + return client; + }; + parent .command("recover") - .description("unlock with the recovery key and set a new master password") - .action(async function (this: Command) { + .description("unlock with the recovery key (or --email) and set a new master password") + .option("--email", "recover through your account email instead of the offline recovery key (needs `recovery enable` first)") + .addHelpText("after", examples(` + $CLI recover type the offline recovery key printed by \`init\` + $CLI recover --email the code from your enrollment email + a fresh emailed one-time code (works locked)`)) + .action(async function (this: Command, opts: { email?: boolean }) { await run(async () => { const store = storeFor(this); + if (opts.email) { + await recoverByEmail(store, recoveryClient(store)); + return; + } const meta = requireMeta(store); const recoveryKey = await promptSecret("Recovery key: "); let userKey: Uint8Array; @@ -499,6 +533,154 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions }); }); + // ------------------------------------------------------ email recovery --- + + async function recoverByEmail(store: VaultStore, client: EmailRecoveryClient): Promise { + requireMeta(store); + process.stderr.write( + 'Email recovery needs the recovery code from the "Your LogicSRC vault email-recovery code" email.\n', + ); + let result: EmailRecoveryResult; + try { + result = await runEmailRecovery({ + store, + client, + say: (line) => process.stderr.write(`${line}\n`), + prompts: { + recoveryCode: () => promptSecret("Recovery code from the enrollment email: "), + oneTimeCode: () => promptSecret("One-time code from the email just sent: "), + newPassword: () => promptNewSecret("New master password: ", "Repeat: "), + }, + }); + } catch (err) { + const code = (err as EmailRecoveryError).code; + fail((err as Error).message, code === "recovery_code_mismatch" || code === "escrow_stale" ? EXIT.CRYPTO : EXIT.USAGE); + } + unlockedKey = result.userKey; + store.appendAudit( + auditEvent({ action: "vault.recovery_reset", namespace: result.meta.namespace, reason: "email-recovery" }), + ); + process.stdout.write(`Master password changed through email recovery. Not one item was re-encrypted.\n\n`); + process.stdout.write(` New recovery key ${result.recoveryKey}\n\n`); + process.stdout.write("Write it down now; it will not be shown again. The old recovery key no longer works.\n"); + if (result.reenrolled) { + process.stdout.write( + `Email recovery is re-armed: a NEW recovery code was emailed to ${result.reenrolledEmail}. ` + + "The code you just used no longer works.\n", + ); + return; + } + process.stderr.write( + "\n!!! WARNING: your vault is recovered, but email recovery could NOT be re-armed" + + (result.reenrollError ? ` (${result.reenrollError})` : "") + + ".\n!!! The recovery code you just used may still work on the server. Run `" + cli + " recovery enable`\n" + + "!!! now to replace it, or `" + cli + " recovery disable` to turn email recovery off.\n", + ); + } + + const recovery = parent + .command("recovery") + .description("email recovery (opt-in, $5 lifetime): get back in through your account email if the password is lost") + .addHelpText("after", examples(` + $CLI recovery status enrolled? since when? which email? purchased? + $CLI recovery buy print the CoinPay checkout link ($5, lifetime) + $CLI recovery enable enroll this vault (unlocks it); emails you a recovery code to keep + $CLI recovery disable turn it off; the server deletes its escrow share and copy + $CLI recover --email the day you need it: works with the vault locked + +What the server keeps: a copy of your vault key encrypted under a random key E, +and one half of E (S), encrypted under the server's own key. The other half is +the recovery code in the enrollment email; the server never stores it. +Recovering needs that email plus a fresh one-time code. Without enrollment the +vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`)); + + recovery + .command("status") + .description("is email recovery enrolled and purchased (works locked)") + .option("--json", "machine-readable output") + .action(async function (this: Command, opts: { json?: boolean }) { + await run(async () => { + const client = recoveryClient(storeFor(this)); + const status = await client.status(); + if (opts.json) { + process.stdout.write(`${JSON.stringify(status, null, 2)}\n`); + return; + } + process.stdout.write(` Account ${client.label}\n`); + process.stdout.write( + ` Purchased ${status.purchased ? "yes (lifetime)" : `no ($${status.priceUsd} lifetime: \`${cli} recovery buy\`)`}\n`, + ); + process.stdout.write( + ` Enrolled ${status.enrolled ? `yes, since ${status.enrolledAt ?? "?"}` : `no${status.purchased ? ` (\`${cli} recovery enable\`)` : ""}`}\n`, + ); + if (status.email) process.stdout.write(` Email ${status.email}\n`); + }); + }); + + recovery + .command("buy") + .description("print the CoinPay checkout link for email recovery ($5 lifetime)") + .action(async function (this: Command) { + await run(async () => { + const client = recoveryClient(storeFor(this)); + const status = await client.status(); + if (status.purchased) { + process.stdout.write(`Email recovery is already purchased. Turn it on with \`${cli} recovery enable\`.\n`); + return; + } + const { url, priceUsd } = await client.checkout(); + process.stdout.write(`Pay $${priceUsd} (lifetime) here, then run \`${cli} recovery enable\`:\n\n ${url}\n`); + }); + }); + + recovery + .command("enable") + .description("enroll this vault in email recovery; running it again re-keys and emails a new code") + .action(async function (this: Command) { + await run(async () => { + const store = storeFor(this); + const client = recoveryClient(store); + const meta = requireMeta(store); + const status = await client.status(); + if (!status.purchased) { + const checkout = await client.checkout().catch(() => undefined); + fail( + `Email recovery is a $${status.priceUsd} lifetime add-on and is not purchased yet.` + + (checkout ? ` Pay here, then run this again:\n\n ${checkout.url}\n` : ` Run \`${cli} recovery buy\`.`), + EXIT.USAGE, + ); + } + const userKey = await unlock(store); + let result: { enrolled: boolean; email: string }; + try { + result = await enrollEmailRecovery(client, meta, userKey); + } catch (err) { + const e = err as EmailRecoveryError; + fail(`${e.message}${e.checkoutUrl ? `\n\n ${e.checkoutUrl}\n` : ""}`, EXIT.USAGE); + } + process.stdout.write( + `Email recovery is on. Your recovery code was emailed to ${result.email}.\n` + + "Keep that email: it is half of the way back in, and it is not stored anywhere else.\n" + + (status.enrolled ? "The previous recovery code no longer works.\n" : ""), + ); + }); + }); + + recovery + .command("disable") + .description("turn email recovery off; the server deletes its escrow share and copy") + .action(async function (this: Command) { + await run(async () => { + const client = recoveryClient(storeFor(this)); + const { disabled } = await client.disable(); + process.stdout.write( + disabled + ? "Email recovery is off. The server deleted its share, so the emailed recovery code is useless now.\n" + : "Email recovery was not enabled.\n", + ); + }); + }); + // ---------------------------------------------------------------- items --- const add = parent @@ -1109,7 +1291,9 @@ function registerSync( : `vault sync: skipped (${message}); changes stay on this machine and go up next time.`, ); }; - const autosync = (command: Command) => !NO_AUTOSYNC.has(command.name()) && process.env.OPENCREDS_SYNC !== "off"; + // `recovery …` talks to the account, not the vault files: nothing to sync around it. + const autosync = (command: Command) => + !NO_AUTOSYNC.has(command.name()) && command.parent?.name() !== "recovery" && process.env.OPENCREDS_SYNC !== "off"; parent.hook("preAction", async (_self, command) => { if (!autosync(command)) return; diff --git a/packages/opencreds/src/email-recovery.test.ts b/packages/opencreds/src/email-recovery.test.ts new file mode 100644 index 00000000..b99baecc --- /dev/null +++ b/packages/opencreds/src/email-recovery.test.ts @@ -0,0 +1,318 @@ +/** + * Email recovery: the XOR split, the escrow copy, the recovery code format, and + * the whole `recover --email` flow against a fake account server that behaves + * like apps/pwa (stores S and the blob, mails U and one-time codes, never keeps U). + */ + +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { + EmailRecoveryError, + RecoveryCodeMismatchError, + combineEscrowKey, + enrollEmailRecovery, + formatRecoveryCode, + openEscrow, + parseRecoveryCode, + prepareEnrollment, + recoverUserKeyByEmail, + runEmailRecovery, + sealEscrow, + splitEscrowKey, + xorBytes, + type EmailRecoveryClient, + type EscrowEnrollment, + type EscrowMaterial, +} from "./email-recovery.js"; +import { createItem, encryptItem } from "./items.js"; +import { fromBase64, randomBytes, toBase64 } from "./primitives.js"; +import { createVaultStore } from "./store.js"; +import { createVault, unlockVault, unlockWithRecoveryKey } from "./vault-key.js"; + +const FAST = { kdf: "pbkdf2-sha256" as const, iterations: 100_000 }; +const dirs: string[] = []; +afterEach(() => { + while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); +}); + +describe("the XOR split", () => { + it("splits E into two shares that recombine, and neither share is E", () => { + const E = randomBytes(32); + const { serverShare, userShare } = splitEscrowKey(E); + expect(serverShare).not.toEqual(E); + expect(userShare).not.toEqual(E); + expect(combineEscrowKey(serverShare, userShare)).toEqual(E); + expect(xorBytes(userShare, E)).toEqual(serverShare); + }); + + it("gives a fresh server share every time", () => { + const E = randomBytes(32); + expect(splitEscrowKey(E).serverShare).not.toEqual(splitEscrowKey(E).serverShare); + }); + + it("refuses shares of the wrong size", () => { + expect(() => splitEscrowKey(randomBytes(16))).toThrow(); + expect(() => combineEscrowKey(randomBytes(32), randomBytes(31))).toThrow(); + }); +}); + +describe("the escrow copy of the user key", () => { + it("round-trips K under E, bound to the vault", async () => { + const { meta, userKey } = await createVault("pw", { params: FAST }); + const sealed = await sealEscrow(userKey, meta); + const material = { ...sealed, vaultCreatedAt: meta.createdAt! }; + expect(await openEscrow(sealed.escrowKey, material, meta.namespace)).toEqual(userKey); + // Another vault's createdAt is different associated data: the tag fails. + await expect(openEscrow(sealed.escrowKey, { ...material, vaultCreatedAt: "2001-01-01T00:00:00Z" }, meta.namespace)).rejects.toBeInstanceOf( + RecoveryCodeMismatchError, + ); + }); + + it("a wrong U fails cleanly with a mismatch error, not a crypto stack", async () => { + const { meta, userKey } = await createVault("pw", { params: FAST }); + const { payload } = await prepareEnrollment(meta, userKey); + const material: EscrowMaterial = { ...payload }; + const wrongU = randomBytes(32); + const err = await recoverUserKeyByEmail({ meta, material, userShare: wrongU }).catch((e) => e); + expect(err).toBeInstanceOf(RecoveryCodeMismatchError); + expect(err.message).toMatch(/doesn't match/); + // The right U opens it. + expect(await recoverUserKeyByEmail({ meta, material, userShare: fromBase64(payload.userShare) })).toEqual(userKey); + }); + + it("refuses material enrolled for a different vault", async () => { + const a = await createVault("pw", { params: FAST }); + const b = await createVault("pw", { params: FAST }); + const { payload } = await prepareEnrollment(a.meta, a.userKey); + const err = await recoverUserKeyByEmail({ + meta: { ...b.meta, createdAt: "2030-01-01T00:00:00Z" }, + material: payload, + userShare: fromBase64(payload.userShare), + }).catch((e) => e); + expect(err).toBeInstanceOf(EmailRecoveryError); + expect(err.code).toBe("vault_mismatch"); + }); + + it("wipes E, S and U on request", async () => { + const { meta, userKey } = await createVault("pw", { params: FAST }); + const prepared = await prepareEnrollment(meta, userKey); + expect(fromBase64(prepared.payload.userShare).some((b) => b !== 0)).toBe(true); + prepared.wipe(); // no throw; the base64 copies in the payload are what gets sent + }); +}); + +describe("the recovery code", () => { + it("is twelve groups of five and parses back to U", async () => { + const U = randomBytes(32); + const code = await formatRecoveryCode(U); + expect(code).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){11}$/); + expect(await parseRecoveryCode(code)).toEqual(U); + }); + + it("tolerates case, spaces, missing dashes and Crockford's confusables", async () => { + const U = randomBytes(32); + const code = await formatRecoveryCode(U); + const sloppy = code.toLowerCase().replace(/-/g, " ").replace(/0/g, "o").replace(/1/g, "l"); + expect(await parseRecoveryCode(sloppy)).toEqual(U); + }); + + it("catches a typo with the check group, before anything is spent", async () => { + const U = randomBytes(32); + const code = await formatRecoveryCode(U); + // Change one data character to a different valid one. + const i = 7; + const swapped = code[i] === "A" ? "B" : "A"; + const typo = code.slice(0, i) + swapped + code.slice(i + 1); + const err = await parseRecoveryCode(typo).catch((e) => e); + expect(err).toBeInstanceOf(EmailRecoveryError); + expect(err.code).toBe("recovery_code_typo"); + // A typo in the check group itself is caught too. + const last = code.at(-1) === "Z" ? "Y" : "Z"; + expect((await parseRecoveryCode(code.slice(0, -1) + last).catch((e) => e)).code).toBe("recovery_code_typo"); + }); + + it("rejects the wrong length and bad characters", async () => { + expect((await parseRecoveryCode("ABCDE-FGHJK").catch((e) => e)).code).toBe("recovery_code_invalid"); + const code = await formatRecoveryCode(randomBytes(32)); + expect((await parseRecoveryCode(code.replace(/^./, "U")).catch((e) => e)).code).toBe("recovery_code_invalid"); + }); +}); + +/** A fake apps/pwa: keeps S and the blob, "mails" U and one-time codes, and never stores U. */ +function fakeServer() { + let enrollment: (EscrowMaterial & { active: boolean }) | null = null; + let otp: { code: string; used: boolean } | null = null; + const inbox: string[] = []; + const state = { starts: 0, claims: 0, failEnroll: false }; + const client: EmailRecoveryClient = { + label: "fake.test (me@example.com)", + async status() { + return { enrolled: Boolean(enrollment?.active), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5 }; + }, + async checkout() { + return { url: "https://coinpay.test/pay/cs_1", priceUsd: 5 }; + }, + async enroll(p: EscrowEnrollment) { + if (state.failEnroll) throw new EmailRecoveryError("Could not send the enrollment email", 502, "email_failed"); + enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt, active: true }; + inbox.push(await formatRecoveryCode(fromBase64(p.userShare))); + otp = null; + return { enrolled: true, email: "m***@example.com" }; + }, + async start() { + if (!enrollment?.active) throw new EmailRecoveryError("not enrolled", 404, "not_enrolled"); + state.starts++; + otp = { code: String(Math.floor(Math.random() * 1e8)).padStart(8, "0"), used: false }; + return { sent: true, email: "m***@example.com" }; + }, + async claim(code: string) { + state.claims++; + if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code"); + otp.used = true; + const { active: _active, ...material } = enrollment!; + return material; + }, + async disable() { + const was = Boolean(enrollment?.active); + enrollment = null; + return { disabled: was }; + }, + }; + return { client, inbox, state, otp: () => otp?.code ?? "" }; +} + +async function vaultOnDisk() { + const dir = mkdtempSync(join(tmpdir(), "opencreds-email-recovery-")); + dirs.push(dir); + const store = createVaultStore(dir); + const created = await createVault("old master password", { params: FAST }); + store.writeMeta(created.meta); + const item = createItem("login", { name: "GitHub", login: { username: "me", password: "hunter2" } }); + store.writeEnvelope(await encryptItem(created.userKey, item, created.meta.namespace)); + return { store, ...created }; +} + +describe("recover --email, end to end against a fake server", () => { + it("new password unlocks; the old password and the old recovery key do not; the used code is dead", async () => { + const { store, meta, userKey, recoveryKey: oldRecoveryKey } = await vaultOnDisk(); + const server = fakeServer(); + await enrollEmailRecovery(server.client, meta, userKey); + const enrolledCode = server.inbox.at(-1)!; + + const said: string[] = []; + const result = await runEmailRecovery({ + store, + client: server.client, + say: (l) => said.push(l), + prompts: { + recoveryCode: async () => enrolledCode, + oneTimeCode: async () => server.otp(), + newPassword: async () => "brand new master password", + }, + }); + + expect(result.userKey).toEqual(userKey); + expect(result.recoveryKey).not.toBe(oldRecoveryKey); + expect(said.join("\n")).toMatch(/one-time code was emailed to m\*\*\*@example\.com/); + + const onDisk = store.readMeta()!; + expect(onDisk.createdAt).toBe(meta.createdAt); + expect(await unlockVault(onDisk, "brand new master password")).toEqual(userKey); + await expect(unlockVault(onDisk, "old master password")).rejects.toThrow(/Wrong master password/); + await expect(unlockWithRecoveryKey(onDisk, oldRecoveryKey)).rejects.toThrow(/Wrong recovery key/); + expect(await unlockWithRecoveryKey(onDisk, result.recoveryKey)).toEqual(userKey); + + // Re-armed with fresh shares: a new code was mailed and the old one no longer opens anything. + expect(result.reenrolled).toBe(true); + expect(server.inbox).toHaveLength(2); + expect(server.inbox[1]).not.toBe(enrolledCode); + await server.client.start(); + const material = await server.client.claim(server.otp()); + await expect( + recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(enrolledCode) }), + ).rejects.toBeInstanceOf(RecoveryCodeMismatchError); + expect( + await recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(server.inbox[1]!) }), + ).toEqual(userKey); + }); + + it("a wrong recovery code: clear mismatch error, the one-time code is spent, the vault untouched", async () => { + const { store, meta, userKey } = await vaultOnDisk(); + const server = fakeServer(); + await enrollEmailRecovery(server.client, meta, userKey); + const before = JSON.stringify(store.readMeta()); + const otherCode = await formatRecoveryCode(randomBytes(32)); // well-formed, just not ours + let asked = false; + const err = await runEmailRecovery({ + store, + client: server.client, + prompts: { + recoveryCode: async () => otherCode, + oneTimeCode: async () => server.otp(), + newPassword: async () => { + asked = true; + return "x"; + }, + }, + }).catch((e) => e); + expect(err).toBeInstanceOf(RecoveryCodeMismatchError); + expect(err.message).toMatch(/doesn't match/); + expect(asked).toBe(false); + expect(server.state.claims).toBe(1); + await expect(server.client.claim(server.otp())).rejects.toThrow(/Wrong one-time code/); // spent + expect(JSON.stringify(store.readMeta())).toBe(before); + expect((await server.client.status()).enrolled).toBe(true); // the purchase and enrollment stand + }); + + it("a typo in the recovery code costs nothing: no one-time code is requested", async () => { + const { store, meta, userKey } = await vaultOnDisk(); + const server = fakeServer(); + await enrollEmailRecovery(server.client, meta, userKey); + const code = server.inbox.at(-1)!; + const typo = code.slice(0, 3) + (code[3] === "A" ? "B" : "A") + code.slice(4); + const err = await runEmailRecovery({ + store, + client: server.client, + prompts: { recoveryCode: async () => typo, oneTimeCode: async () => "", newPassword: async () => "x" }, + }).catch((e) => e); + expect(err.code).toBe("recovery_code_typo"); + expect(server.state.starts).toBe(0); + }); + + it("if re-enrolling fails the vault is still recovered, and the result says so", async () => { + const { store, meta, userKey } = await vaultOnDisk(); + const server = fakeServer(); + await enrollEmailRecovery(server.client, meta, userKey); + const code = server.inbox.at(-1)!; + server.state.failEnroll = true; + const result = await runEmailRecovery({ + store, + client: server.client, + prompts: { recoveryCode: async () => code, oneTimeCode: async () => server.otp(), newPassword: async () => "new pw" }, + }); + expect(result.reenrolled).toBe(false); + expect(result.reenrollError).toMatch(/enrollment email/); + expect(await unlockVault(store.readMeta()!, "new pw")).toEqual(userKey); + }); + + it("the server never receives E, and U only in the enroll call", async () => { + const { meta, userKey } = await vaultOnDisk(); + const seen: EscrowEnrollment[] = []; + const server = fakeServer(); + const spy: EmailRecoveryClient = { + ...server.client, + enroll: async (p) => { + seen.push({ ...p }); + return server.client.enroll(p); + }, + }; + await enrollEmailRecovery(spy, meta, userKey); + const p = seen[0]!; + const E = combineEscrowKey(fromBase64(p.serverShare), fromBase64(p.userShare)); + for (const value of Object.values(p)) expect(value).not.toBe(toBase64(E)); + expect(await openEscrow(E, p, meta.namespace)).toEqual(userKey); + }); +}); diff --git a/packages/opencreds/src/email-recovery.ts b/packages/opencreds/src/email-recovery.ts new file mode 100644 index 00000000..89754bc3 --- /dev/null +++ b/packages/opencreds/src/email-recovery.ts @@ -0,0 +1,401 @@ +/** + * Email recovery (opt-in, paid): a way back into a personal vault after the + * master password AND the offline recovery key are gone, through the account's + * mailbox. + * + * The client generates a random escrow key E and encrypts the user key K under + * it. E is then split into two XOR shares: + * + * S random 32 bytes held by the server, encrypted under its escrow key + * U E XOR S mailed to the account once, as a recovery code; never stored + * + * Neither share alone says anything about E (each is uniformly random on its + * own), so neither the database, nor the database plus the server's env, nor + * the enrollment email alone opens the vault. Recovering needs U (the user's + * mailbox, from enrollment) and S, which the server releases only against a + * fresh one-time code mailed at recovery time. + * + * The server sees U in transit once, at enrollment, to put it in the email. A + * live server compromise at that moment, or an attacker holding both the + * mailbox and a live server, can recover the vault; that is the trade this + * feature makes, and why it is opt-in. See docs/opencreds/security.md. + */ + +import { decryptItem } from "./items.js"; +import { emailEscrowLabel } from "./kdf.js"; +import { aesGcmDecrypt, aesGcmEncrypt, fromBase64, KEY_BYTES, randomBytes, sha256, toBase64, utf8Encode } from "./primitives.js"; +import type { VaultStore } from "./store.js"; +import type { Envelope, VaultMeta } from "./types.js"; +import { assertProfile, resetRecoveryKey, rewrapUserKey } from "./vault-key.js"; + +/** Crockford base32, the same alphabet as the offline recovery key. */ +const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + +/** U is 256 bits; 55 characters carry 275, the last 19 always zero, so the groups come out even. */ +export const RECOVERY_CODE_DATA_CHARS = 55; +/** One trailing group of five is a 25-bit checksum, so a typo is caught before anything is spent. */ +export const RECOVERY_CODE_CHECK_CHARS = 5; +export const RECOVERY_CODE_CHARS = RECOVERY_CODE_DATA_CHARS + RECOVERY_CODE_CHECK_CHARS; +/** Domain separation for the checksum hash; the server renders codes with the same rule. */ +export const RECOVERY_CODE_CHECK_PREFIX = "opencreds:email-recovery-code:v1"; + +/** Something went wrong in a way the person can act on. */ +export class EmailRecoveryError extends Error { + constructor( + message: string, + readonly status?: number, + readonly code?: string, + readonly checkoutUrl?: string, + ) { + super(message); + } +} + +/** The recovery code decrypted nothing: it is not the code for this enrollment. */ +export class RecoveryCodeMismatchError extends EmailRecoveryError { + constructor() { + super( + "That recovery code doesn't match this vault's email recovery. Use the code from the most recent " + + "\"vault email-recovery code\" email; an older one stops working when recovery is re-enabled.", + undefined, + "recovery_code_mismatch", + ); + } +} + +/** What the client sends to enroll. U (`userShare`) is mailed by the server and never stored. */ +export interface EscrowEnrollment { + escrowBlob: string; + escrowIv: string; + serverShare: string; + userShare: string; + vaultCreatedAt: string; +} + +/** What the server releases on a successful claim. */ +export interface EscrowMaterial { + escrowBlob: string; + escrowIv: string; + serverShare: string; + vaultCreatedAt: string; +} + +export interface EmailRecoveryStatus { + enrolled: boolean; + enrolledAt: string | null; + /** Masked, e.g. a***@example.com. */ + email: string | null; + purchased: boolean; + priceUsd: number; +} + +/** The account's email-recovery endpoints. The logicsrc CLI provides one. */ +export interface EmailRecoveryClient { + label: string; + status(): Promise; + checkout(): Promise<{ url: string; priceUsd: number }>; + /** Throws EmailRecoveryError with status 402 and a checkoutUrl when not purchased. */ + enroll(payload: EscrowEnrollment): Promise<{ enrolled: boolean; email: string }>; + start(): Promise<{ sent: boolean; email?: string }>; + claim(code: string): Promise; + disable(): Promise<{ disabled: boolean }>; +} + +// ------------------------------------------------------------- shares --- + +export function xorBytes(a: Uint8Array, b: Uint8Array): Uint8Array { + if (a.length !== b.length) throw new Error("XOR shares must be the same length"); + const out = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) out[i] = a[i]! ^ b[i]!; + return out; +} + +/** Split E into a random server share S and the user share U = E XOR S. */ +export function splitEscrowKey(escrowKey: Uint8Array): { serverShare: Uint8Array; userShare: Uint8Array } { + if (escrowKey.length !== KEY_BYTES) throw new Error(`The escrow key must be ${KEY_BYTES} bytes`); + const serverShare = randomBytes(KEY_BYTES); + return { serverShare, userShare: xorBytes(escrowKey, serverShare) }; +} + +/** E = S XOR U. */ +export function combineEscrowKey(serverShare: Uint8Array, userShare: Uint8Array): Uint8Array { + if (serverShare.length !== KEY_BYTES || userShare.length !== KEY_BYTES) { + throw new Error(`Both escrow shares must be ${KEY_BYTES} bytes`); + } + return xorBytes(serverShare, userShare); +} + +/** Overwrite key material that is no longer needed. Best effort: JS gives no stronger guarantee. */ +export function wipe(...buffers: Array): void { + for (const b of buffers) b?.fill(0); +} + +// --------------------------------------------------------------- escrow --- + +/** AAD binds the escrow copy to its purpose and to one vault (createdAt survives password changes). */ +export function escrowAad(namespace: string, vaultCreatedAt: string): Uint8Array { + return utf8Encode(`${emailEscrowLabel(namespace)}|${vaultCreatedAt}`); +} + +/** Encrypt the user key under a fresh random escrow key E. */ +export async function sealEscrow( + userKey: Uint8Array, + meta: VaultMeta, +): Promise<{ escrowKey: Uint8Array; escrowBlob: string; escrowIv: string }> { + assertProfile(meta, ["user"]); + if (!meta.createdAt) throw new Error("This vault has no createdAt; it cannot be enrolled in email recovery"); + const escrowKey = randomBytes(KEY_BYTES); + const { iv, ciphertext } = await aesGcmEncrypt(escrowKey, userKey, escrowAad(meta.namespace, meta.createdAt)); + return { escrowKey, escrowBlob: toBase64(ciphertext), escrowIv: toBase64(iv) }; +} + +/** Decrypt the user key with E. A wrong E (a wrong U) fails the GCM tag: {@link RecoveryCodeMismatchError}. */ +export async function openEscrow( + escrowKey: Uint8Array, + material: Pick, + namespace: string, +): Promise { + try { + return await aesGcmDecrypt( + escrowKey, + fromBase64(material.escrowIv), + fromBase64(material.escrowBlob), + escrowAad(namespace, material.vaultCreatedAt), + ); + } catch { + throw new RecoveryCodeMismatchError(); + } +} + +/** + * Everything enrollment sends, plus a `wipe` that zeroes E, S and U. The + * payload's base64 strings cannot be zeroed; they live only until the request + * is sent. + */ +export async function prepareEnrollment( + meta: VaultMeta, + userKey: Uint8Array, +): Promise<{ payload: EscrowEnrollment; wipe: () => void }> { + const { escrowKey, escrowBlob, escrowIv } = await sealEscrow(userKey, meta); + const { serverShare, userShare } = splitEscrowKey(escrowKey); + return { + payload: { + escrowBlob, + escrowIv, + serverShare: toBase64(serverShare), + userShare: toBase64(userShare), + vaultCreatedAt: meta.createdAt!, + }, + wipe: () => wipe(escrowKey, serverShare, userShare), + }; +} + +/** Enroll (or re-enroll) this vault. The server mails U and keeps S; a prior enrollment stops working. */ +export async function enrollEmailRecovery( + client: EmailRecoveryClient, + meta: VaultMeta, + userKey: Uint8Array, +): Promise<{ enrolled: boolean; email: string }> { + const prepared = await prepareEnrollment(meta, userKey); + try { + return await client.enroll(prepared.payload); + } finally { + prepared.wipe(); + prepared.payload.userShare = ""; + prepared.payload.serverShare = ""; + } +} + +// -------------------------------------------------------- recovery code --- + +function encodeBits(bytes: Uint8Array, chars: number): string { + let out = ""; + for (let i = 0; i < chars; i++) { + let v = 0; + for (let b = 0; b < 5; b++) { + const bit = i * 5 + b; + const byte = bit >> 3; + v = (v << 1) | (byte < bytes.length ? (bytes[byte]! >> (7 - (bit & 7))) & 1 : 0); + } + out += ALPHABET[v]; + } + return out; +} + +/** Decode `text` into `length` bytes; `padOk` is false when a bit past them is set. */ +function decodeBits(text: string, length: number): { bytes: Uint8Array; padOk: boolean } { + const bytes = new Uint8Array(length); + let padOk = true; + for (let i = 0; i < text.length; i++) { + const v = ALPHABET.indexOf(text[i]!); + if (v < 0) throw new EmailRecoveryError(`Invalid character in recovery code: ${text[i]}`, undefined, "recovery_code_invalid"); + for (let b = 0; b < 5; b++) { + const bit = i * 5 + b; + const set = (v >> (4 - b)) & 1; + const byte = bit >> 3; + if (byte < length) bytes[byte] = (bytes[byte] ?? 0) | (set << (7 - (bit & 7))); + else if (set) padOk = false; + } + } + return { bytes, padOk }; +} + +async function checkGroup(userShare: Uint8Array): Promise { + const digest = await sha256(new Uint8Array([...utf8Encode(RECOVERY_CODE_CHECK_PREFIX), ...userShare])); + return encodeBits(digest, RECOVERY_CODE_CHECK_CHARS); +} + +/** + * Render U for the enrollment email: 11 groups of data and one check group, + * twelve groups of five in all. + */ +export async function formatRecoveryCode(userShare: Uint8Array): Promise { + if (userShare.length !== KEY_BYTES) throw new Error(`The user share must be ${KEY_BYTES} bytes`); + const text = encodeBits(userShare, RECOVERY_CODE_DATA_CHARS) + (await checkGroup(userShare)); + return (text.match(/.{1,5}/g) ?? []).join("-"); +} + +/** + * Parse a recovery code back into U, tolerating case, spaces and dashes and + * Crockford's confusables. A typo fails the check group here, before the + * one-time code is asked for or spent. + */ +export async function parseRecoveryCode(input: string): Promise { + const clean = String(input || "") + .toUpperCase() + .replace(/[^0-9A-Z]/g, "") + .replace(/O/g, "0") + .replace(/[IL]/g, "1"); + if (clean.length !== RECOVERY_CODE_CHARS) { + throw new EmailRecoveryError( + `That recovery code has ${clean.length} characters; it should have ${RECOVERY_CODE_CHARS} (12 groups of 5). ` + + "Copy it again from the enrollment email.", + undefined, + "recovery_code_invalid", + ); + } + const { bytes, padOk } = decodeBits(clean.slice(0, RECOVERY_CODE_DATA_CHARS), KEY_BYTES); + const check = clean.slice(RECOVERY_CODE_DATA_CHARS); + if (!padOk || check !== (await checkGroup(bytes))) { + wipe(bytes); + throw new EmailRecoveryError( + "That recovery code has a typo (its last group, the check group, does not match). Copy it again from the enrollment email.", + undefined, + "recovery_code_typo", + ); + } + return bytes; +} + +// ------------------------------------------------------------- recovery --- + +/** + * K from the server's material and the user's code. Checks the material is for + * this vault, and that K actually opens an item when there is one to try. + */ +export async function recoverUserKeyByEmail(input: { + meta: VaultMeta; + material: EscrowMaterial; + userShare: Uint8Array; + envelopes?: Envelope[]; +}): Promise { + const { meta, material, userShare } = input; + assertProfile(meta, ["user"]); + if (material.vaultCreatedAt !== meta.createdAt) { + throw new EmailRecoveryError( + `Email recovery was enrolled for a different vault (created ${material.vaultCreatedAt}); this one was created ${meta.createdAt ?? "?"}.`, + undefined, + "vault_mismatch", + ); + } + const serverShare = fromBase64(material.serverShare); + const escrowKey = combineEscrowKey(serverShare, userShare); + try { + const userKey = await openEscrow(escrowKey, material, meta.namespace); + const probe = input.envelopes?.[0]; + if (probe) { + try { + await decryptItem(userKey, probe, meta.namespace); + } catch { + wipe(userKey); + throw new EmailRecoveryError( + "The escrowed key does not open this vault's items. Nothing was changed.", + undefined, + "escrow_stale", + ); + } + } + return userKey; + } finally { + wipe(serverShare, escrowKey); + } +} + +export interface EmailRecoveryPrompts { + /** The recovery code from the enrollment email. */ + recoveryCode(): Promise; + /** The 8-digit one-time code mailed by `start`. */ + oneTimeCode(email: string | undefined): Promise; + /** The new master password, already confirmed. */ + newPassword(): Promise; +} + +export interface EmailRecoveryResult { + meta: VaultMeta; + userKey: Uint8Array; + /** The new offline recovery key, to print once. */ + recoveryKey: string; + reenrolled: boolean; + reenrolledEmail?: string; + reenrollError?: string; +} + +/** + * The whole `recover --email` flow over a store and a client. + * + * Order matters: the recovery code is checked (checksum) before a one-time code + * is requested, so a typo costs nothing; the one-time code is spent on claim; + * nothing on disk changes until K is proven. After the new password is set, + * email recovery is re-armed with fresh shares, so the code just used is dead. + */ +export async function runEmailRecovery(opts: { + store: VaultStore; + client: EmailRecoveryClient; + prompts: EmailRecoveryPrompts; + say?: (line: string) => void; +}): Promise { + const { store, client, prompts } = opts; + const say = opts.say ?? (() => {}); + const meta = store.readMeta(); + if (!meta) throw new EmailRecoveryError(`No vault at ${store.baseDir}`, undefined, "no_vault"); + assertProfile(meta, ["user"]); + + const userShare = await parseRecoveryCode(await prompts.recoveryCode()); + const userKey = await (async () => { + try { + const started = await client.start(); + say(`A one-time code was emailed to ${started.email ?? "your account email"}. It expires in 15 minutes.`); + const code = (await prompts.oneTimeCode(started.email)).replace(/\s+/g, ""); + const material = await client.claim(code); + return await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() }); + } finally { + wipe(userShare); + } + })(); + + const password = await prompts.newPassword(); + if (!password) throw new EmailRecoveryError("A master password is required", undefined, "no_password"); + const rewrapped = await rewrapUserKey(meta, userKey, password); + const reset = await resetRecoveryKey(rewrapped, userKey); + store.writeMeta(reset.meta); + + const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false }; + try { + const enrolled = await enrollEmailRecovery(client, reset.meta, userKey); + result.reenrolled = Boolean(enrolled.enrolled); + result.reenrolledEmail = enrolled.email; + } catch (err) { + result.reenrollError = (err as Error).message; + } + return result; +} diff --git a/packages/opencreds/src/index.ts b/packages/opencreds/src/index.ts index e6fa48e2..d3bf4377 100644 --- a/packages/opencreds/src/index.ts +++ b/packages/opencreds/src/index.ts @@ -53,6 +53,7 @@ export { wrapLabel, authLabel, recoveryLabel, + emailEscrowLabel, itemLabel, databaseLabel, assertUsableNamespace, @@ -177,6 +178,33 @@ export { type SyncState, } from "./sync.js"; +export { + EmailRecoveryError, + RecoveryCodeMismatchError, + RECOVERY_CODE_CHARS, + RECOVERY_CODE_CHECK_CHARS, + RECOVERY_CODE_CHECK_PREFIX, + RECOVERY_CODE_DATA_CHARS, + combineEscrowKey, + enrollEmailRecovery, + escrowAad, + formatRecoveryCode, + openEscrow, + parseRecoveryCode, + prepareEnrollment, + recoverUserKeyByEmail, + runEmailRecovery, + sealEscrow, + splitEscrowKey, + xorBytes, + type EmailRecoveryClient, + type EmailRecoveryPrompts, + type EmailRecoveryResult, + type EmailRecoveryStatus, + type EscrowEnrollment, + type EscrowMaterial, +} from "./email-recovery.js"; + export { auditEvent, fingerprint, type AuditInput } from "./audit.js"; export { diff --git a/packages/opencreds/src/kdf.ts b/packages/opencreds/src/kdf.ts index 730688f6..a304badd 100644 --- a/packages/opencreds/src/kdf.ts +++ b/packages/opencreds/src/kdf.ts @@ -58,6 +58,15 @@ export function recoveryLabel(namespace: Namespace): string { return `${namespace}:vault:recovery:v1`; } +/** + * Associated data for the email-recovery escrow copy of the user key. Not an + * HKDF label: the escrow key is random, not derived, so the label only binds + * the ciphertext to its purpose (and, with the vault's createdAt, to one vault). + */ +export function emailEscrowLabel(namespace: Namespace): string { + return `${namespace}:vault:email-escrow:v1`; +} + export function itemLabel(namespace: Namespace, version: number, id: string): string { return `${namespace}:vault:item:${version}:${id}`; }