mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-04 02:29:06 +00:00
Three locked a real owner out for an hour after a few honest retries
("Too many recovery attempts. Try again in 1 minute(s)."). The guess budget
stays negligible: 10 codes x 5 tries an hour against 10^8, and every start
mails the owner. Confirmation links share the same allowance.
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
514 lines
30 KiB
JavaScript
514 lines
30 KiB
JavaScript
// Vault email recovery (lib/vault-recovery.mjs, routes/vault-recovery.mjs): a
|
|
// paid, opt-in escrow. What these pin: enrolling needs the purchase (402 with a
|
|
// checkout link otherwise); the user share U goes out in the email and is never
|
|
// written anywhere; a failed email leaves nothing enrolled; one-time codes have
|
|
// a TTL, an attempt cap, single use and a start rate limit; a claim returns S
|
|
// decrypted and, with U, reopens the vault key; disable deletes the material;
|
|
// the shared CoinPay webhook settles vault_recovery once and still settles
|
|
// auto_rotation; a machine key never gets in.
|
|
process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:";
|
|
process.env.COINPAY_WEBHOOK_SECRET = "whsec_test";
|
|
process.env.COINPAY_API_KEY = "cp_test";
|
|
process.env.COINPAY_API_URL = "https://coinpay.test";
|
|
process.env.RESEND_API_KEY = "re_test";
|
|
process.env.VAULT_ESCROW_KEY = (await import("node:crypto")).randomBytes(32).toString("base64");
|
|
delete process.env.VAULT_ESCROW_KEY_VERSION;
|
|
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { readFileSync } from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
import { dirname, join } from "node:path";
|
|
import express from "express";
|
|
import { signWebhook } from "@profullstack/coinpay-onboard";
|
|
import {
|
|
createVault,
|
|
formatRecoveryCode,
|
|
fromBase64,
|
|
parseRecoveryCode,
|
|
prepareEnrollment,
|
|
recoverUserKeyByEmail,
|
|
} from "@logicsrc/opencreds";
|
|
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const { db, run, get, all, isPostgres } = await import("../src/db.mjs");
|
|
const { vaultRecoveryRouter } = await import("../src/routes/vault-recovery.mjs");
|
|
const { autoRotationRouter } = await import("../src/routes/auto-rotation.mjs");
|
|
const { createApiKey } = await import("../src/lib/apikey.mjs");
|
|
const vr = await import("../src/lib/vault-recovery.mjs");
|
|
|
|
const now = Date.now();
|
|
|
|
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", "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);
|
|
}
|
|
|
|
// ---- outbound mail and CoinPay, intercepted; everything else (our own server) passes through ----
|
|
const realFetch = globalThis.fetch;
|
|
const mail = [];
|
|
let mailFails = false;
|
|
let sessionSeq = 0;
|
|
const sessions = new Map();
|
|
globalThis.fetch = async (url, init = {}) => {
|
|
const u = String(url);
|
|
if (u.startsWith("https://api.resend.com/")) {
|
|
const body = JSON.parse(init.body);
|
|
if (mailFails) return new Response(JSON.stringify({ message: "down" }), { status: 500 });
|
|
mail.push(body);
|
|
return new Response(JSON.stringify({ id: `em_${mail.length}` }), { status: 200 });
|
|
}
|
|
if (u.startsWith("https://coinpay.test/api/checkout/sessions")) {
|
|
if ((init.method || "GET") === "POST") {
|
|
const input = JSON.parse(init.body);
|
|
const id = `cs_vr${++sessionSeq}`;
|
|
const session = { id, url: `https://coinpay.test/pay/${id}`, status: "open", amount: input.amount, currency: "USD", metadata: input.metadata, account_id: input.account_id };
|
|
sessions.set(id, session);
|
|
return new Response(JSON.stringify({ session }), { status: 201 });
|
|
}
|
|
const id = decodeURIComponent(u.split("/").pop());
|
|
return new Response(JSON.stringify({ session: sessions.get(id) }), { status: 200 });
|
|
}
|
|
return realFetch(url, init);
|
|
};
|
|
test.after(() => { globalThis.fetch = realFetch; });
|
|
|
|
// ---- people, keys and a team (for the auto-rotation dispatch check) ----
|
|
const users = ["u_a", "u_b", "u_c", "u_d", "u_e", "u_owner"];
|
|
for (const uid of users) await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, `${uid}@example.com`, now]);
|
|
const keys = {};
|
|
for (const uid of users) keys[uid] = (await createApiKey(uid, "cli")).plaintext;
|
|
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t_acme", "acme", "acme", "u_owner", now]);
|
|
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t_acme", "u_owner", "u_owner@example.com", "owner", "active", now]);
|
|
const machine = (await createApiKey("u_a", "dev2-deploy", { kind: "machine", teamId: "t_acme", vaultScope: null, readOnly: true })).plaintext;
|
|
|
|
const app = express();
|
|
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf.toString("utf8"); } }));
|
|
app.use(vaultRecoveryRouter);
|
|
app.use(autoRotationRouter);
|
|
const server = app.listen(0);
|
|
await new Promise((r) => server.once("listening", r));
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
test.after(() => new Promise((r) => server.close(r)));
|
|
|
|
async function call(token, method, path, body, headers = {}) {
|
|
const raw = body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body);
|
|
const res = await realFetch(base + path, {
|
|
method,
|
|
headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(raw ? { "content-type": "application/json" } : {}), ...headers },
|
|
body: raw,
|
|
});
|
|
const text = await res.text();
|
|
return { status: res.status, body: text ? JSON.parse(text) : null };
|
|
}
|
|
|
|
// One real vault for everything below (PBKDF2 at the floor, to keep this quick).
|
|
const vault = await createVault("old master password", { params: { kdf: "pbkdf2-sha256", iterations: 100_000 } });
|
|
|
|
async function enrollPayload() {
|
|
const prepared = await prepareEnrollment(vault.meta, vault.userKey);
|
|
return { ...prepared.payload };
|
|
}
|
|
const grant = (uid, cs = `cs_grant_${uid}`) =>
|
|
run(`INSERT INTO vault_recovery_payments (checkout_session_id, user_id, status, created_at, settled_at) VALUES (?,?,?,?,?)`, [cs, uid, "settled", now, now]);
|
|
const lastMailTo = (to) => [...mail].reverse().find((m) => m.to === to);
|
|
const codeIn = (text) => /\b([0-9A-Z]{5}(?:-[0-9A-Z]{5}){11})\b/.exec(text)?.[1];
|
|
const otpIn = (text) => /One-time code: (\d{8})/.exec(text)?.[1];
|
|
|
|
async function enrolled(uid) {
|
|
await grant(uid);
|
|
const payload = await enrollPayload();
|
|
const r = await call(keys[uid], "POST", "/api/opencreds/recovery/enroll", payload);
|
|
assert.equal(r.status, 201, JSON.stringify(r.body));
|
|
return payload;
|
|
}
|
|
|
|
test("no key: 401; a machine key is refused everywhere", async () => {
|
|
assert.equal((await call(null, "GET", "/api/opencreds/recovery")).status, 401);
|
|
for (const [method, path] of [["GET", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/enroll"], ["POST", "/api/opencreds/recovery/start"], ["POST", "/api/opencreds/recovery/claim"], ["DELETE", "/api/opencreds/recovery"], ["POST", "/api/opencreds/recovery/checkout"]]) {
|
|
const r = await call(machine, method, path, method === "POST" ? {} : undefined);
|
|
assert.equal(r.status, 403, `${method} ${path}`);
|
|
assert.equal(r.body.code, "machine_key_forbidden");
|
|
}
|
|
});
|
|
|
|
test("enroll without the purchase: 402 with a checkout link, and nothing stored", async () => {
|
|
const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload());
|
|
assert.equal(r.status, 402);
|
|
assert.equal(r.body.code, "payment_required");
|
|
assert.equal(r.body.priceUsd, 5);
|
|
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, 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 () => {
|
|
const checkout = await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout");
|
|
assert.equal(checkout.status, 201);
|
|
const cs = checkout.body.sessionId;
|
|
const created = sessions.get(cs);
|
|
assert.equal(created.metadata.purpose, "vault_recovery");
|
|
assert.equal(created.metadata.user_id, "u_a");
|
|
assert.ok(created.metadata.payment_ref);
|
|
assert.equal((await get(`SELECT status FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs])).status, "pending");
|
|
|
|
const event = (id, data) => JSON.stringify({ id, type: "payment.confirmed", data: { payment_id: `pay_${id}`, status: "confirmed", amount_usd: 5, blockchain: "USDC_POL", property: "app.logicsrc.com", ...data } });
|
|
const vrEvent = event("vr1", { checkout_session_id: cs, metadata: { purpose: "vault_recovery", user_id: "u_a", payment_ref: created.metadata.payment_ref } });
|
|
assert.equal((await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": "t=1,v1=bad" })).status, 401);
|
|
const first = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") });
|
|
assert.equal(first.status, 200);
|
|
assert.equal(first.body.purpose, "vault_recovery");
|
|
assert.equal(first.body.action, "settled");
|
|
const replay = await call(null, "POST", "/api/coinpay/webhook", vrEvent, { "x-coinpay-signature": signWebhook(vrEvent, "whsec_test") });
|
|
assert.equal(replay.body.duplicate, true);
|
|
const row = await get(`SELECT * FROM vault_recovery_payments WHERE checkout_session_id = ?`, [cs]);
|
|
assert.equal(row.status, "settled");
|
|
assert.equal((await all(`SELECT * FROM vault_recovery_payments WHERE user_id = ? AND status = 'settled'`, ["u_a"])).length, 1);
|
|
assert.equal((await call(keys.u_a, "GET", "/api/opencreds/recovery")).body.purchased, true);
|
|
assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/checkout")).status, 409);
|
|
|
|
// The same endpoint, an auto-rotation purchase: routed to the old settler, unchanged.
|
|
const arEvent = event("ar1", { checkout_session_id: "cs_ar1", metadata: { purpose: "auto_rotation", team_id: "t_acme", user_id: "u_owner" } });
|
|
const ar = await call(null, "POST", "/api/coinpay/webhook", arEvent, { "x-coinpay-signature": signWebhook(arEvent, "whsec_test") });
|
|
assert.equal(ar.body.action, "activated");
|
|
assert.equal(Number((await get(`SELECT rotation_auto_approve FROM credshare_teams WHERE id = ?`, ["t_acme"])).rotation_auto_approve), 1);
|
|
assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_payments WHERE checkout_session_id = ?`, ["cs_ar1"])).n), 0);
|
|
|
|
// An unpaid vault_recovery event settles nothing.
|
|
const pending = JSON.stringify({ id: "vr2", type: "payment.pending", data: { status: "pending", metadata: { purpose: "vault_recovery", user_id: "u_b" } } });
|
|
assert.equal((await call(null, "POST", "/api/coinpay/webhook", pending, { "x-coinpay-signature": signWebhook(pending, "whsec_test") })).body.handled, false);
|
|
assert.equal(await vr.isEntitled("u_b"), false);
|
|
});
|
|
|
|
test("enroll rolls back when the email does not send (a prior enrollment survives)", async () => {
|
|
mailFails = true;
|
|
try {
|
|
const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload());
|
|
assert.equal(r.status, 502);
|
|
assert.equal(r.body.code, "email_failed");
|
|
} finally {
|
|
mailFails = false;
|
|
}
|
|
assert.equal(Number((await get(`SELECT COUNT(*) AS n FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_a"])).n), 0);
|
|
|
|
await enrolled("u_c");
|
|
const before = await get(`SELECT id FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_c"]);
|
|
mailFails = true;
|
|
try {
|
|
assert.equal((await call(keys.u_c, "POST", "/api/opencreds/recovery/enroll", await enrollPayload())).status, 502);
|
|
} finally {
|
|
mailFails = false;
|
|
}
|
|
const rows = await all(`SELECT id, status FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_c"]);
|
|
assert.deepEqual(rows.map((r) => [r.id, r.status]), [[before.id, "active"]]);
|
|
});
|
|
|
|
test("enroll emails U as a checksummed code and never stores it; a re-enroll replaces the old one", async () => {
|
|
const payload = await enrollPayload();
|
|
const sent = mail.length;
|
|
const r = await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", payload);
|
|
assert.equal(r.status, 201);
|
|
assert.deepEqual(r.body, { enrolled: true, email: "u***@example.com" });
|
|
assert.ok(!JSON.stringify(r.body).includes(payload.userShare));
|
|
|
|
assert.equal(mail.length, sent + 1);
|
|
const email = mail.at(-1);
|
|
assert.equal(email.to, "u_a@example.com");
|
|
assert.equal(email.subject, "Your LogicSRC vault email-recovery code — keep this email");
|
|
const code = codeIn(email.text);
|
|
assert.ok(code, "a recovery code in the email");
|
|
const U = fromBase64(payload.userShare);
|
|
// The server's renderer and the CLI's agree, and the CLI parses it back to U.
|
|
assert.equal(code, await formatRecoveryCode(U));
|
|
assert.deepEqual(await parseRecoveryCode(code), U);
|
|
|
|
// U is nowhere at rest: no column for it, and no value in any table holds it in any encoding.
|
|
const tables = ["vault_recovery_enrollments", "vault_recovery_codes", "vault_recovery_payments", "vault_recovery_audit", "users", "api_keys"];
|
|
const needles = [payload.userShare, Buffer.from(U).toString("hex"), Buffer.from(U).toString("base64url"), code, code.replace(/-/g, "")];
|
|
for (const table of tables) {
|
|
for (const row of await all(`SELECT * FROM ${table}`)) {
|
|
for (const [column, value] of Object.entries(row)) {
|
|
assert.ok(!/user_?share/i.test(column), `${table}.${column}`);
|
|
if (typeof value !== "string") continue;
|
|
for (const needle of needles) assert.ok(!value.includes(needle), `U found in ${table}.${column}`);
|
|
}
|
|
}
|
|
}
|
|
// S is stored only encrypted.
|
|
const active = await get(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? AND status = 'active'`, ["u_a"]);
|
|
assert.notEqual(active.server_share_ct, payload.serverShare);
|
|
assert.equal(Number(active.key_version), 1);
|
|
assert.equal(active.escrow_blob, payload.escrowBlob);
|
|
|
|
// Re-enroll: a single active row, the old one revoked with its material deleted.
|
|
const again = await enrollPayload();
|
|
assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", again)).status, 201);
|
|
const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ? ORDER BY enrolled_at, status`, ["u_a"]);
|
|
assert.equal(rows.filter((x) => x.status === "active").length, 1);
|
|
const old = rows.find((x) => x.id === active.id);
|
|
assert.equal(old.status, "revoked");
|
|
assert.equal(old.escrow_blob, null);
|
|
assert.equal(old.server_share_ct, null);
|
|
});
|
|
|
|
test("start + claim: emails a code, wrong code counts, the right one returns S decrypted and reopens K, once", async () => {
|
|
const payload = await enrolled("u_d");
|
|
const U = await parseRecoveryCode(codeIn(lastMailTo("u_d@example.com").text));
|
|
|
|
const start = await call(keys.u_d, "POST", "/api/opencreds/recovery/start");
|
|
assert.deepEqual(start.body, { sent: true, email: "u***@example.com" });
|
|
const otp = otpIn(lastMailTo("u_d@example.com").text);
|
|
assert.match(otp, /^\d{8}$/);
|
|
const row = await get(`SELECT * FROM vault_recovery_codes WHERE user_id = ? AND used_at IS NULL`, ["u_d"]);
|
|
assert.ok(!row.code_hash.includes(otp));
|
|
assert.equal(Number(row.expires_at) - Number(row.created_at), 15 * 60 * 1000);
|
|
|
|
const wrong = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp === "00000000" ? "11111111" : "00000000" });
|
|
assert.equal(wrong.status, 401);
|
|
assert.equal(wrong.body.attemptsLeft, 4);
|
|
|
|
const notices = mail.length;
|
|
const claim = await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp });
|
|
assert.equal(claim.status, 200);
|
|
assert.deepEqual(claim.body, { escrowBlob: payload.escrowBlob, escrowIv: payload.escrowIv, serverShare: payload.serverShare, vaultCreatedAt: vault.meta.createdAt });
|
|
assert.equal(mail.at(-1).subject, "Your LogicSRC vault email recovery was used");
|
|
assert.equal(mail.length, notices + 1);
|
|
assert.ok((await all(`SELECT action FROM vault_recovery_audit WHERE user_id = ?`, ["u_d"])).some((a) => a.action === "claim"));
|
|
|
|
// S from the server + U from the enrollment email = the vault's own key.
|
|
const K = await recoverUserKeyByEmail({ meta: vault.meta, material: claim.body, userShare: U });
|
|
assert.deepEqual(K, vault.userKey);
|
|
|
|
// Single use.
|
|
assert.equal((await call(keys.u_d, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410);
|
|
});
|
|
|
|
test("codes expire after 15 minutes and die after 5 wrong tries", async () => {
|
|
await enrolled("u_e");
|
|
await call(keys.u_e, "POST", "/api/opencreds/recovery/start");
|
|
const expired = otpIn(lastMailTo("u_e@example.com").text);
|
|
await run(`UPDATE vault_recovery_codes SET expires_at = ? WHERE user_id = ? AND used_at IS NULL`, [Date.now() - 1, "u_e"]);
|
|
const late = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: expired });
|
|
assert.equal(late.status, 410);
|
|
assert.equal(late.body.code, "code_expired");
|
|
|
|
await call(keys.u_e, "POST", "/api/opencreds/recovery/start");
|
|
const otp = otpIn(lastMailTo("u_e@example.com").text);
|
|
const bad = otp === "99999999" ? "88888888" : "99999999";
|
|
let r;
|
|
for (let i = 0; i < 5; i++) r = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: bad });
|
|
assert.equal(r.status, 401);
|
|
assert.equal(r.body.attemptsLeft, 0);
|
|
const after = await call(keys.u_e, "POST", "/api/opencreds/recovery/claim", { code: otp });
|
|
assert.equal(after.status, 410, "the right code is dead after five wrong ones");
|
|
});
|
|
|
|
test("start is rate limited per hour per user, with room for honest retries", async () => {
|
|
assert.equal(vr.STARTS_PER_HOUR, 10);
|
|
// u_e has used 2 starts above; the rest of the hour's allowance works, the next does not.
|
|
for (let i = 2; i < vr.STARTS_PER_HOUR; i++) {
|
|
assert.equal((await call(keys.u_e, "POST", "/api/opencreds/recovery/start")).status, 200, `start ${i + 1}`);
|
|
}
|
|
const limited = await call(keys.u_e, "POST", "/api/opencreds/recovery/start");
|
|
assert.equal(limited.status, 429);
|
|
assert.equal(limited.body.code, "rate_limited");
|
|
assert.ok(limited.body.retryAfter > 0);
|
|
});
|
|
|
|
test("start/claim need an active enrollment; disable deletes the material and kills live codes", async () => {
|
|
assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404);
|
|
|
|
await enrolled("u_b");
|
|
await call(keys.u_b, "POST", "/api/opencreds/recovery/start");
|
|
const otp = otpIn(lastMailTo("u_b@example.com").text);
|
|
const off = await call(keys.u_b, "DELETE", "/api/opencreds/recovery");
|
|
assert.deepEqual(off.body, { disabled: true });
|
|
const rows = await all(`SELECT * FROM vault_recovery_enrollments WHERE user_id = ?`, ["u_b"]);
|
|
assert.ok(rows.every((x) => x.status === "revoked" && x.escrow_blob === null && x.escrow_iv === null && x.server_share_ct === null && x.server_share_iv === null));
|
|
assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/claim", { code: otp })).status, 410);
|
|
assert.equal((await call(keys.u_b, "POST", "/api/opencreds/recovery/start")).status, 404);
|
|
const status = (await call(keys.u_b, "GET", "/api/opencreds/recovery")).body;
|
|
assert.equal(status.enrolled, false);
|
|
assert.equal(status.purchased, true, "disabling does not burn the purchase");
|
|
assert.deepEqual((await call(keys.u_b, "DELETE", "/api/opencreds/recovery")).body, { disabled: false });
|
|
});
|
|
|
|
test("escrow keyring: a rotated key still opens rows sealed under the old version", () => {
|
|
const share = Buffer.alloc(32, 7);
|
|
const v1 = vr.escrowKeyring({ VAULT_ESCROW_KEY: process.env.VAULT_ESCROW_KEY });
|
|
const sealed = vr.sealServerShare(share, "u_x", v1);
|
|
const rotated = vr.escrowKeyring({ VAULT_ESCROW_KEY: Buffer.alloc(32, 1).toString("base64"), VAULT_ESCROW_KEY_VERSION: "2", VAULT_ESCROW_KEY_V1: process.env.VAULT_ESCROW_KEY });
|
|
assert.equal(rotated.version, 2);
|
|
const row = { user_id: "u_x", server_share_ct: sealed.ct, server_share_iv: sealed.iv, key_version: sealed.version };
|
|
assert.deepEqual(vr.openServerShare(row, rotated), share);
|
|
// Bound to the user: the same ciphertext under another user id does not open.
|
|
assert.throws(() => vr.openServerShare({ ...row, user_id: "u_y" }, rotated));
|
|
assert.throws(() => vr.escrowKeyring({ VAULT_ESCROW_KEY: "dG9vLXNob3J0" }), /32 random bytes/);
|
|
});
|
|
|
|
test("the Settings card: a Buy button before the purchase, the CLI hint after, a switch-off once enrolled", async () => {
|
|
const { vaultRecoveryCard } = await import("../src/routes/vault-recovery.mjs");
|
|
const req = (uid) => ({ query: {}, user: { id: uid, email: `${uid}@example.com` }, csrfToken: "t" });
|
|
const unpaid = await vaultRecoveryCard(req("u_owner"));
|
|
assert.match(unpaid, /Vault email recovery — \$5 lifetime/);
|
|
assert.match(unpaid, /action="\/settings\/vault-recovery\/checkout"/);
|
|
await grant("u_owner");
|
|
assert.match(await vaultRecoveryCard(req("u_owner")), /logicsrc vault recovery enable/);
|
|
const on = await vaultRecoveryCard(req("u_a"));
|
|
assert.match(on, /action="\/settings\/vault-recovery\/disable"/);
|
|
assert.match(on, /u\*\*\*@example\.com/);
|
|
});
|
|
|
|
test("the re-arm after a recovery says it is finished, so nobody recovers again because of the email", async () => {
|
|
const after = vr.enrollmentEmail("AAAAA-BBBBB", { afterRecovery: true });
|
|
assert.match(after.subject, /^Your LogicSRC vault email-recovery code was replaced/);
|
|
assert.match(after.text, /You are done: there is nothing to run now\./);
|
|
assert.match(after.text, /AAAAA-BBBBB/);
|
|
const first = vr.enrollmentEmail("AAAAA-BBBBB");
|
|
assert.equal(first.subject, "Your LogicSRC vault email-recovery code — keep this email");
|
|
assert.doesNotMatch(first.text, /You are done/);
|
|
});
|
|
|
|
test("an enroll right after a claim sends the finished wording; a later one sends the ordinary one", async () => {
|
|
await vr.audit("u_a", "claim");
|
|
assert.equal((await call(keys.u_a, "POST", "/api/opencreds/recovery/enroll", await enrollPayload())).status, 201);
|
|
assert.match(mail.at(-1).subject, /was replaced — recovery complete, nothing to do$/);
|
|
assert.ok(codeIn(mail.at(-1).text), "the replacement code is in the email");
|
|
// The enroll itself is now the latest event, so the next enroll is an ordinary one.
|
|
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/);
|
|
});
|
|
|
|
test("the Settings card offers a way to add the second proof, and shows what the account has", async () => {
|
|
const { vaultRecoveryCard } = await import("../src/routes/vault-recovery.mjs");
|
|
const card = await vaultRecoveryCard({ user: { id: "u_a", email: "u_a@example.com" }, query: {}, csrfToken: "t" });
|
|
assert.match(card, /id="passkey-add"/);
|
|
assert.match(card, /no passkey/);
|
|
assert.match(card, /\/passkey-add\.js/);
|
|
const added = await vaultRecoveryCard({ user: { id: "u_a", email: "u_a@example.com" }, query: { passkey: "added" }, csrfToken: "t" });
|
|
assert.match(added, /Passkey added\./);
|
|
// An error handed back by the CoinPay round trip is shown escaped.
|
|
const bad = await vaultRecoveryCard({ user: { id: "u_a", email: "u_a@example.com" }, query: { coinpay_err: "<b>x</b>" }, csrfToken: "t" });
|
|
assert.doesNotMatch(bad, /<b>x<\/b>/);
|
|
});
|
|
|
|
test("linkCoinpay connects an identity only to an account that has none", async () => {
|
|
const { linkCoinpay, userByCoinpay } = await import("../src/lib/users.mjs");
|
|
await linkCoinpay("u_b", "sub_link_1");
|
|
assert.equal((await userByCoinpay("sub_link_1")).id, "u_b");
|
|
await linkCoinpay("u_b", "sub_link_2");
|
|
assert.ok(!(await userByCoinpay("sub_link_2")), "a second identity does not replace the first");
|
|
});
|