From 6ff3089088f508c94832d712f0848a5dfc892cd8 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Wed, 2 Dec 2026 22:17:56 -0800 Subject: [PATCH] feat(recovery): assisted recovery, no old email: one-time code + passkey or CoinPay (CLI 0.18.0) (#305) Email recovery needs the recovery code from the enrollment email. People who delete their mail lose it, and with it the only way back in. `logicsrc vault recovery enable --assisted` (opt-in) replaces that code with a fresh sign-in: recovery asks for the one-time code emailed at that moment and a confirmation in the browser with a passkey of the account or its connected CoinPay identity (bound by subject, never by email, never creating an account, no session made). - Server: U is kept sealed under VAULT_ESCROW_KEY in vault_recovery_assisted (migration 015) only for accounts that ask. A step-up (vault_recovery_stepups) is single use, lives ten minutes, names no account and is approved only by a proof belonging to the account being recovered. The second proof is checked before the one-time code, so a missing confirmation never spends it. A claim without a confirmed step-up never returns U. disable and a plain re-enroll delete the stored U. - CLI: `passwd --email` and `vault recover --email` print the link, wait for the confirmation, then ask for the one-time code. The re-arm keeps the mode. - This mode is custodial: the server holds everything that opens the vault. docs/opencreds/security.md says so; accounts that do not opt in keep the split-key scheme unchanged. Co-authored-by: Claude Fable 5.2 --- apps/pwa/public/recover-confirm.js | 39 +++++ apps/pwa/src/lib/vault-recovery.mjs | 155 +++++++++++++++++- .../015_vault_assisted_recovery.sql | 22 +++ .../015_vault_assisted_recovery.sql | 25 +++ apps/pwa/src/routes/coinpay.mjs | 23 ++- apps/pwa/src/routes/vault-recovery.mjs | 120 +++++++++++++- apps/pwa/test/vault-recovery.test.mjs | 112 ++++++++++++- docs/opencreds/cli.md | 1 + docs/opencreds/security.md | 31 ++++ packages/cli/package.json | 2 +- packages/cli/src/passwd.test.ts | 110 +++++++++++++ packages/cli/src/passwd.ts | 50 +++--- packages/cli/src/vault-sync.ts | 14 +- packages/opencreds/src/commands.ts | 39 ++++- packages/opencreds/src/email-recovery.ts | 116 +++++++++++-- packages/opencreds/src/index.ts | 2 + 16 files changed, 799 insertions(+), 62 deletions(-) create mode 100644 apps/pwa/public/recover-confirm.js create mode 100644 apps/pwa/src/migrations-pg/015_vault_assisted_recovery.sql create mode 100644 apps/pwa/src/migrations/015_vault_assisted_recovery.sql diff --git a/apps/pwa/public/recover-confirm.js b/apps/pwa/public/recover-confirm.js new file mode 100644 index 00000000..394a196b --- /dev/null +++ b/apps/pwa/public/recover-confirm.js @@ -0,0 +1,39 @@ +/* Vault recovery confirmation: prove it is you with a passkey of the account being + recovered. Uses the @simplewebauthn/browser UMD bundle (/vendor). */ +(function () { + var btn = document.getElementById("stepup-passkey"); + var msg = document.getElementById("stepup-msg"); + if (!btn) return; + var base = "/recover/confirm/" + encodeURIComponent(btn.getAttribute("data-stepup")); + + function csrf() { + var m = document.cookie.match(/(?:^|; )mc_csrf=([^;]+)/); + return m ? decodeURIComponent(m[1]) : ""; + } + function post(url, body) { + return fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-csrf-token": csrf() }, + body: JSON.stringify(body || {}), + }); + } + function say(t) { if (msg) msg.textContent = t; } + + btn.addEventListener("click", async function () { + btn.disabled = true; + say("Waiting for your passkey…"); + try { + var optsRes = await post(base + "/passkey/options"); + var opts = await optsRes.json(); + if (!optsRes.ok) throw new Error(opts.error || "Could not start."); + var asr = await SimpleWebAuthnBrowser.startAuthentication({ optionsJSON: opts }); + var r = await post(base + "/passkey/verify", asr); + var out = await r.json(); + if (!r.ok || !out.ok) throw new Error(out.error || "The passkey did not verify."); + location.reload(); + } catch (e) { + say(e && e.message ? e.message : "Could not confirm with a passkey."); + btn.disabled = false; + } + }); +})(); diff --git a/apps/pwa/src/lib/vault-recovery.mjs b/apps/pwa/src/lib/vault-recovery.mjs index 13587b77..7ee80cee 100644 --- a/apps/pwa/src/lib/vault-recovery.mjs +++ b/apps/pwa/src/lib/vault-recovery.mjs @@ -92,6 +92,108 @@ export function openServerShare(row, ring = escrowKeyring()) { return Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]); } +// --------------------------------------------------- assisted recovery --- +// Opt-in. The account asks the server to keep U as well, so recovery needs no +// old email: the emailed one-time code plus a fresh passkey or CoinPay sign-in +// (a step-up) releases both shares. Custodial by construction: the server holds +// everything that opens the vault, sealed under VAULT_ESCROW_KEY. Nothing here +// applies to an account that did not ask for it. + +export const STEPUP_TTL_MS = 10 * 60 * 1000; +export const STEPUP_METHODS = ["passkey", "coinpay"]; +const userShareAad = (userId) => Buffer.from(`logicsrc:vault-escrow:user-share:v1:${userId}`); + +export function sealUserShare(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(userShareAad(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 openUserShare(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.user_share_ct, "base64"); + const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(row.user_share_iv, "base64")); + decipher.setAAD(userShareAad(row.user_id)); + decipher.setAuthTag(data.subarray(data.length - 16)); + return Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]); +} + +const assistedRow = (enrollmentId) => get(`SELECT * FROM vault_recovery_assisted WHERE enrollment_id = ?`, [enrollmentId]); + +/** Which second proofs this account can give: a registered passkey, a connected CoinPay identity. */ +export async function stepupMethods(userId) { + const [passkey, user] = await Promise.all([ + get(`SELECT 1 AS ok FROM webauthn_credentials WHERE user_id = ? LIMIT 1`, [userId]).catch(() => null), + get(`SELECT coinpay_sub FROM users WHERE id = ?`, [userId]).catch(() => null), + ]); + return { passkey: Boolean(passkey), coinpay: Boolean(user?.coinpay_sub) }; +} + +/** Open a step-up: the CLI shows its link, a person approves it in a browser with a passkey or CoinPay. */ +export async function createStepup(user, ctx = {}, now = Date.now()) { + const enrollment = await activeEnrollment(user.id); + if (!enrollment) throw new RecoveryError(404, "not_enrolled", "Email recovery is not enabled for this account."); + if (!(await assistedRow(enrollment.id))) { + throw new RecoveryError(409, "not_assisted", "Assisted recovery is not on for this account. It needs the recovery code from the enrollment email."); + } + const methods = await stepupMethods(user.id); + if (!methods.passkey && !methods.coinpay) { + throw new RecoveryError(409, "no_stepup_method", "This account has no passkey and no connected CoinPay account to confirm with."); + } + const recent = await all(`SELECT id FROM vault_recovery_stepups WHERE user_id = ? AND created_at > ?`, [user.id, now - HOUR_MS]); + if (recent.length >= STARTS_PER_HOUR * 2) { + throw new RecoveryError(429, "rate_limited", "Too many recovery confirmations requested. Try again in an hour."); + } + const stepupId = crypto.randomBytes(24).toString("base64url"); + await run( + `INSERT INTO vault_recovery_stepups (id, user_id, status, created_at, expires_at) VALUES (?,?,?,?,?)`, + [stepupId, user.id, "pending", now, now + STEPUP_TTL_MS], + ); + await audit(user.id, "stepup_start", ctx, now); + return { id: stepupId, url: `${config.origin}/recover/confirm/${stepupId}`, expiresIn: Math.floor(STEPUP_TTL_MS / 1000), methods }; +} + +/** A live step-up by id, or null. Its id is the capability: it says which account, never who is asking. */ +export async function liveStepup(stepupId, now = Date.now()) { + if (typeof stepupId !== "string" || !/^[A-Za-z0-9_-]{20,64}$/.test(stepupId)) return null; + const row = await get(`SELECT * FROM vault_recovery_stepups WHERE id = ?`, [stepupId]); + return row && Number(row.expires_at) > now ? row : null; +} + +/** + * Approve a step-up. `provenUserId` is the account the passkey or the CoinPay + * subject belongs to, established by the caller from the proof itself: it must + * be the step-up's account, or nothing is approved. + */ +export async function approveStepup(stepupId, provenUserId, method, ctx = {}, now = Date.now()) { + if (!STEPUP_METHODS.includes(method)) throw new RecoveryError(400, "bad_method", "Unknown confirmation method."); + const row = await liveStepup(stepupId, now); + if (!row) throw new RecoveryError(410, "stepup_expired", "This confirmation link has expired. Start the recovery again."); + if (!provenUserId || provenUserId !== row.user_id) { + await audit(row.user_id, "stepup_refused", { ...ctx, detail: `${method}: another account` }, now).catch(() => {}); + throw new RecoveryError(403, "stepup_wrong_account", "That sign-in belongs to a different account than the vault being recovered."); + } + const done = await run( + `UPDATE vault_recovery_stepups SET status = 'approved', method = ?, approved_at = ? WHERE id = ? AND status = 'pending'`, + [method, now, stepupId], + ); + if (!affected(done) && row.status !== "approved") { + throw new RecoveryError(410, "stepup_expired", "This confirmation was already used. Start the recovery again."); + } + await audit(row.user_id, "stepup_approved", { ...ctx, detail: method }, now); + return { approved: true, method }; +} + +export async function stepupStatus(user, stepupId, now = Date.now()) { + const row = await liveStepup(stepupId, now); + if (!row || row.user_id !== user.id) return { status: "expired" }; + return { status: row.status, method: row.method || null }; +} + // -------------------------------------------------------- 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 @@ -257,9 +359,12 @@ 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)]); + const [row, purchased, methods] = await Promise.all([activeEnrollment(user.id), isEntitled(user.id), stepupMethods(user.id)]); + const assisted = row ? Boolean(await assistedRow(row.id).catch(() => null)) : false; return { enrolled: Boolean(row), + assisted, + stepupMethods: methods, enrolledAt: row ? new Date(Number(row.enrolled_at)).toISOString() : null, email: maskEmail(user.email), purchased, @@ -284,7 +389,7 @@ export function parseEnrollment(body) { 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 }; + return { escrowBlob: body.escrowBlob, escrowIv: body.escrowIv, serverShare, userShare, vaultCreatedAt: createdAt, assisted: body?.assisted === true }; } /** A recovery that finished in the last half hour: this enrollment is the automatic re-arm after it. */ @@ -342,9 +447,18 @@ export function enrollmentEmail(code, { afterRecovery = false } = {}) { * row is deleted and the prior enrollment, if any, is untouched. */ export async function enroll(user, parsed, ctx = {}, now = Date.now()) { + if (parsed.assisted) { + const methods = await stepupMethods(user.id); + if (!methods.passkey && !methods.coinpay) { + parsed.serverShare.fill(0); + parsed.userShare.fill(0); + throw new RecoveryError(409, "no_stepup_method", "Assisted recovery confirms with a passkey or a connected CoinPay account, and this account has neither. Add one in Settings first."); + } + } const sealed = sealServerShare(parsed.serverShare, user.id); parsed.serverShare.fill(0); const rowId = id(); + const sealedUser = parsed.assisted ? sealUserShare(parsed.userShare, user.id) : null; 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], @@ -368,9 +482,17 @@ export async function enroll(user, parsed, ctx = {}, now = Date.now()) { }, { 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] }, + // A new enrollment replaces any stored user share: the old one opens nothing now. + { sql: `DELETE FROM vault_recovery_assisted WHERE user_id = ?`, args: [user.id] }, + ...(sealedUser + ? [{ + sql: `INSERT INTO vault_recovery_assisted (enrollment_id, user_id, user_share_ct, user_share_iv, key_version, created_at) VALUES (?,?,?,?,?,?)`, + args: [rowId, user.id, sealedUser.ct, sealedUser.iv, sealedUser.version, now], + }] + : []), ]); - await audit(user.id, "enroll", ctx, now); - return { ok: true }; + await audit(user.id, "enroll", { ...ctx, detail: sealedUser ? "assisted" : null }, now); + return { ok: true, assisted: Boolean(sealedUser) }; } /** Turn it off: the escrow material is deleted, live codes die. */ @@ -380,6 +502,8 @@ export async function disable(userId, ctx = {}, now = Date.now()) { [now, userId], ); await run(`UPDATE vault_recovery_codes SET used_at = ? WHERE user_id = ? AND used_at IS NULL`, [now, userId]); + await run(`DELETE FROM vault_recovery_assisted WHERE user_id = ?`, [userId]); + await run(`UPDATE vault_recovery_stepups SET status = 'used', used_at = ? WHERE user_id = ? AND status <> 'used'`, [now, userId]); const disabled = affected(r) > 0; if (disabled) await audit(userId, "disable", ctx, now); return { disabled }; @@ -436,7 +560,16 @@ export async function startRecovery(user, ctx = {}, now = Date.now()) { } /** Spend a one-time code; on success release the escrow material with S decrypted. */ -export async function claimRecovery(user, code, ctx = {}, now = Date.now()) { +export async function claimRecovery(user, code, ctx = {}, now = Date.now(), stepupId = null) { + // Assisted recovery: the second proof is checked BEFORE the one-time code is + // looked at, so a missing or stale confirmation never spends the code. + let stepup = null; + if (stepupId) { + stepup = await liveStepup(stepupId, now); + if (!stepup || stepup.user_id !== user.id || stepup.status !== "approved") { + throw new RecoveryError(403, "stepup_required", "Confirm the recovery in your browser first (passkey or CoinPay), then enter the one-time code."); + } + } 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) { @@ -473,7 +606,17 @@ export async function claimRecovery(user, code, ctx = {}, now = Date.now()) { vaultCreatedAt: enrollment.vault_created_at, }; share.fill(0); - await audit(user.id, "claim", ctx, now); + if (stepup) { + const stored = await assistedRow(enrollment.id); + if (!stored) throw new RecoveryError(409, "not_assisted", "Assisted recovery is not on for this account."); + // Single use, like the code: only the update that flips the status wins. + const used = await run(`UPDATE vault_recovery_stepups SET status = 'used', used_at = ? WHERE id = ? AND status = 'approved'`, [now, stepup.id]); + if (!affected(used)) throw new RecoveryError(410, "stepup_expired", "That confirmation was already used. Start the recovery again."); + const userShare = openUserShare(stored); + material.userShare = userShare.toString("base64"); + userShare.fill(0); + } + await audit(user.id, "claim", { ...ctx, detail: stepup ? `assisted:${stepup.method}` : null }, now); await sendMail( user.email, "Your LogicSRC vault email recovery was used", diff --git a/apps/pwa/src/migrations-pg/015_vault_assisted_recovery.sql b/apps/pwa/src/migrations-pg/015_vault_assisted_recovery.sql new file mode 100644 index 00000000..da5fe741 --- /dev/null +++ b/apps/pwa/src/migrations-pg/015_vault_assisted_recovery.sql @@ -0,0 +1,22 @@ +-- Postgres copy of migrations/015_vault_assisted_recovery.sql (INTEGER -> bigint). +-- No inline comments: the pg shim joins lines. Additive only. +CREATE TABLE IF NOT EXISTS vault_recovery_assisted ( + enrollment_id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + user_share_ct TEXT NOT NULL, + user_share_iv TEXT NOT NULL, + key_version bigint NOT NULL, + created_at bigint NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_assisted_user ON vault_recovery_assisted(user_id); +CREATE TABLE IF NOT EXISTS vault_recovery_stepups ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + method TEXT, + created_at bigint NOT NULL, + expires_at bigint NOT NULL, + approved_at bigint, + used_at bigint +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_stepups_user ON vault_recovery_stepups(user_id, created_at); diff --git a/apps/pwa/src/migrations/015_vault_assisted_recovery.sql b/apps/pwa/src/migrations/015_vault_assisted_recovery.sql new file mode 100644 index 00000000..b8684f2a --- /dev/null +++ b/apps/pwa/src/migrations/015_vault_assisted_recovery.sql @@ -0,0 +1,25 @@ +-- Assisted vault recovery (opt-in on top of email recovery): the account holder asks the +-- server to keep the user share U as well, sealed under VAULT_ESCROW_KEY, and to release it +-- only after the emailed one-time code AND a fresh passkey or CoinPay sign-in (a step-up). +-- This is custodial: with U and S the server can open the vault. Accounts that do not opt in +-- have no row here and keep the split-key scheme of 014. Additive only. +CREATE TABLE IF NOT EXISTS vault_recovery_assisted ( + enrollment_id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + user_share_ct TEXT NOT NULL, + user_share_iv TEXT NOT NULL, + key_version INTEGER NOT NULL, + created_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_assisted_user ON vault_recovery_assisted(user_id); +CREATE TABLE IF NOT EXISTS vault_recovery_stepups ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + method TEXT, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + approved_at INTEGER, + used_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_vault_recovery_stepups_user ON vault_recovery_stepups(user_id, created_at); diff --git a/apps/pwa/src/routes/coinpay.mjs b/apps/pwa/src/routes/coinpay.mjs index d5d325a0..94dc4462 100644 --- a/apps/pwa/src/routes/coinpay.mjs +++ b/apps/pwa/src/routes/coinpay.mjs @@ -7,6 +7,7 @@ import { token } from "../lib/crypto.mjs"; import { createSession, setCeremony, getCeremony, clearCeremony, takeNext } from "../lib/session.mjs"; import { userByCoinpay, createUserForCoinpay } from "../lib/users.mjs"; import { profiles } from "../lib/profile.mjs"; +import { RecoveryError, approveStepup } from "../lib/vault-recovery.mjs"; import { saveOpenProfileContact } from "@profullstack/profile"; export const coinpayRouter = Router(); @@ -18,7 +19,10 @@ coinpayRouter.get("/auth/coinpay/start", (req, res) => { const state = token(16); const verifier = b64url(crypto.randomBytes(32)); const challenge = b64url(crypto.createHash("sha256").update(verifier).digest()); - setCeremony(res, "cp", { state, verifier }, 1000 * 60 * 10); + // A vault-recovery confirmation rides the same round trip (the redirect URI + // registered with CoinPay is this router's callback); it signs nobody in. + const stepup = typeof req.query.stepup === "string" && /^[A-Za-z0-9_-]{20,64}$/.test(req.query.stepup) ? req.query.stepup : null; + setCeremony(res, "cp", { state, verifier, ...(stepup ? { stepup } : {}) }, 1000 * 60 * 10); const u = new URL(config.coinpay.oauth.authorizeUrl); u.searchParams.set("response_type", "code"); @@ -34,8 +38,10 @@ coinpayRouter.get("/auth/coinpay/start", (req, res) => { coinpayRouter.get("/auth/coinpay/callback", async (req, res) => { const ceremony = getCeremony(req, "cp"); clearCeremony(res, "cp"); + const stepup = ceremony?.stepup || null; + const back = (err) => (stepup ? `/recover/confirm/${encodeURIComponent(stepup)}${err ? `?err=${encodeURIComponent(err)}` : ""}` : null); if (!ceremony || req.query.state !== ceremony.state) return res.redirect("/?err=coinpay-state"); - if (!req.query.code) return res.redirect("/?err=coinpay-denied"); + if (!req.query.code) return res.redirect(back("CoinPay sign-in was cancelled.") || "/?err=coinpay-denied"); try { const tokenRes = await fetch(config.coinpay.oauth.tokenUrl, { @@ -60,6 +66,17 @@ coinpayRouter.get("/auth/coinpay/callback", async (req, res) => { const sub = String(info.sub || info.id || info.user_id || ""); if (!sub) throw new Error("no subject in userinfo"); + if (stepup) { + // Confirming a vault recovery: bound by the CoinPay subject only (never by + // email, never creating an account), and no session is made. + const owner = await userByCoinpay(sub); + try { + await approveStepup(stepup, owner?.id || null, "coinpay", { ip: (req.ip || "").replace(/^::ffff:/, "") || null, userAgent: String(req.get("user-agent") || "").slice(0, 300) || null }); + return res.redirect(back("")); + } catch (e) { + return res.redirect(back(e instanceof RecoveryError ? e.message : "Could not confirm with CoinPay.")); + } + } let user = await userByCoinpay(sub); if (!user) user = await createUserForCoinpay(sub, info.name || info.username); if (typeof info.openprofile_url === "string") { @@ -73,6 +90,6 @@ coinpayRouter.get("/auth/coinpay/callback", async (req, res) => { res.redirect(takeNext(req, res) || "/"); } catch (e) { console.error("coinpay login failed:", e.message); - res.redirect("/?err=coinpay-failed"); + res.redirect(back("CoinPay sign-in failed. Try again.") || "/?err=coinpay-failed"); } }); diff --git a/apps/pwa/src/routes/vault-recovery.mjs b/apps/pwa/src/routes/vault-recovery.mjs index 97db9e87..8557c50e 100644 --- a/apps/pwa/src/routes/vault-recovery.mjs +++ b/apps/pwa/src/routes/vault-recovery.mjs @@ -4,7 +4,11 @@ // 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} +// POST /api/opencreds/recovery/claim {code, stepup?} -> {escrowBlob, escrowIv, serverShare, vaultCreatedAt, userShare?} +// POST /api/opencreds/recovery/stepup assisted recovery: open a confirmation {id, url, expiresIn, methods} +// GET /api/opencreds/recovery/stepup/:id its status: pending | approved | used | expired +// GET /recover/confirm/:id the page a person opens to confirm with a passkey or CoinPay +// POST /recover/confirm/:id/passkey/* the passkey assertion for that page // 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 @@ -14,15 +18,21 @@ // 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 { generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server"; +import { all, get, run } 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 { esc, page } from "../lib/html.mjs"; +import { clearCeremony, csrfInput, getCeremony, requireAuth, setCeremony } from "../lib/session.mjs"; import { RecoveryError, + approveStepup, claimRecovery, createRecoveryCheckout, + createStepup, + liveStepup, + stepupMethods, + stepupStatus, disable, enroll, isEntitled, @@ -121,7 +131,7 @@ vaultRecoveryRouter.post("/api/opencreds/recovery/enroll", api(async (req, res, 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) }); + res.status(201).json({ enrolled: true, email: maskEmail(user.email), ...(result.assisted ? { assisted: true } : {}) }); })); vaultRecoveryRouter.post("/api/opencreds/recovery/start", api(async (req, res, user) => { @@ -131,9 +141,104 @@ vaultRecoveryRouter.post("/api/opencreds/recovery/start", api(async (req, res, u 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))); + res.json(await claimRecovery(user, req.body?.code, context(req), Date.now(), req.body?.stepup || null)); })); +vaultRecoveryRouter.post("/api/opencreds/recovery/stepup", api(async (req, res, user) => { + if (!recoveryConfigured()) return notConfigured(res); + res.status(201).json(await createStepup(user, context(req))); +})); + +vaultRecoveryRouter.get("/api/opencreds/recovery/stepup/:id", api(async (req, res, user) => { + res.json(await stepupStatus(user, String(req.params.id))); +})); + +// ---- the confirmation page (no session needed: the passkey or CoinPay proof is the sign-in) ---- + +const confirmPage = (title, inner, head = "") => + page({ title: `LogicSRC ▸ ${title}`, head, body: `
${esc(title)}
${inner}
` }); + +vaultRecoveryRouter.get("/recover/confirm/:id", async (req, res) => { + res.set("Cache-Control", "no-store"); + const stepup = await liveStepup(String(req.params.id)); + if (!stepup) { + return res.status(410).send(confirmPage("Vault recovery", `

This confirmation link has expired or was already used. Run the recovery again in your terminal to get a new one.

`)); + } + if (stepup.status !== "pending") { + return res.send(confirmPage("Vault recovery confirmed", `
Confirmed. Go back to your terminal and enter the one-time code we emailed you.
`)); + } + const methods = await stepupMethods(stepup.user_id); + const err = typeof req.query.err === "string" ? `
${esc(req.query.err)}
` : ""; + const id = esc(stepup.id); + res.send(confirmPage( + "Confirm vault recovery", + `${err}

Someone, hopefully you, is recovering a LogicSRC personal vault from a terminal. Confirm it is you. If you did not start this, close this page: nothing happens without your confirmation.

+
+ ${methods.passkey ? `` : ""} + ${methods.coinpay && config.coinpayLoginEnabled ? `Confirm with CoinPay` : ""} +
+

`, + ``, + )); +}); + +vaultRecoveryRouter.post("/recover/confirm/:id/passkey/options", async (req, res) => { + const stepup = await liveStepup(String(req.params.id)); + if (!stepup || stepup.status !== "pending") return res.status(410).json({ error: "This confirmation link has expired. Start the recovery again." }); + const creds = await all(`SELECT id, transports FROM webauthn_credentials WHERE user_id = ?`, [stepup.user_id]); + if (!creds.length) return res.status(409).json({ error: "This account has no passkey." }); + const options = await generateAuthenticationOptions({ + rpID: config.rpID, + allowCredentials: creds.map((c) => ({ id: c.id, transports: JSON.parse(c.transports || "[]") })), + userVerification: "required", + }); + setCeremony(res, "su", { challenge: options.challenge, stepup: stepup.id }); + res.json(options); +}); + +vaultRecoveryRouter.post("/recover/confirm/:id/passkey/verify", async (req, res) => { + const ceremony = getCeremony(req, "su"); + clearCeremony(res, "su"); + if (!ceremony || ceremony.stepup !== String(req.params.id)) return res.status(400).json({ error: "Confirmation expired. Try again." }); + const cred = await get(`SELECT * FROM webauthn_credentials WHERE id = ?`, [req.body?.id]); + if (!cred) return res.status(400).json({ error: "Unknown passkey." }); + let verification; + try { + verification = await verifyAuthenticationResponse({ + response: req.body, + expectedChallenge: ceremony.challenge, + expectedOrigin: config.origin, + expectedRPID: config.rpID, + requireUserVerification: true, + credential: { + id: cred.id, + publicKey: Buffer.from(cred.public_key, "base64url"), + counter: Number(cred.counter), + transports: JSON.parse(cred.transports || "[]"), + }, + }); + } catch (e) { + return res.status(400).json({ error: String(e.message || e) }); + } + if (!verification.verified) return res.status(400).json({ error: "The passkey did not verify." }); + await run(`UPDATE webauthn_credentials SET counter = ? WHERE id = ?`, [verification.authenticationInfo.newCounter, cred.id]); + try { + // The account the passkey belongs to must be the account being recovered. + await approveStepup(ceremony.stepup, cred.user_id, "passkey", context(req)); + } catch (e) { + return res.status(e instanceof RecoveryError ? e.status : 500).json({ error: e instanceof RecoveryError ? e.message : "Could not confirm." }); + } + res.json({ ok: true }); +}); + +// CoinPay: the shared OAuth callback (routes/coinpay.mjs) finishes this, because the +// redirect URI registered with CoinPay is that one. It signs nobody in. +vaultRecoveryRouter.get("/recover/confirm/:id/coinpay", async (req, res) => { + const stepup = await liveStepup(String(req.params.id)); + if (!stepup || stepup.status !== "pending") return res.redirect(`/recover/confirm/${encodeURIComponent(String(req.params.id))}`); + res.redirect(`/auth/coinpay/start?stepup=${encodeURIComponent(stepup.id)}`); +}); + vaultRecoveryRouter.delete("/api/opencreds/recovery", api(async (req, res, user) => { res.json(await disable(user.id, context(req))); })); @@ -196,6 +301,9 @@ export async function vaultRecoveryCard(req) { ${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")} ${status.email ? `codes go to ${esc(status.email)}` : ""} +

${status.assisted + ? `Assisted recovery is on. No old email is needed: recovery asks for the emailed one-time code and a passkey or CoinPay sign-in. To make that possible the server keeps both halves of your recovery key, sealed, so it is able to open your vault. Turn it off with logicsrc vault recovery enable (without --assisted).` + : `Delete your email? logicsrc vault recovery enable --assisted makes recovery ask for a passkey or CoinPay sign-in instead of the code in the enrollment email. The trade: the server then holds everything needed to open your vault.`}

${status.configured ? action : `

Not available on this server yet.

`} `; } diff --git a/apps/pwa/test/vault-recovery.test.mjs b/apps/pwa/test/vault-recovery.test.mjs index a4a344f4..5e693619 100644 --- a/apps/pwa/test/vault-recovery.test.mjs +++ b/apps/pwa/test/vault-recovery.test.mjs @@ -43,7 +43,7 @@ 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"]) { +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", "015_vault_assisted_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); } @@ -144,7 +144,7 @@ test("enroll without the purchase: 402 with a checkout link, and nothing stored" 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 }); + assert.deepEqual({ ...status.body, enrolledAt: null }, { enrolled: false, assisted: false, stepupMethods: { passkey: false, coinpay: 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 () => { @@ -380,3 +380,111 @@ test("an enroll right after a claim sends the finished wording; a later one send assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload())).status, 201); assert.equal(mail.at(-1).subject, "Your LogicSRC vault email-recovery code — keep this email"); }); + +// ---- assisted recovery (opt-in): no old email, a passkey or CoinPay step-up instead ---- + +async function assistedUser(uid, { coinpay = true } = {}) { + await run(`INSERT INTO users (id, email, coinpay_sub, created_at) VALUES (?,?,?,?)`, [uid, `${uid}@example.com`, coinpay ? `sub_${uid}` : null, Date.now()]).catch(() => {}); + await vr.settleVaultRecovery({ checkoutSessionId: `cs_${uid}`, paymentId: null, userId: uid, amountUsd: 5, method: "comp" }); + return get(`SELECT id, email FROM users WHERE id = ?`, [uid]); +} + +test("assisted: a plain enrollment stores no user share, and cannot be claimed with a step-up", async () => { + const user = await assistedUser("u_as1"); + const payload = await enrollPayload(); + assert.equal((await vr.enroll(user, vr.parseEnrollment(payload))).assisted, false); + assert.equal((await all(`SELECT 1 FROM vault_recovery_assisted WHERE user_id = ?`, [user.id])).length, 0); + assert.equal((await vr.recoveryStatus(user)).assisted, false); + await assert.rejects(vr.createStepup(user), (e) => e.code === "not_assisted"); +}); + +test("assisted: needs a passkey or a connected CoinPay account before it can be turned on", async () => { + const user = await assistedUser("u_as2", { coinpay: false }); + await assert.rejects(vr.enroll(user, vr.parseEnrollment({ ...(await enrollPayload()), assisted: true })), (e) => e.code === "no_stepup_method"); + assert.equal((await all(`SELECT 1 FROM vault_recovery_enrollments WHERE user_id = ?`, [user.id])).length, 0); +}); + +test("assisted: one-time code + an approved step-up release both shares, once; the code alone releases only S", async () => { + const user = await assistedUser("u_as3"); + const payload = await enrollPayload(); + const r = await vr.enroll(user, vr.parseEnrollment({ ...payload, assisted: true })); + assert.equal(r.assisted, true); + assert.equal((await vr.recoveryStatus(user)).assisted, true); + // U is at rest only sealed: no table holds it in the clear. + const row = await get(`SELECT * FROM vault_recovery_assisted WHERE user_id = ?`, [user.id]); + assert.ok(row.user_share_ct && !row.user_share_ct.includes(payload.userShare)); + + const stepup = await vr.createStepup(user); + assert.match(stepup.url, /\/recover\/confirm\/[A-Za-z0-9_-]{20,}$/); + assert.deepEqual(await vr.stepupStatus(user, stepup.id), { status: "pending", method: null }); + + // Not approved yet: refused, and the one-time code is NOT spent by the refusal. + await vr.startRecovery(user); + const otp = /One-time code: (\d{8})/.exec(mail.at(-1).text)[1]; + await assert.rejects(vr.claimRecovery(user, otp, {}, Date.now(), stepup.id), (e) => e.code === "stepup_required"); + + // A proof for some other account approves nothing. + await assert.rejects(vr.approveStepup(stepup.id, "u_a", "coinpay"), (e) => e.code === "stepup_wrong_account"); + await assert.rejects(vr.approveStepup(stepup.id, null, "passkey"), (e) => e.code === "stepup_wrong_account"); + assert.equal((await vr.stepupStatus(user, stepup.id)).status, "pending"); + + await vr.approveStepup(stepup.id, user.id, "coinpay"); + assert.deepEqual(await vr.stepupStatus(user, stepup.id), { status: "approved", method: "coinpay" }); + const material = await vr.claimRecovery(user, otp, {}, Date.now(), stepup.id); + assert.equal(material.userShare, payload.userShare); + assert.equal(material.serverShare, payload.serverShare); + + // Single use: the step-up and the code are both spent. + assert.equal((await vr.stepupStatus(user, stepup.id)).status, "used"); + await assert.rejects(vr.claimRecovery(user, otp, {}, Date.now(), stepup.id), (e) => e.code === "stepup_required"); + + // Without a step-up the server never hands out U, assisted or not. + await vr.startRecovery(user); + const otp2 = /One-time code: (\d{8})/.exec(mail.at(-1).text)[1]; + const plain = await vr.claimRecovery(user, otp2); + assert.equal(plain.userShare, undefined); +}); + +test("assisted: a step-up expires, another account cannot read its status, and disable deletes the stored share", async () => { + const user = await assistedUser("u_as4"); + await vr.enroll(user, vr.parseEnrollment({ ...(await enrollPayload()), assisted: true })); + const stepup = await vr.createStepup(user); + assert.deepEqual(await vr.stepupStatus({ id: "u_a" }, stepup.id), { status: "expired" }); + const later = Date.now() + vr.STEPUP_TTL_MS + 1000; + await assert.rejects(vr.approveStepup(stepup.id, user.id, "passkey", {}, later), (e) => e.code === "stepup_expired"); + + await vr.disable(user.id); + assert.equal((await all(`SELECT 1 FROM vault_recovery_assisted WHERE user_id = ?`, [user.id])).length, 0); +}); + +test("assisted: the routes exist, and the confirmation page for an unknown link is gone, not an error", async () => { + const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/stepup"); + assert.equal(r.status, 409); + assert.equal(r.body.code, "not_assisted"); + const s = await call(keys.u_a, "GET", `/api/opencreds/recovery/stepup/${"x".repeat(32)}`); + assert.deepEqual(s.body, { status: "expired" }); +}); + +test("assisted: the confirmation page shows for a live link, is gone for a dead one, and a passkey of nobody approves nothing", async () => { + const user = await assistedUser("u_as5"); + await vr.enroll(user, vr.parseEnrollment({ ...(await enrollPayload()), assisted: true })); + const stepup = await vr.createStepup(user); + + const live = await realFetch(`${base}/recover/confirm/${stepup.id}`); + assert.equal(live.status, 200); + const html = await live.text(); + assert.match(html, /Confirm vault recovery/); + assert.doesNotMatch(html, /u_as5@example\.com/, "the page names no account"); + + const dead = await realFetch(`${base}/recover/confirm/${"z".repeat(32)}`); + assert.equal(dead.status, 410); + + // This account has no passkey: there is nothing to assert with. + const options = await realFetch(`${base}/recover/confirm/${stepup.id}/passkey/options`, { method: "POST" }); + assert.equal(options.status, 409); + assert.equal((await vr.stepupStatus(user, stepup.id)).status, "pending"); + + // Once approved, the page says to go back to the terminal. + await vr.approveStepup(stepup.id, user.id, "coinpay"); + assert.match(await (await realFetch(`${base}/recover/confirm/${stepup.id}`)).text(), /Go back to your terminal/); +}); diff --git a/docs/opencreds/cli.md b/docs/opencreds/cli.md index d437f202..96bb8b12 100644 --- a/docs/opencreds/cli.md +++ b/docs/opencreds/cli.md @@ -58,6 +58,7 @@ why it is instant on a vault of any size. 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 enable --assisted # no old email needed: one-time code + passkey or CoinPay sign-in (custodial, see security.md) 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 logicsrc passwd --email # the same two codes, then ONE new password for the vault and the SSH keyring diff --git a/docs/opencreds/security.md b/docs/opencreds/security.md index 306c25cd..90600d3f 100644 --- a/docs/opencreds/security.md +++ b/docs/opencreds/security.md @@ -163,6 +163,37 @@ What this does and does not hold against, stated plainly: 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. +### Assisted recovery (opt-in on top of email recovery) + +`logicsrc vault recovery enable --assisted` is for people who do not keep old +email. Recovery then asks for two things and no stored code: the one-time code +emailed at that moment, and a fresh sign-in in the browser with a passkey of +the account or its connected CoinPay identity (bound by the CoinPay subject, +never by email). + +**This mode is custodial, and that is the whole trade.** To make it work the +server keeps the user share U as well as S, each sealed under +`VAULT_ESCROW_KEY`. With both it can rebuild the escrow key and open the +vault. So for an account that turns this on: + +- the server operator, or anyone who takes the database **and** the escrow + key, can read the vault; +- "the server cannot read the vault" no longer holds for that account. + +It still holds for every account that did not opt in: there is no row for them +in `vault_recovery_assisted`, U is mailed once and never stored, and a claim +without a confirmed step-up never returns U. + +What an outside attacker needs against an assisted account: the account's API +token or session, the mailbox (for the one-time code), **and** the passkey or +the CoinPay account. The confirmation link is single use, lives ten minutes, +names no account, and is approved only by a proof that belongs to the account +being recovered. The second proof is checked before the one-time code, so a +missing confirmation never spends the code. + +Running `logicsrc vault recovery enable` without the flag goes back to the +split-key scheme and deletes the stored U; so does `recovery disable`. + ## Reporting Security issues in the specification or the reference implementation: diff --git a/packages/cli/package.json b/packages/cli/package.json index d1665dfa..41dc5bee 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@logicsrc/cli", - "version": "0.17.0", + "version": "0.18.0", "description": "LogicSRC CLI: every LogicSRC standard and tool as one command.", "type": "module", "main": "./dist/index.js", diff --git a/packages/cli/src/passwd.test.ts b/packages/cli/src/passwd.test.ts index 3bd91686..9f385c35 100644 --- a/packages/cli/src/passwd.test.ts +++ b/packages/cli/src/passwd.test.ts @@ -344,6 +344,116 @@ function fakeVaultAccount() { return { remote, meta: () => held?.meta, has: (id: string) => Boolean(rows.get(id)?.envelope) }; } +/** An account with assisted recovery: it keeps U too and releases it for a confirmed step-up. */ +function fakeAssistedRecovery() { + let enrollment: (EscrowMaterial & { userShare?: string; assisted: boolean }) | null = null; + let otp: { code: string; used: boolean } | null = null; + const stepups = new Map(); + const state = { enrolls: 0, polls: 0, approveAfterPolls: 2 }; + const client: EmailRecoveryClient = { + label: "fake.test", + async status() { + return { enrolled: Boolean(enrollment), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5, assisted: Boolean(enrollment?.assisted), stepupMethods: { passkey: true, coinpay: false } }; + }, + async checkout() { + return { url: "https://pay.test/1", priceUsd: 5 }; + }, + async enroll(p: EscrowEnrollment) { + state.enrolls++; + enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt, assisted: p.assisted === true, userShare: p.assisted ? p.userShare : undefined }; + otp = null; + return { enrolled: true, email: "m***@example.com", assisted: p.assisted === true }; + }, + async start() { + otp = { code: "12345678", used: false }; + return { sent: true, email: "m***@example.com" }; + }, + async claim(code: string, stepupId?: string) { + if (!stepupId || stepups.get(stepupId) !== "approved") throw new EmailRecoveryError("Confirm the recovery in your browser first", 403, "stepup_required"); + if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code"); + otp.used = true; + stepups.set(stepupId, "used"); + const { assisted: _a, ...material } = enrollment!; + return { ...material }; + }, + async stepup() { + stepups.set("su_1", "pending"); + return { id: "su_1", url: "https://fake.test/recover/confirm/su_1", expiresIn: 600 }; + }, + async stepupStatus(id: string) { + // The person confirms in the browser a moment later. + if (++state.polls >= state.approveAfterPolls && stepups.get(id) === "pending") stepups.set(id, "approved"); + return { status: stepups.get(id) ?? "expired" }; + }, + async disable() { + enrollment = null; + return { disabled: true }; + } + }; + return { client, state, assisted: () => Boolean(enrollment?.assisted) }; +} + +describe("logicsrc passwd --email with assisted recovery", () => { + it("asks for no enrollment-email code: a browser confirmation and the one-time code are enough", async () => { + await seed("lost", "also lost"); + const server = fakeAssistedRecovery(); + await enrollEmailRecovery(server.client, vault.readMeta()!, await unlockVault(vault.readMeta()!, "lost"), { assisted: true }); + const said: string[] = []; + + const r = await changeAllPasswords( + { noSync: true, email: true }, + { + vault, + keyring, + sshDir: join(dir, "nowhere"), + recovery: () => server.client, + sleep: async () => {}, + // Only the one-time code, then Enter twice for the lost keyring. No recovery code prompt. + ask: answers("12345678", "", ""), + askNew: async () => "one password", + say: (l) => said.push(l) + } + ); + expect(r).toMatchObject({ vault: "changed", keyring: "created", emailRearmed: true, assistedRecovery: true }); + await expect(unlockVault(vault.readMeta()!, "one password")).resolves.toBeInstanceOf(Uint8Array); + expect(said.join("\n")).toMatch(/https:\/\/fake\.test\/recover\/confirm\/su_1/); + expect(said.join("\n")).not.toMatch(/enrollment email|email-recovery code/); + // Re-armed the same way: still assisted. + expect(server.state.enrolls).toBe(2); + expect(server.assisted()).toBe(true); + }, 60_000); + + it("gives up cleanly, changing nothing, when the link is never confirmed", async () => { + await seed("lost", "also lost"); + const server = fakeAssistedRecovery(); + await enrollEmailRecovery(server.client, vault.readMeta()!, await unlockVault(vault.readMeta()!, "lost"), { assisted: true }); + server.state.approveAfterPolls = Number.POSITIVE_INFINITY; + const before = JSON.stringify(vault.readMeta()); + let polls = 0; + const realNow = Date.now; + await expect( + changeAllPasswords( + { noSync: true, email: true }, + { + vault, + keyring, + recovery: () => server.client, + // Each wait jumps the clock past the link's lifetime. + sleep: async () => { + if (++polls > 1) Date.now = () => realNow() + 11 * 60 * 1000; + }, + ask: answers(), + askNew: async () => "n", + say: () => {} + } + ).finally(() => { + Date.now = realNow; + }) + ).rejects.toThrow(/expired before it was confirmed/); + expect(JSON.stringify(vault.readMeta())).toBe(before); + }, 60_000); +}); + describe("logicsrc passwd across machines", () => { it("an email reset on a machine that is behind the account still wins everywhere", async () => { const account = fakeVaultAccount(); diff --git a/packages/cli/src/passwd.ts b/packages/cli/src/passwd.ts index 0220e1d6..8c28c2a2 100644 --- a/packages/cli/src/passwd.ts +++ b/packages/cli/src/passwd.ts @@ -10,10 +10,9 @@ import { encryptItem, enrollEmailRecovery, fromBase64, - parseRecoveryCode, + obtainUserKeyByEmail, promptNewSecret, promptSecret, - recoverUserKeyByEmail, resetRecoveryKey, rewrapUserKey, pullVault, @@ -113,6 +112,8 @@ export interface PasswdDeps { vaultRemote?: (store: VaultStore) => SyncRemote | undefined; /** Email recovery for the vault (`--email`). */ recovery?: (store: VaultStore) => EmailRecoveryClient | undefined; + /** Test seam for the wait while a browser confirmation is pending. */ + sleep?: (ms: number) => Promise; /** Where the keyring's key files live on disk, to refill a keyring that had to be reset. */ sshDir?: string; ask?: (label: string) => Promise; @@ -133,6 +134,8 @@ export interface PasswdResult { emailRearmed?: boolean; emailRearmedTo?: string; emailRearmError?: string; + /** The account uses assisted recovery (browser confirmation, no enrollment-email code). */ + assistedRecovery?: boolean; /** The keyring's key is now kept in the vault, so `passwd --email` can open it next time. */ keyringEscrowed: boolean; /** After a reset: keys put back from disk, and keys that were only in the old keyring. */ @@ -140,25 +143,26 @@ export interface PasswdResult { keysLost: string[]; } -/** Open the vault with the two emailed codes. Nothing is written here. */ +/** Open the vault through email recovery (assisted or with the emailed recovery code). Nothing is written here. */ async function openVaultByEmail( vault: VaultStore, meta: VaultMeta, client: EmailRecoveryClient, ask: (l: string) => Promise, - say: (line: string) => void -): Promise { - say('Email reset needs the recovery code from your newest "Your LogicSRC vault email-recovery code" email.'); - const userShare = await parseRecoveryCode(await ask("Recovery code from the enrollment email: ")); - 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 ask("One-time code from the email just sent: ")).replace(/\s+/g, ""); - const material = await client.claim(code); - return await recoverUserKeyByEmail({ meta, material, userShare, envelopes: vault.listEnvelopes() }); - } finally { - userShare.fill(0); - } + say: (line: string) => void, + sleep?: (ms: number) => Promise +): Promise<{ userKey: Uint8Array; assisted: boolean }> { + return obtainUserKeyByEmail({ + store: vault, + meta, + client, + say, + prompts: { + recoveryCode: () => ask("Recovery code from the enrollment email: "), + oneTimeCode: () => ask("One-time code from the email just sent: "), + sleep + } + }); } /** With `--email` the old keyring passphrase may be gone too: every prompt can be skipped, and skipping all of them means a reset. */ @@ -284,11 +288,14 @@ export async function changeAllPasswords( const vaultMeta = vault.readMeta(); let opened: { userKey: Uint8Array; password?: string } | undefined; let recoveryClient: EmailRecoveryClient | undefined; + let assistedRecovery = false; if (opts.email) { if (!vaultMeta) throw new Error("No personal vault on this machine. Run `logicsrc login` and `logicsrc vault sync` first, then this again."); recoveryClient = (deps.recovery ?? accountRecoveryFor)(vault); if (!recoveryClient) throw new Error("Email reset works through your account. Run `logicsrc login` first, then this again."); - opened = { userKey: await openVaultByEmail(vault, vaultMeta, recoveryClient, ask, say) }; + const viaEmail = await openVaultByEmail(vault, vaultMeta, recoveryClient, ask, say, deps.sleep); + opened = { userKey: viaEmail.userKey }; + assistedRecovery = viaEmail.assisted; } else if (vaultMeta) { opened = await openVault(vaultMeta, ask); } @@ -382,7 +389,9 @@ export async function changeAllPasswords( // Email recovery was spent by the claim: arm it again with fresh shares. if (opts.email && recoveryClient && currentVaultMeta && opened) { try { - const enrolled = await enrollEmailRecovery(recoveryClient, currentVaultMeta, opened.userKey); + // Re-armed the way it was: an account on assisted recovery stays on it. + const enrolled = await enrollEmailRecovery(recoveryClient, currentVaultMeta, opened.userKey, { assisted: assistedRecovery }); + result.assistedRecovery = assistedRecovery; result.emailRearmed = Boolean(enrolled.enrolled); result.emailRearmedTo = enrolled.email; } catch (e) { @@ -461,8 +470,11 @@ Each run stores the keyring's key as an item in your vault, so the next console.error(`Not on this machine's disk, so not in the new keyring: ${r.keysLost.join(", ")}. Add them where the files are: logicsrc keyring add `); } if (r.keyringEscrowed) console.error("The keyring's key is stored in your vault: next time `logicsrc passwd --email` opens both."); - if (r.emailRearmed) { + if (r.emailRearmed && r.assistedRecovery) { + console.error("Assisted recovery is armed again. You are done: next time you need the emailed one-time code and a passkey or CoinPay sign-in, nothing else."); + } else if (r.emailRearmed) { console.error(`Email recovery is armed again: a NEW recovery code was emailed to ${r.emailRearmedTo ?? "your account email"}. The code you just used no longer works. You are done: that email is only the replacement to keep.`); + console.error("Delete your email? Turn on assisted recovery so no old email is ever needed: logicsrc vault recovery enable --assisted"); } else if (r.emailRearmError) { console.error(`Email recovery is OFF now and could not be re-armed (${r.emailRearmError}). Run: logicsrc vault recovery enable`); } diff --git a/packages/cli/src/vault-sync.ts b/packages/cli/src/vault-sync.ts index adbc13b5..a37011d0 100644 --- a/packages/cli/src/vault-sync.ts +++ b/packages/cli/src/vault-sync.ts @@ -166,14 +166,22 @@ export function createRecoveryClient( }, async enroll(payload: EscrowEnrollment) { const body = await call("POST", "/enroll", payload); - return { enrolled: Boolean(body.enrolled), email: String(body.email ?? "") }; + return { enrolled: Boolean(body.enrolled), email: String(body.email ?? ""), assisted: body.assisted === true }; }, 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 claim(code: string, stepupId?: string) { + return (await call("POST", "/claim", stepupId ? { code, stepup: stepupId } : { code })) as unknown as EscrowMaterial; + }, + async stepup() { + const body = await call("POST", "/stepup"); + return { id: String(body.id), url: String(body.url), expiresIn: Number(body.expiresIn) || 600 }; + }, + async stepupStatus(id: string) { + const body = await call("GET", `/stepup/${encodeURIComponent(id)}`); + return { status: String(body.status), method: typeof body.method === "string" ? body.method : null }; }, async disable() { const body = await call("DELETE", ""); diff --git a/packages/opencreds/src/commands.ts b/packages/opencreds/src/commands.ts index cc403e03..9bbbf916 100644 --- a/packages/opencreds/src/commands.ts +++ b/packages/opencreds/src/commands.ts @@ -537,9 +537,6 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions 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({ @@ -615,6 +612,15 @@ vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`)) ` Enrolled ${status.enrolled ? `yes, since ${status.enrolledAt ?? "?"}` : `no${status.purchased ? ` (\`${cli} recovery enable\`)` : ""}`}\n`, ); if (status.email) process.stdout.write(` Email ${status.email}\n`); + if (status.enrolled) { + const m = status.stepupMethods; + const have = [m?.passkey ? "passkey" : "", m?.coinpay ? "CoinPay" : ""].filter(Boolean).join(" or "); + process.stdout.write( + status.assisted + ? ` Second proof a ${have || "passkey or CoinPay"} sign-in in the browser (assisted recovery: the server can open this vault)\n` + : ` Second proof the recovery code in the enrollment email${have ? ` (or switch to ${have}: \`${cli} recovery enable --assisted\`)` : ""}\n`, + ); + } }); }); @@ -637,7 +643,11 @@ vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`)) 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) { + .option( + "--assisted", + "no old email needed: recover with the emailed one-time code plus a passkey or CoinPay sign-in. The server then keeps both halves of the recovery key and is able to open this vault", + ) + .action(async function (this: Command, opts: { assisted?: boolean }) { await run(async () => { const store = storeFor(this); const client = recoveryClient(store); @@ -652,13 +662,30 @@ vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`)) ); } const userKey = await unlock(store); - let result: { enrolled: boolean; email: string }; + if (opts.assisted && status.stepupMethods && !status.stepupMethods.passkey && !status.stepupMethods.coinpay) { + fail( + "Assisted recovery confirms with a passkey or a connected CoinPay account, and this account has neither. " + + "Add a passkey or sign in with CoinPay on the account's Settings page, then run this again.", + EXIT.USAGE, + ); + } + let result: { enrolled: boolean; email: string; assisted?: boolean }; try { - result = await enrollEmailRecovery(client, meta, userKey); + result = await enrollEmailRecovery(client, meta, userKey, { assisted: Boolean(opts.assisted) }); } catch (err) { const e = err as EmailRecoveryError; fail(`${e.message}${e.checkoutUrl ? `\n\n ${e.checkoutUrl}\n` : ""}`, EXIT.USAGE); } + if (opts.assisted) { + process.stdout.write( + "Assisted recovery is on. To get back in you need two things: the one-time code we email at that moment, " + + "and a passkey or CoinPay sign-in in the browser. No old email is needed.\n" + + "The trade: the server now keeps both halves of your recovery key (sealed) and is able to open this vault. " + + `Go back to the stricter setup any time with \`${cli} recovery enable\`.\n` + + (status.enrolled ? "The previous recovery code no longer works.\n" : ""), + ); + return; + } 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" + diff --git a/packages/opencreds/src/email-recovery.ts b/packages/opencreds/src/email-recovery.ts index 89754bc3..83ba10d6 100644 --- a/packages/opencreds/src/email-recovery.ts +++ b/packages/opencreds/src/email-recovery.ts @@ -70,6 +70,12 @@ export interface EscrowEnrollment { serverShare: string; userShare: string; vaultCreatedAt: string; + /** + * Assisted recovery (opt-in): ask the server to keep U too, sealed, and to release it + * after the one-time code plus a passkey or CoinPay sign-in. Custodial: the server then + * holds everything that opens the vault. + */ + assisted?: boolean; } /** What the server releases on a successful claim. */ @@ -78,6 +84,8 @@ export interface EscrowMaterial { escrowIv: string; serverShare: string; vaultCreatedAt: string; + /** Only on an assisted claim (a confirmed step-up): U, base64. */ + userShare?: string; } export interface EmailRecoveryStatus { @@ -87,6 +95,18 @@ export interface EmailRecoveryStatus { email: string | null; purchased: boolean; priceUsd: number; + /** Assisted recovery is on: no enrollment-email code needed, a browser confirmation instead. */ + assisted?: boolean; + /** What the account can confirm with. */ + stepupMethods?: { passkey: boolean; coinpay: boolean }; +} + +/** A browser confirmation of an assisted recovery. */ +export interface RecoveryStepup { + id: string; + url: string; + /** Seconds until the link dies. */ + expiresIn: number; } /** The account's email-recovery endpoints. The logicsrc CLI provides one. */ @@ -97,7 +117,11 @@ export interface EmailRecoveryClient { /** 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; + /** With `stepupId` (assisted recovery) the material carries U as well. */ + claim(code: string, stepupId?: string): Promise; + /** Assisted recovery: open a confirmation and read its status. Absent on a client that cannot. */ + stepup?(): Promise; + stepupStatus?(id: string): Promise<{ status: string; method?: string | null }>; disable(): Promise<{ disabled: boolean }>; } @@ -195,8 +219,10 @@ export async function enrollEmailRecovery( client: EmailRecoveryClient, meta: VaultMeta, userKey: Uint8Array, -): Promise<{ enrolled: boolean; email: string }> { + opts: { assisted?: boolean } = {}, +): Promise<{ enrolled: boolean; email: string; assisted?: boolean }> { const prepared = await prepareEnrollment(meta, userKey); + if (opts.assisted) prepared.payload.assisted = true; try { return await client.enroll(prepared.payload); } finally { @@ -338,6 +364,73 @@ export interface EmailRecoveryPrompts { oneTimeCode(email: string | undefined): Promise; /** The new master password, already confirmed. */ newPassword(): Promise; + /** Test seam for the wait between confirmation checks. */ + sleep?(ms: number): Promise; +} + +/** + * The vault's user key through email recovery, by whichever second proof the + * account uses. Nothing on disk changes here. + * + * - Assisted recovery on: a link to confirm in a browser (passkey or CoinPay), + * then the emailed one-time code. No enrollment-email code is asked for. + * - Otherwise: the recovery code from the enrollment email (checked first, so a + * typo costs nothing), then the emailed one-time code. + */ +export async function obtainUserKeyByEmail(opts: { + store: VaultStore; + meta: VaultMeta; + client: EmailRecoveryClient; + prompts: Pick; + say?: (line: string) => void; +}): Promise<{ userKey: Uint8Array; assisted: boolean }> { + const { store, meta, client, prompts } = opts; + const say = opts.say ?? (() => {}); + const status = await client.status().catch(() => undefined); + + if (status?.assisted && client.stepup && client.stepupStatus) { + const stepup = await client.stepup(); + say("Confirm this recovery in a browser, with your passkey or your CoinPay account:"); + say(`\n ${stepup.url}\n`); + say(`Waiting for the confirmation (the link works for ${Math.max(1, Math.round(stepup.expiresIn / 60))} minutes)...`); + const sleep = prompts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + const deadline = Date.now() + stepup.expiresIn * 1000; + for (;;) { + const s = await client.stepupStatus(stepup.id); + if (s.status === "approved") break; + if (s.status !== "pending" || Date.now() > deadline) { + throw new EmailRecoveryError("The confirmation link expired before it was confirmed. Run this again.", undefined, "stepup_expired"); + } + await sleep(2000); + } + say("Confirmed."); + 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, stepup.id); + if (!material.userShare) { + throw new EmailRecoveryError("The account did not release the recovery key. Run this again.", undefined, "stepup_required"); + } + const userShare = fromBase64(material.userShare); + material.userShare = ""; + try { + return { userKey: await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() }), assisted: true }; + } finally { + wipe(userShare); + } + } + + say('This needs the recovery code from your newest "Your LogicSRC vault email-recovery code" email.'); + const userShare = await parseRecoveryCode(await prompts.recoveryCode()); + 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 { userKey: await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() }), assisted: false }; + } finally { + wipe(userShare); + } } export interface EmailRecoveryResult { @@ -346,6 +439,8 @@ export interface EmailRecoveryResult { /** The new offline recovery key, to print once. */ recoveryKey: string; reenrolled: boolean; + /** Assisted recovery was on, and stays on after the re-arm. */ + assisted?: boolean; reenrolledEmail?: string; reenrollError?: string; } @@ -370,18 +465,7 @@ export async function runEmailRecovery(opts: { 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 { userKey, assisted } = await obtainUserKeyByEmail({ store, meta, client, prompts, say }); const password = await prompts.newPassword(); if (!password) throw new EmailRecoveryError("A master password is required", undefined, "no_password"); @@ -389,9 +473,9 @@ export async function runEmailRecovery(opts: { const reset = await resetRecoveryKey(rewrapped, userKey); store.writeMeta(reset.meta); - const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false }; + const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false, assisted }; try { - const enrolled = await enrollEmailRecovery(client, reset.meta, userKey); + const enrolled = await enrollEmailRecovery(client, reset.meta, userKey, { assisted }); result.reenrolled = Boolean(enrolled.enrolled); result.reenrolledEmail = enrolled.email; } catch (err) { diff --git a/packages/opencreds/src/index.ts b/packages/opencreds/src/index.ts index d3bf4377..4a61d680 100644 --- a/packages/opencreds/src/index.ts +++ b/packages/opencreds/src/index.ts @@ -193,6 +193,7 @@ export { parseRecoveryCode, prepareEnrollment, recoverUserKeyByEmail, + obtainUserKeyByEmail, runEmailRecovery, sealEscrow, splitEscrowKey, @@ -201,6 +202,7 @@ export { type EmailRecoveryPrompts, type EmailRecoveryResult, type EmailRecoveryStatus, + type RecoveryStepup, type EscrowEnrollment, type EscrowMaterial, } from "./email-recovery.js";