logicsrc/packages/opencreds/src/email-recovery.test.ts
Anthony Ettinger 41ad9f0987
vault: opt-in paid email recovery for the personal vault ($5 lifetime) (#298)
* vault: opt-in paid email recovery for the personal vault ($5 lifetime)

A second way back into a logicsrc personal vault when the master password and
the offline recovery key are both gone, without the server holding anything
that alone (even with the DB and server env) opens the vault.

Client (packages/opencreds): random escrow key E encrypts the user key K
(AES-256-GCM, AAD "<ns>:vault:email-escrow:v1|<createdAt>"); E is split into
S (random, to the server) and U = E XOR S (emailed once as a checksummed
Crockford recovery code, never stored). `recover --email` checks the code's
check group first, asks the server for a one-time code, claims S, recombines
E, proves K against an item, sets a new password, issues a new offline
recovery key and re-enrolls with fresh shares (warns loudly if that fails).
New `recovery status|buy|enable|disable` commands; the CLI client lives in
packages/cli/src/vault-sync.ts.

Server (apps/pwa): /api/opencreds/recovery/{checkout,enroll,start,claim} +
status/disable. S is sealed under VAULT_ESCROW_KEY (versioned for rotation,
AAD binds the user). Enrollment is pending until the email with U is sent,
else rolled back. One-time codes: 8 digits, HMAC at rest, 15 min, 5 tries,
single use, 3 starts/hour; claims are audited and announced by email.
Purchase via CoinPay checkout (purpose vault_recovery); /api/coinpay/webhook
now verifies once and dispatches by purpose, auto_rotation unchanged.
Settings card with status and a Buy button. Migration 014 in both dialects.

Docs: security.md and crypto.md "Email recovery (opt-in, paid)" sections with
the honest trade-off; cli.md command reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vault email recovery: state that the mailbox alone is enough

The account password resets by email, so mailbox control = sign-in + one-time
code + the enrollment code U. Say so in security.md and stop the one-time-code
email from implying the vault stays safe if someone else reads the mailbox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vault email recovery: leave .env.example as on master

Touching it made the credential gate re-scan the existing SESSION_SECRET
placeholder (false positive). VAULT_ESCROW_KEY / _VERSION / VAULT_RECOVERY_PRICE_USD
are documented in docs/opencreds/security.md and crypto.md; prod values live in
vault app-logicsrc-com--prod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:49:06 -08:00

318 lines
14 KiB
TypeScript

/**
* Email recovery: the XOR split, the escrow copy, the recovery code format, and
* the whole `recover --email` flow against a fake account server that behaves
* like apps/pwa (stores S and the blob, mails U and one-time codes, never keeps U).
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
EmailRecoveryError,
RecoveryCodeMismatchError,
combineEscrowKey,
enrollEmailRecovery,
formatRecoveryCode,
openEscrow,
parseRecoveryCode,
prepareEnrollment,
recoverUserKeyByEmail,
runEmailRecovery,
sealEscrow,
splitEscrowKey,
xorBytes,
type EmailRecoveryClient,
type EscrowEnrollment,
type EscrowMaterial,
} from "./email-recovery.js";
import { createItem, encryptItem } from "./items.js";
import { fromBase64, randomBytes, toBase64 } from "./primitives.js";
import { createVaultStore } from "./store.js";
import { createVault, unlockVault, unlockWithRecoveryKey } from "./vault-key.js";
const FAST = { kdf: "pbkdf2-sha256" as const, iterations: 100_000 };
const dirs: string[] = [];
afterEach(() => {
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
});
describe("the XOR split", () => {
it("splits E into two shares that recombine, and neither share is E", () => {
const E = randomBytes(32);
const { serverShare, userShare } = splitEscrowKey(E);
expect(serverShare).not.toEqual(E);
expect(userShare).not.toEqual(E);
expect(combineEscrowKey(serverShare, userShare)).toEqual(E);
expect(xorBytes(userShare, E)).toEqual(serverShare);
});
it("gives a fresh server share every time", () => {
const E = randomBytes(32);
expect(splitEscrowKey(E).serverShare).not.toEqual(splitEscrowKey(E).serverShare);
});
it("refuses shares of the wrong size", () => {
expect(() => splitEscrowKey(randomBytes(16))).toThrow();
expect(() => combineEscrowKey(randomBytes(32), randomBytes(31))).toThrow();
});
});
describe("the escrow copy of the user key", () => {
it("round-trips K under E, bound to the vault", async () => {
const { meta, userKey } = await createVault("pw", { params: FAST });
const sealed = await sealEscrow(userKey, meta);
const material = { ...sealed, vaultCreatedAt: meta.createdAt! };
expect(await openEscrow(sealed.escrowKey, material, meta.namespace)).toEqual(userKey);
// Another vault's createdAt is different associated data: the tag fails.
await expect(openEscrow(sealed.escrowKey, { ...material, vaultCreatedAt: "2001-01-01T00:00:00Z" }, meta.namespace)).rejects.toBeInstanceOf(
RecoveryCodeMismatchError,
);
});
it("a wrong U fails cleanly with a mismatch error, not a crypto stack", async () => {
const { meta, userKey } = await createVault("pw", { params: FAST });
const { payload } = await prepareEnrollment(meta, userKey);
const material: EscrowMaterial = { ...payload };
const wrongU = randomBytes(32);
const err = await recoverUserKeyByEmail({ meta, material, userShare: wrongU }).catch((e) => e);
expect(err).toBeInstanceOf(RecoveryCodeMismatchError);
expect(err.message).toMatch(/doesn't match/);
// The right U opens it.
expect(await recoverUserKeyByEmail({ meta, material, userShare: fromBase64(payload.userShare) })).toEqual(userKey);
});
it("refuses material enrolled for a different vault", async () => {
const a = await createVault("pw", { params: FAST });
const b = await createVault("pw", { params: FAST });
const { payload } = await prepareEnrollment(a.meta, a.userKey);
const err = await recoverUserKeyByEmail({
meta: { ...b.meta, createdAt: "2030-01-01T00:00:00Z" },
material: payload,
userShare: fromBase64(payload.userShare),
}).catch((e) => e);
expect(err).toBeInstanceOf(EmailRecoveryError);
expect(err.code).toBe("vault_mismatch");
});
it("wipes E, S and U on request", async () => {
const { meta, userKey } = await createVault("pw", { params: FAST });
const prepared = await prepareEnrollment(meta, userKey);
expect(fromBase64(prepared.payload.userShare).some((b) => b !== 0)).toBe(true);
prepared.wipe(); // no throw; the base64 copies in the payload are what gets sent
});
});
describe("the recovery code", () => {
it("is twelve groups of five and parses back to U", async () => {
const U = randomBytes(32);
const code = await formatRecoveryCode(U);
expect(code).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){11}$/);
expect(await parseRecoveryCode(code)).toEqual(U);
});
it("tolerates case, spaces, missing dashes and Crockford's confusables", async () => {
const U = randomBytes(32);
const code = await formatRecoveryCode(U);
const sloppy = code.toLowerCase().replace(/-/g, " ").replace(/0/g, "o").replace(/1/g, "l");
expect(await parseRecoveryCode(sloppy)).toEqual(U);
});
it("catches a typo with the check group, before anything is spent", async () => {
const U = randomBytes(32);
const code = await formatRecoveryCode(U);
// Change one data character to a different valid one.
const i = 7;
const swapped = code[i] === "A" ? "B" : "A";
const typo = code.slice(0, i) + swapped + code.slice(i + 1);
const err = await parseRecoveryCode(typo).catch((e) => e);
expect(err).toBeInstanceOf(EmailRecoveryError);
expect(err.code).toBe("recovery_code_typo");
// A typo in the check group itself is caught too.
const last = code.at(-1) === "Z" ? "Y" : "Z";
expect((await parseRecoveryCode(code.slice(0, -1) + last).catch((e) => e)).code).toBe("recovery_code_typo");
});
it("rejects the wrong length and bad characters", async () => {
expect((await parseRecoveryCode("ABCDE-FGHJK").catch((e) => e)).code).toBe("recovery_code_invalid");
const code = await formatRecoveryCode(randomBytes(32));
expect((await parseRecoveryCode(code.replace(/^./, "U")).catch((e) => e)).code).toBe("recovery_code_invalid");
});
});
/** A fake apps/pwa: keeps S and the blob, "mails" U and one-time codes, and never stores U. */
function fakeServer() {
let enrollment: (EscrowMaterial & { active: boolean }) | null = null;
let otp: { code: string; used: boolean } | null = null;
const inbox: string[] = [];
const state = { starts: 0, claims: 0, failEnroll: false };
const client: EmailRecoveryClient = {
label: "fake.test (me@example.com)",
async status() {
return { enrolled: Boolean(enrollment?.active), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5 };
},
async checkout() {
return { url: "https://coinpay.test/pay/cs_1", priceUsd: 5 };
},
async enroll(p: EscrowEnrollment) {
if (state.failEnroll) throw new EmailRecoveryError("Could not send the enrollment email", 502, "email_failed");
enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt, active: true };
inbox.push(await formatRecoveryCode(fromBase64(p.userShare)));
otp = null;
return { enrolled: true, email: "m***@example.com" };
},
async start() {
if (!enrollment?.active) throw new EmailRecoveryError("not enrolled", 404, "not_enrolled");
state.starts++;
otp = { code: String(Math.floor(Math.random() * 1e8)).padStart(8, "0"), used: false };
return { sent: true, email: "m***@example.com" };
},
async claim(code: string) {
state.claims++;
if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code");
otp.used = true;
const { active: _active, ...material } = enrollment!;
return material;
},
async disable() {
const was = Boolean(enrollment?.active);
enrollment = null;
return { disabled: was };
},
};
return { client, inbox, state, otp: () => otp?.code ?? "" };
}
async function vaultOnDisk() {
const dir = mkdtempSync(join(tmpdir(), "opencreds-email-recovery-"));
dirs.push(dir);
const store = createVaultStore(dir);
const created = await createVault("old master password", { params: FAST });
store.writeMeta(created.meta);
const item = createItem("login", { name: "GitHub", login: { username: "me", password: "hunter2" } });
store.writeEnvelope(await encryptItem(created.userKey, item, created.meta.namespace));
return { store, ...created };
}
describe("recover --email, end to end against a fake server", () => {
it("new password unlocks; the old password and the old recovery key do not; the used code is dead", async () => {
const { store, meta, userKey, recoveryKey: oldRecoveryKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const enrolledCode = server.inbox.at(-1)!;
const said: string[] = [];
const result = await runEmailRecovery({
store,
client: server.client,
say: (l) => said.push(l),
prompts: {
recoveryCode: async () => enrolledCode,
oneTimeCode: async () => server.otp(),
newPassword: async () => "brand new master password",
},
});
expect(result.userKey).toEqual(userKey);
expect(result.recoveryKey).not.toBe(oldRecoveryKey);
expect(said.join("\n")).toMatch(/one-time code was emailed to m\*\*\*@example\.com/);
const onDisk = store.readMeta()!;
expect(onDisk.createdAt).toBe(meta.createdAt);
expect(await unlockVault(onDisk, "brand new master password")).toEqual(userKey);
await expect(unlockVault(onDisk, "old master password")).rejects.toThrow(/Wrong master password/);
await expect(unlockWithRecoveryKey(onDisk, oldRecoveryKey)).rejects.toThrow(/Wrong recovery key/);
expect(await unlockWithRecoveryKey(onDisk, result.recoveryKey)).toEqual(userKey);
// Re-armed with fresh shares: a new code was mailed and the old one no longer opens anything.
expect(result.reenrolled).toBe(true);
expect(server.inbox).toHaveLength(2);
expect(server.inbox[1]).not.toBe(enrolledCode);
await server.client.start();
const material = await server.client.claim(server.otp());
await expect(
recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(enrolledCode) }),
).rejects.toBeInstanceOf(RecoveryCodeMismatchError);
expect(
await recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(server.inbox[1]!) }),
).toEqual(userKey);
});
it("a wrong recovery code: clear mismatch error, the one-time code is spent, the vault untouched", async () => {
const { store, meta, userKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const before = JSON.stringify(store.readMeta());
const otherCode = await formatRecoveryCode(randomBytes(32)); // well-formed, just not ours
let asked = false;
const err = await runEmailRecovery({
store,
client: server.client,
prompts: {
recoveryCode: async () => otherCode,
oneTimeCode: async () => server.otp(),
newPassword: async () => {
asked = true;
return "x";
},
},
}).catch((e) => e);
expect(err).toBeInstanceOf(RecoveryCodeMismatchError);
expect(err.message).toMatch(/doesn't match/);
expect(asked).toBe(false);
expect(server.state.claims).toBe(1);
await expect(server.client.claim(server.otp())).rejects.toThrow(/Wrong one-time code/); // spent
expect(JSON.stringify(store.readMeta())).toBe(before);
expect((await server.client.status()).enrolled).toBe(true); // the purchase and enrollment stand
});
it("a typo in the recovery code costs nothing: no one-time code is requested", async () => {
const { store, meta, userKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const code = server.inbox.at(-1)!;
const typo = code.slice(0, 3) + (code[3] === "A" ? "B" : "A") + code.slice(4);
const err = await runEmailRecovery({
store,
client: server.client,
prompts: { recoveryCode: async () => typo, oneTimeCode: async () => "", newPassword: async () => "x" },
}).catch((e) => e);
expect(err.code).toBe("recovery_code_typo");
expect(server.state.starts).toBe(0);
});
it("if re-enrolling fails the vault is still recovered, and the result says so", async () => {
const { store, meta, userKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const code = server.inbox.at(-1)!;
server.state.failEnroll = true;
const result = await runEmailRecovery({
store,
client: server.client,
prompts: { recoveryCode: async () => code, oneTimeCode: async () => server.otp(), newPassword: async () => "new pw" },
});
expect(result.reenrolled).toBe(false);
expect(result.reenrollError).toMatch(/enrollment email/);
expect(await unlockVault(store.readMeta()!, "new pw")).toEqual(userKey);
});
it("the server never receives E, and U only in the enroll call", async () => {
const { meta, userKey } = await vaultOnDisk();
const seen: EscrowEnrollment[] = [];
const server = fakeServer();
const spy: EmailRecoveryClient = {
...server.client,
enroll: async (p) => {
seen.push({ ...p });
return server.client.enroll(p);
},
};
await enrollEmailRecovery(spy, meta, userKey);
const p = seen[0]!;
const E = combineEscrowKey(fromBase64(p.serverShare), fromBase64(p.userShare));
for (const value of Object.values(p)) expect(value).not.toBe(toBase64(E));
expect(await openEscrow(E, p, meta.namespace)).toEqual(userKey);
});
});