mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-04 02:29:06 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
parent
896eba3c07
commit
6ff3089088
16 changed files with 799 additions and 62 deletions
39
apps/pwa/public/recover-confirm.js
Normal file
39
apps/pwa/public/recover-confirm.js
Normal file
|
|
@ -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;
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
22
apps/pwa/src/migrations-pg/015_vault_assisted_recovery.sql
Normal file
22
apps/pwa/src/migrations-pg/015_vault_assisted_recovery.sql
Normal file
|
|
@ -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);
|
||||
25
apps/pwa/src/migrations/015_vault_assisted_recovery.sql
Normal file
25
apps/pwa/src/migrations/015_vault_assisted_recovery.sql
Normal file
|
|
@ -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);
|
||||
|
|
@ -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");
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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: `<main class="wrap" style="max-width:560px;margin:48px auto;padding:0 16px"><div class="card"><div class="card-head"><span class="h">${esc(title)}</span></div><div class="card-body">${inner}</div></div></main>` });
|
||||
|
||||
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", `<p>This confirmation link has expired or was already used. Run the recovery again in your terminal to get a new one.</p>`));
|
||||
}
|
||||
if (stepup.status !== "pending") {
|
||||
return res.send(confirmPage("Vault recovery confirmed", `<div class="notice ok">Confirmed. Go back to your terminal and enter the one-time code we emailed you.</div>`));
|
||||
}
|
||||
const methods = await stepupMethods(stepup.user_id);
|
||||
const err = typeof req.query.err === "string" ? `<div class="notice err">${esc(req.query.err)}</div>` : "";
|
||||
const id = esc(stepup.id);
|
||||
res.send(confirmPage(
|
||||
"Confirm vault recovery",
|
||||
`${err}<p>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.</p>
|
||||
<div class="row" style="gap:10px;flex-wrap:wrap;margin-top:14px">
|
||||
${methods.passkey ? `<button class="btn acid" id="stepup-passkey" data-stepup="${id}">Confirm with passkey</button>` : ""}
|
||||
${methods.coinpay && config.coinpayLoginEnabled ? `<a class="btn" href="/recover/confirm/${id}/coinpay">Confirm with CoinPay</a>` : ""}
|
||||
</div>
|
||||
<p class="dim" id="stepup-msg" style="font-size:.85rem;margin-top:12px"></p>`,
|
||||
`<script src="/vendor/simplewebauthn-browser.umd.js" defer></script><script src="/recover-confirm.js" defer></script>`,
|
||||
));
|
||||
});
|
||||
|
||||
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 ? `<span class="faint">codes go to ${esc(status.email)}</span>` : ""}
|
||||
</div>
|
||||
<p class="dim" style="font-size:.85rem">${status.assisted
|
||||
? `<b>Assisted recovery is on.</b> 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 <code>logicsrc vault recovery enable</code> (without <code>--assisted</code>).`
|
||||
: `Delete your email? <code>logicsrc vault recovery enable --assisted</code> 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.`}</p>
|
||||
${status.configured ? action : `<p class="faint mono" style="font-size:.78rem">Not available on this server yet.</p>`}
|
||||
</div></div>`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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/);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue