Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
455 changes: 455 additions & 0 deletions apps/pwa/src/lib/vault-recovery.mjs

Large diffs are not rendered by default.

50 changes: 50 additions & 0 deletions apps/pwa/src/migrations-pg/014_vault_email_recovery.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
-- Postgres copy of migrations/014_vault_email_recovery.sql (INTEGER -> bigint, REAL -> double precision).
-- Vault email recovery (opt-in, $5 lifetime): escrowed blob + server share S (encrypted
-- under VAULT_ESCROW_KEY); the user share U is emailed once and never stored (no column for it).
-- No inline comments: the pg shim joins lines. Additive only.
CREATE TABLE IF NOT EXISTS vault_recovery_enrollments (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL,
escrow_blob TEXT,
escrow_iv TEXT,
server_share_ct TEXT,
server_share_iv TEXT,
key_version bigint NOT NULL,
vault_created_at TEXT NOT NULL,
enrolled_at bigint NOT NULL,
revoked_at bigint
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_enrollments_user ON vault_recovery_enrollments(user_id, status);
CREATE TABLE IF NOT EXISTS vault_recovery_codes (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash TEXT NOT NULL,
attempts bigint NOT NULL DEFAULT 0,
created_at bigint NOT NULL,
expires_at bigint NOT NULL,
used_at bigint
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_codes_user ON vault_recovery_codes(user_id, created_at);
CREATE TABLE IF NOT EXISTS vault_recovery_payments (
checkout_session_id TEXT PRIMARY KEY,
payment_ref TEXT,
payment_id TEXT,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
amount_usd double precision,
method TEXT,
status TEXT NOT NULL,
created_at bigint NOT NULL,
settled_at bigint
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_payments_user ON vault_recovery_payments(user_id, status);
CREATE TABLE IF NOT EXISTS vault_recovery_audit (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
action TEXT NOT NULL,
detail TEXT,
ip TEXT,
user_agent TEXT,
created_at bigint NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_audit_user ON vault_recovery_audit(user_id, created_at);
65 changes: 65 additions & 0 deletions apps/pwa/src/migrations/014_vault_email_recovery.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
-- Vault email recovery (opt-in, $5 lifetime per user). See docs/opencreds/security.md.
--
-- The CLI encrypts the personal vault's user key under a random key E and splits
-- E into two XOR shares. The server keeps the escrowed blob and share S, with S
-- encrypted under VAULT_ESCROW_KEY (key_version says which one, for rotation).
-- The other share, U, is emailed to the account once and NEVER stored: there is
-- deliberately no column for it. Neither the blob, S, nor this database plus the
-- server env opens a vault without the enrollment email.
--
-- status: pending (enrollment email not yet confirmed sent) -> active -> revoked.
-- A revoked row keeps its timestamps for the audit trail; its escrow material is
-- set to NULL (deleted). Additive only.
CREATE TABLE IF NOT EXISTS vault_recovery_enrollments (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL,
escrow_blob TEXT,
escrow_iv TEXT,
server_share_ct TEXT,
server_share_iv TEXT,
key_version INTEGER NOT NULL,
vault_created_at TEXT NOT NULL,
enrolled_at INTEGER NOT NULL,
revoked_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_enrollments_user ON vault_recovery_enrollments(user_id, status);

-- One-time codes for a recovery: 8 digits, HMAC'd at rest, 15 minutes, 5 tries, single use.
CREATE TABLE IF NOT EXISTS vault_recovery_codes (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
used_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_codes_user ON vault_recovery_codes(user_id, created_at);

-- The purchase ledger: one row per CoinPay checkout session; settled once.
-- Entitlement = any settled row for the user.
CREATE TABLE IF NOT EXISTS vault_recovery_payments (
checkout_session_id TEXT PRIMARY KEY,
payment_ref TEXT,
payment_id TEXT,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
amount_usd REAL,
method TEXT,
status TEXT NOT NULL,
created_at INTEGER NOT NULL,
settled_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_payments_user ON vault_recovery_payments(user_id, status);

-- Append-only trail of every enroll, start, claim, failure and disable.
CREATE TABLE IF NOT EXISTS vault_recovery_audit (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
action TEXT NOT NULL,
detail TEXT,
ip TEXT,
user_agent TEXT,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_vault_recovery_audit_user ON vault_recovery_audit(user_id, created_at);
9 changes: 8 additions & 1 deletion apps/pwa/src/routes/auto-rotation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions apps/pwa/src/routes/pages.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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>
Expand Down Expand Up @@ -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>
Expand Down
201 changes: 201 additions & 0 deletions apps/pwa/src/routes/vault-recovery.mjs
Original file line number Diff line number Diff line change
@@ -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>`;
}
2 changes: 2 additions & 0 deletions apps/pwa/src/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { autoRotationRouter } from "./routes/auto-rotation.mjs";
import { sweepAutoRotation } from "./lib/auto-rotation.mjs";
import { apiKeysRouter } from "./routes/apikeys.mjs";
import { opencredsRouter } from "./routes/opencreds.mjs";
import { vaultRecoveryRouter } from "./routes/vault-recovery.mjs";
import { keyringRouter } from "./routes/keyring.mjs";
import { keyringShareRouter, publicKeysRouter } from "./routes/keyring-share.mjs";
import { cliRouter } from "./routes/cli.mjs";
Expand Down Expand Up @@ -97,6 +98,7 @@ app.use(autoRotationRouter); // paid automatic rotation: CoinPay checkout + /api
app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values)
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
app.use(vaultRecoveryRouter); // /api/opencreds/recovery/* + /settings/vault-recovery/* — opt-in paid email recovery
app.use(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key)
app.use(keyringRouter); // /api/keyring/* + /keyring — SSH keys / key pairs, ciphertext only
app.use(cliRouter); // /cli/authorize, /cli/token, /api/me
Expand Down
Loading
Loading