// 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 ? `
logicsrc vault recovery enable.Turn it on from the CLI (it needs your unlocked vault): logicsrc vault recovery enable
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.
Not available on this server yet.
`}