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: `
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", `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.
+${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.`}
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