// 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 }; } /** A recovery that finished in the last half hour: this enrollment is the automatic re-arm after it. */ const REARM_WINDOW_MS = 30 * 60 * 1000; async function followsRecovery(userId, now) { const last = await get(`SELECT action, created_at FROM vault_recovery_audit WHERE user_id = ? ORDER BY created_at DESC LIMIT 1`, [userId]).catch(() => null); return Boolean(last && last.action === "claim" && now - Number(last.created_at) <= REARM_WINDOW_MS); } /** * The mail that carries U. After a recovery the same mail read as "run recover * --email", and people ran it again, and got another: so the re-arm says the * recovery is finished and there is nothing to do. */ export function enrollmentEmail(code, { afterRecovery = false } = {}) { if (afterRecovery) { return { subject: "Your LogicSRC vault email-recovery code was replaced — recovery complete, nothing to do", text: "Your LogicSRC personal vault was just recovered by email and has a new master password. " + "You are done: there is nothing to run now.\n\n" + "Using a recovery code spends it, so here is the replacement, for the next time you ever need it:\n\n" + ` ${code}\n\n` + "Keep this email and delete the older recovery-code emails: those codes no longer work.\n\n" + "Only if you lose your master password again, run `logicsrc passwd --email` (or `logicsrc vault recover --email`) " + "and type this code when it asks.\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" + "If you did not just recover your vault, someone else did: sign in, turn email recovery off (Settings, or " + "`logicsrc vault recovery disable`), change your password and secure this mailbox.", }; } 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), { afterRecovery: await followsRecovery(user.id, now) }); 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; }