mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +00:00
vault: opt-in paid email recovery for the personal vault ($5 lifetime)
A second way back into a logicsrc personal vault when the master password and
the offline recovery key are both gone, without the server holding anything
that alone (even with the DB and server env) opens the vault.
Client (packages/opencreds): random escrow key E encrypts the user key K
(AES-256-GCM, AAD "<ns>:vault:email-escrow:v1|<createdAt>"); E is split into
S (random, to the server) and U = E XOR S (emailed once as a checksummed
Crockford recovery code, never stored). `recover --email` checks the code's
check group first, asks the server for a one-time code, claims S, recombines
E, proves K against an item, sets a new password, issues a new offline
recovery key and re-enrolls with fresh shares (warns loudly if that fails).
New `recovery status|buy|enable|disable` commands; the CLI client lives in
packages/cli/src/vault-sync.ts.
Server (apps/pwa): /api/opencreds/recovery/{checkout,enroll,start,claim} +
status/disable. S is sealed under VAULT_ESCROW_KEY (versioned for rotation,
AAD binds the user). Enrollment is pending until the email with U is sent,
else rolled back. One-time codes: 8 digits, HMAC at rest, 15 min, 5 tries,
single use, 3 starts/hour; claims are audited and announced by email.
Purchase via CoinPay checkout (purpose vault_recovery); /api/coinpay/webhook
now verifies once and dispatches by purpose, auto_rotation unchanged.
Settings card with status and a Buy button. Migration 014 in both dialects.
Docs: security.md and crypto.md "Email recovery (opt-in, paid)" sections with
the honest trade-off; cli.md command reference.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4e4fedd35e
commit
8528634e09
21 changed files with 2368 additions and 7 deletions
|
|
@ -12,6 +12,7 @@ import { get } from "../db.mjs";
|
|||
import { requireAuth } from "../lib/session.mjs";
|
||||
import { api, requireMember } from "./credshare.mjs";
|
||||
import { autoRotationState, createCheckout, settleWebhook, verifySignature, AUTO_ROTATION_PRICE_USD, AUTO_ROTATION_DAYS } from "../lib/auto-rotation.mjs";
|
||||
import { isVaultRecoveryEvent, settleVaultRecoveryWebhook } from "../lib/vault-recovery.mjs";
|
||||
|
||||
export const autoRotationRouter = Router();
|
||||
|
||||
|
|
@ -49,10 +50,16 @@ autoRotationRouter.post("/api/credshare/teams/:slug/rotation/auto/checkout", api
|
|||
res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: AUTO_ROTATION_PRICE_USD, days: AUTO_ROTATION_DAYS });
|
||||
}));
|
||||
|
||||
// The one CoinPay webhook for this app: the signature is verified once, then the
|
||||
// event goes to its product by metadata.purpose. "vault_recovery" (email
|
||||
// recovery, lib/vault-recovery.mjs) settles there; everything else goes to the
|
||||
// automatic-rotation settler exactly as before.
|
||||
autoRotationRouter.post("/api/coinpay/webhook", async (req, res) => {
|
||||
if (!verifySignature(req.rawBody, req.get("x-coinpay-signature"))) return res.status(401).json({ error: "Invalid signature" });
|
||||
try {
|
||||
const result = await settleWebhook(req.body);
|
||||
const result = isVaultRecoveryEvent(req.body)
|
||||
? await settleVaultRecoveryWebhook(req.body)
|
||||
: await settleWebhook(req.body);
|
||||
console.log("coinpay webhook", JSON.stringify(result));
|
||||
res.json({ received: true, ...result });
|
||||
} catch (e) {
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { CLI_HINT } from "../lib/cli-hint.mjs";
|
|||
import { bulkUnlockCard, vaultPageBody } from "../lib/vault-page.mjs";
|
||||
import { keyFingerprint } from "../lib/keyfp.mjs";
|
||||
import { teamAudit } from "./credshare.mjs";
|
||||
import { vaultRecoveryCard } from "./vault-recovery.mjs";
|
||||
import { config } from "../config.mjs";
|
||||
import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile";
|
||||
import { profiles } from "../lib/profile.mjs";
|
||||
|
|
@ -313,6 +314,7 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
|
|||
if (recoveryToken) clearCeremony(res, "recovery");
|
||||
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
|
||||
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
|
||||
const recoveryCardHtml = await vaultRecoveryCard(req);
|
||||
const body = `${appBar(req)}
|
||||
<main class="wrap" style="max-width:720px;padding-top:30px">
|
||||
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
|
||||
|
|
@ -364,6 +366,7 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
|
|||
<button class="btn">Create key</button>
|
||||
</form>
|
||||
</div></div>
|
||||
${recoveryCardHtml}
|
||||
<div class="card" style="margin-top:20px"><div class="card-head"><span class="h">Emergency recovery</span></div>
|
||||
<div class="card-body">
|
||||
<p class="dim" style="font-size:.85rem;margin-top:0">Create a single-use recovery token for your password manager. The server stores only a hash; if you lose the plaintext, it cannot be recovered. Creating a new token revokes older ones.</p>
|
||||
|
|
|
|||
201
apps/pwa/src/routes/vault-recovery.mjs
Normal file
201
apps/pwa/src/routes/vault-recovery.mjs
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
// Vault email recovery (opt-in, $5 lifetime): lib/vault-recovery.mjs holds the logic.
|
||||
//
|
||||
// GET /api/opencreds/recovery status: {enrolled, enrolledAt, email (masked), purchased, priceUsd}
|
||||
// POST /api/opencreds/recovery/checkout a CoinPay checkout: {url, sessionId, priceUsd}
|
||||
// POST /api/opencreds/recovery/enroll {escrowBlob, escrowIv, serverShare, userShare, vaultCreatedAt}
|
||||
// POST /api/opencreds/recovery/start mail a one-time code
|
||||
// POST /api/opencreds/recovery/claim {code} -> {escrowBlob, escrowIv, serverShare, vaultCreatedAt}
|
||||
// DELETE /api/opencreds/recovery disable: delete the escrow material
|
||||
// POST /settings/vault-recovery/checkout the Settings page's Buy button (303 to CoinPay)
|
||||
// POST /settings/vault-recovery/disable the Settings page's switch-off
|
||||
//
|
||||
// Auth as /api/opencreds: a browser session or a person's `Bearer lsk_…`; a
|
||||
// machine key never reaches the personal vault. The webhook that settles a
|
||||
// purchase is the shared /api/coinpay/webhook (routes/auto-rotation.mjs), which
|
||||
// dispatches purpose "vault_recovery" here.
|
||||
import { Router } from "express";
|
||||
import { get } from "../db.mjs";
|
||||
import { config } from "../config.mjs";
|
||||
import { bearer, keyForBearer } from "../lib/apikey.mjs";
|
||||
import { esc } from "../lib/html.mjs";
|
||||
import { csrfInput, requireAuth } from "../lib/session.mjs";
|
||||
import {
|
||||
RecoveryError,
|
||||
claimRecovery,
|
||||
createRecoveryCheckout,
|
||||
disable,
|
||||
enroll,
|
||||
isEntitled,
|
||||
maskEmail,
|
||||
parseEnrollment,
|
||||
priceUsd,
|
||||
reconcileRecoveryReturn,
|
||||
recoveryConfigured,
|
||||
recoveryStatus,
|
||||
startRecovery,
|
||||
} from "../lib/vault-recovery.mjs";
|
||||
|
||||
export const vaultRecoveryRouter = Router();
|
||||
|
||||
const userRow = (userId) => get(`SELECT id, email FROM users WHERE id = ?`, [userId]);
|
||||
|
||||
function context(req) {
|
||||
return {
|
||||
ip: (req.ip || "").replace(/^::ffff:/, "") || null,
|
||||
userAgent: String(req.get("user-agent") || "").slice(0, 300) || null,
|
||||
};
|
||||
}
|
||||
|
||||
function api(handler) {
|
||||
return async (req, res) => {
|
||||
let userId = req.user?.id;
|
||||
if (!userId) {
|
||||
const found = await keyForBearer(bearer(req));
|
||||
if (!found) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
|
||||
if (found.key.kind === "machine") {
|
||||
return res.status(403).json({ error: "A machine API key cannot reach the personal vault.", code: "machine_key_forbidden" });
|
||||
}
|
||||
userId = found.user.id;
|
||||
}
|
||||
res.set("Cache-Control", "no-store");
|
||||
try {
|
||||
const user = await userRow(userId);
|
||||
if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
|
||||
await handler(req, res, user);
|
||||
} catch (e) {
|
||||
if (e instanceof RecoveryError) {
|
||||
if (e.extra?.retryAfter) res.set("Retry-After", String(e.extra.retryAfter));
|
||||
return res.status(e.status).json({ error: e.message, code: e.code, ...e.extra });
|
||||
}
|
||||
// Never the body: it can carry key shares.
|
||||
console.error("vault-recovery:", e?.message || e);
|
||||
res.status(500).json({ error: "Email recovery failed on the server." });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const notConfigured = (res) =>
|
||||
res.status(503).json({ error: "Email recovery is not configured on this server.", code: "not_configured" });
|
||||
|
||||
/** A checkout link to put in a 402, when CoinPay is reachable; else the Settings page. */
|
||||
async function checkoutHint(user) {
|
||||
try {
|
||||
return (await createRecoveryCheckout({ user })).url;
|
||||
} catch {
|
||||
return `${config.origin}/settings#vault-recovery`;
|
||||
}
|
||||
}
|
||||
|
||||
vaultRecoveryRouter.get("/api/opencreds/recovery", api(async (_req, res, user) => {
|
||||
res.json(await recoveryStatus(user));
|
||||
}));
|
||||
|
||||
vaultRecoveryRouter.post("/api/opencreds/recovery/checkout", api(async (req, res, user) => {
|
||||
if (!user.email) return res.status(422).json({ error: "Add an email to your account first: recovery codes are sent there." });
|
||||
if (await isEntitled(user.id)) return res.status(409).json({ error: "Email recovery is already purchased.", code: "already_purchased" });
|
||||
try {
|
||||
const session = await createRecoveryCheckout({ user });
|
||||
res.status(201).json({ sessionId: session.id, url: session.url, priceUsd: priceUsd() });
|
||||
} catch (e) {
|
||||
console.error("vault-recovery checkout failed:", e.message);
|
||||
res.status(502).json({ error: "Could not open the CoinPay checkout. Try again in a minute." });
|
||||
}
|
||||
}));
|
||||
|
||||
vaultRecoveryRouter.post("/api/opencreds/recovery/enroll", api(async (req, res, user) => {
|
||||
if (!recoveryConfigured()) return notConfigured(res);
|
||||
if (!user.email) return res.status(422).json({ error: "This account has no email address to send the recovery code to." });
|
||||
if (!(await isEntitled(user.id))) {
|
||||
return res.status(402).json({
|
||||
error: `Email recovery is a $${priceUsd()} lifetime add-on and is not purchased yet.`,
|
||||
code: "payment_required",
|
||||
priceUsd: priceUsd(),
|
||||
checkoutUrl: await checkoutHint(user),
|
||||
});
|
||||
}
|
||||
const parsed = parseEnrollment(req.body);
|
||||
// Drop the request's copy of U as soon as it is parsed (a string cannot be zeroed; this is what is possible).
|
||||
if (req.body && typeof req.body === "object") delete req.body.userShare;
|
||||
if (parsed.error) return res.status(422).json({ error: parsed.error });
|
||||
const result = await enroll(user, parsed, context(req));
|
||||
if (!result.ok) {
|
||||
return res.status(502).json({ error: "Could not send the enrollment email, so nothing was enrolled. Try again.", code: "email_failed" });
|
||||
}
|
||||
res.status(201).json({ enrolled: true, email: maskEmail(user.email) });
|
||||
}));
|
||||
|
||||
vaultRecoveryRouter.post("/api/opencreds/recovery/start", api(async (req, res, user) => {
|
||||
if (!recoveryConfigured()) return notConfigured(res);
|
||||
res.json(await startRecovery(user, context(req)));
|
||||
}));
|
||||
|
||||
vaultRecoveryRouter.post("/api/opencreds/recovery/claim", api(async (req, res, user) => {
|
||||
if (!recoveryConfigured()) return notConfigured(res);
|
||||
res.json(await claimRecovery(user, req.body?.code, context(req)));
|
||||
}));
|
||||
|
||||
vaultRecoveryRouter.delete("/api/opencreds/recovery", api(async (req, res, user) => {
|
||||
res.json(await disable(user.id, context(req)));
|
||||
}));
|
||||
|
||||
// ---- the Settings page ----
|
||||
|
||||
vaultRecoveryRouter.post("/settings/vault-recovery/checkout", requireAuth, async (req, res) => {
|
||||
const back = "/settings";
|
||||
const user = await userRow(req.user.id);
|
||||
if (!user?.email) return res.redirect(`${back}?err=${encodeURIComponent("Add an email to your account first: recovery codes are sent there.")}`);
|
||||
if (await isEntitled(user.id)) return res.redirect(`${back}#vault-recovery`);
|
||||
try {
|
||||
const session = await createRecoveryCheckout({ user });
|
||||
res.redirect(303, session.url);
|
||||
} catch (e) {
|
||||
console.error("vault-recovery checkout failed:", e.message);
|
||||
res.redirect(`${back}?err=${encodeURIComponent("Could not open the CoinPay checkout. Try again in a minute.")}`);
|
||||
}
|
||||
});
|
||||
|
||||
vaultRecoveryRouter.post("/settings/vault-recovery/disable", requireAuth, async (req, res) => {
|
||||
await disable(req.user.id, context(req));
|
||||
res.redirect("/settings?vault_recovery=disabled#vault-recovery");
|
||||
});
|
||||
|
||||
/** The Settings card. Never throws: a database without the tables shows the card as unavailable. */
|
||||
export async function vaultRecoveryCard(req) {
|
||||
let status;
|
||||
try {
|
||||
if (req.query.vault_recovery === "paid" && req.query.session_id) {
|
||||
await reconcileRecoveryReturn(String(req.query.session_id), req.user).catch(() => null);
|
||||
}
|
||||
status = await recoveryStatus(req.user);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
const notice =
|
||||
req.query.vault_recovery === "paid"
|
||||
? status.purchased
|
||||
? `<div class="notice ok">Payment received. Turn email recovery on from the CLI: <code>logicsrc vault recovery enable</code>.</div>`
|
||||
: `<div class="notice ok">Thanks. CoinPay is confirming the payment; this page shows it as purchased once it lands.</div>`
|
||||
: req.query.vault_recovery === "cancelled"
|
||||
? `<div class="notice err">Checkout cancelled. Nothing was charged.</div>`
|
||||
: req.query.vault_recovery === "disabled"
|
||||
? `<div class="notice ok">Email recovery is off. The server deleted its share; the emailed code is useless now.</div>`
|
||||
: "";
|
||||
const pill = (on, yes, no) => `<span class="pill ${on ? "on" : ""}">${on ? yes : no}</span>`;
|
||||
const action = !status.purchased
|
||||
? `<form method="post" action="/settings/vault-recovery/checkout" style="margin-top:12px">${csrfInput(req)}<button class="btn acid">Buy email recovery ($${esc(String(status.priceUsd))}, lifetime)</button></form>`
|
||||
: status.enrolled
|
||||
? `<form method="post" action="/settings/vault-recovery/disable" style="margin-top:12px">${csrfInput(req)}<button class="btn danger">Turn email recovery off</button></form>`
|
||||
: `<p class="dim" style="font-size:.85rem">Turn it on from the CLI (it needs your unlocked vault): <code>logicsrc vault recovery enable</code></p>`;
|
||||
return `
|
||||
<div class="card" id="vault-recovery" style="margin-top:20px"><div class="card-head"><span class="h">Vault email recovery — $${esc(String(status.priceUsd))} lifetime</span></div>
|
||||
<div class="card-body">
|
||||
${notice}
|
||||
<p class="dim" style="font-size:.85rem;margin-top:0">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, <code>logicsrc vault recover --email</code> 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 <b>and</b> a compromised LogicSRC server could, which is why it is opt-in. Without it, your vault stays zero-knowledge.</p>
|
||||
<div class="mono" style="font-size:.8rem;display:flex;gap:8px;flex-wrap:wrap;align-items:center">
|
||||
${pill(status.purchased, "purchased", "not purchased")}
|
||||
${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")}
|
||||
${status.email ? `<span class="faint">codes go to ${esc(status.email)}</span>` : ""}
|
||||
</div>
|
||||
${status.configured ? action : `<p class="faint mono" style="font-size:.78rem">Not available on this server yet.</p>`}
|
||||
</div></div>`;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue