logicsrc/packages/cli/src/passwd.test.ts
Anthony Ettinger 6ff3089088
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>
2026-12-02 22:17:56 -08:00

503 lines
23 KiB
TypeScript

import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
EmailRecoveryError,
createItem,
createVault,
createVaultStore,
encryptItem,
enrollEmailRecovery,
formatRecoveryCode,
fromBase64,
pullVault,
pushVault,
rewrapUserKey,
unlockVault,
unlockWithRecoveryKey,
type EmailRecoveryClient,
type EscrowEnrollment,
type Envelope,
type EscrowMaterial,
type RemoteItem,
type RemoteVault,
type SyncRemote,
type VaultStore
} from "@logicsrc/opencreds";
import { KeyringStore, createKeyring, openEntry, sealEntry, unlockKeyring } from "./keyring.js";
import { changeAllPasswords, keyringEscrowId, readKeyringEscrow } from "./passwd.js";
const KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nAAAAfake\n-----END OPENSSH PRIVATE KEY-----\n";
const PUB = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIy86FQN77URkkunH3W6C28+mxsyOF5E6NrigzwAZGlz test";
let dir: string;
let vault: VaultStore;
let keyring: KeyringStore;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "passwd-test-"));
vault = createVaultStore(join(dir, "vault"));
keyring = new KeyringStore(join(dir, "keyring"));
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
/** Answers prompts in order. */
const answers = (...list: string[]) => async () => {
if (!list.length) throw new Error("unexpected prompt");
return list.shift()!;
};
async function seed(vaultPassword: string, keyringPassword: string) {
const v = await createVault(vaultPassword);
vault.writeMeta(v.meta);
const k = await createKeyring(keyringPassword);
keyring.writeMeta(k.meta);
keyring.write(await sealEntry(k.userKey, { name: "id_ed25519", privateKey: KEY, publicKey: PUB }));
return { vaultRecovery: v.recoveryKey, keyringRecovery: k.recoveryKey };
}
describe("logicsrc passwd", () => {
it("puts the vault and the keyring under one new password; stored keys still open", async () => {
await seed("old vault pw", "old keyring pw");
const r = await changeAllPasswords(
{ noSync: true },
{ vault, keyring, ask: answers("old vault pw", "old keyring pw"), askNew: async () => "one password", say: () => {} }
);
expect(r).toMatchObject({ vault: "changed", keyring: "changed" });
await expect(unlockVault(vault.readMeta()!, "one password")).resolves.toBeInstanceOf(Uint8Array);
await expect(unlockVault(vault.readMeta()!, "old vault pw")).rejects.toThrow();
const kk = await unlockKeyring(keyring.readMeta()!, { passphrase: "one password" });
await expect(unlockKeyring(keyring.readMeta()!, { passphrase: "old keyring pw" })).rejects.toThrow();
const opened = await openEntry(kk, keyring.find("id_ed25519")!);
expect(opened.privateKey).toBe(KEY);
}, 60_000);
it("tries the vault password on the keyring first, so a shared password is asked once", async () => {
await seed("same", "same");
const r = await changeAllPasswords(
{ noSync: true },
{ vault, keyring, ask: answers("same"), askNew: async () => "new", say: () => {} }
);
expect(r.keyring).toBe("changed");
}, 60_000);
it("falls back to the recovery keys, and those keep working afterwards", async () => {
const { vaultRecovery, keyringRecovery } = await seed("forgotten 1", "forgotten 2");
await changeAllPasswords(
{ noSync: true },
{ vault, keyring, ask: answers("", vaultRecovery, "", keyringRecovery), askNew: async () => "new", say: () => {} }
);
await expect(unlockKeyring(keyring.readMeta()!, { recoveryKey: keyringRecovery })).resolves.toBeInstanceOf(Uint8Array);
await expect(unlockKeyring(keyring.readMeta()!, { passphrase: "new" })).resolves.toBeInstanceOf(Uint8Array);
}, 60_000);
it("writes nothing when the keyring cannot be opened", async () => {
await seed("vault pw", "keyring pw");
const before = JSON.stringify(vault.readMeta());
await expect(
changeAllPasswords({ noSync: true }, { vault, keyring, ask: answers("vault pw", "wrong"), askNew: async () => "new", say: () => {} })
).rejects.toThrow();
expect(JSON.stringify(vault.readMeta())).toBe(before);
}, 60_000);
it("--reset-keyring starts a fresh keyring under the new password and returns its recovery key", async () => {
await seed("vault pw", "lost");
keyring.writeSync({ cloud: true });
const r = await changeAllPasswords(
{ noSync: true, resetKeyring: true },
{ vault, keyring, ask: answers("vault pw"), askNew: async () => "new", say: () => {} }
);
expect(r.keyring).toBe("created");
expect(r.keyringRecoveryKey).toBeTruthy();
expect(keyring.readSync().cloud).toBe(true);
await expect(unlockKeyring(keyring.readMeta()!, { passphrase: "new" })).resolves.toBeInstanceOf(Uint8Array);
}, 60_000);
it("keeps the keyring's key in the vault, so the next run needs the vault password only", async () => {
await seed("vault pw", "keyring pw");
const first = await changeAllPasswords(
{ noSync: true },
{ vault, keyring, ask: answers("vault pw", "keyring pw"), askNew: async () => "one", say: () => {} }
);
expect(first.keyringEscrowed).toBe(true);
expect(vault.readEnvelope(keyringEscrowId(keyring.readMeta()!))).toBeTruthy();
// The keyring drifts to a passphrase nobody remembers.
const kk = await unlockKeyring(keyring.readMeta()!, { passphrase: "one" });
keyring.writeMeta(await rewrapUserKey(keyring.readMeta()!, kk, "forgotten"));
const second = await changeAllPasswords(
{ noSync: true },
{ vault, keyring, ask: answers("one"), askNew: async () => "two", say: () => {} }
);
expect(second.keyring).toBe("changed");
const opened = await openEntry(await unlockKeyring(keyring.readMeta()!, { passphrase: "two" }), keyring.find("id_ed25519")!);
expect(opened.privateKey).toBe(KEY);
}, 60_000);
it("ignores a stored key that does not open the keyring", async () => {
await seed("vault pw", "keyring pw");
const vaultKey = await unlockVault(vault.readMeta()!, "vault pw");
const stranger = await createKeyring("x");
const item = createItem("note", { name: "n", notes: JSON.stringify({ kind: "logicsrc-keyring-key", userKey: Buffer.from(stranger.userKey).toString("base64") }) });
item.id = keyringEscrowId(keyring.readMeta()!);
vault.writeEnvelope(await encryptItem(vaultKey, item, vault.readMeta()!.namespace));
expect(await readKeyringEscrow(vault, vault.readMeta()!, vaultKey, keyring, keyring.readMeta()!)).toBeUndefined();
}, 60_000);
});
/** A fake account server for email recovery: keeps S and the blob, "mails" U and one-time codes. */
function fakeRecovery() {
let enrollment: EscrowMaterial | null = null;
let otp: { code: string; used: boolean } | null = null;
const inbox: string[] = [];
const client: EmailRecoveryClient = {
label: "fake.test",
async status() {
return { enrolled: Boolean(enrollment), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5 };
},
async checkout() {
return { url: "https://pay.test/1", priceUsd: 5 };
},
async enroll(p: EscrowEnrollment) {
enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt };
inbox.push(await formatRecoveryCode(fromBase64(p.userShare)));
otp = null;
return { enrolled: true, email: "m***@example.com" };
},
async start() {
if (!enrollment) throw new EmailRecoveryError("not enrolled", 404, "not_enrolled");
otp = { code: "12345678", used: false };
return { sent: true, email: "m***@example.com" };
},
async claim(code: string) {
if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code");
otp.used = true;
return enrollment!;
},
async disable() {
enrollment = null;
return { disabled: true };
}
};
return { client, inbox };
}
describe("logicsrc passwd --email", () => {
async function enrolled(vaultPassword: string, keyringPassword: string) {
const seeded = await seed(vaultPassword, keyringPassword);
const server = fakeRecovery();
await enrollEmailRecovery(server.client, vault.readMeta()!, await unlockVault(vault.readMeta()!, vaultPassword));
return { ...seeded, server };
}
it("with every password lost: the emailed codes open the vault, the keyring is reset and refilled from ~/.ssh", async () => {
const { server, vaultRecovery } = await enrolled("lost vault pw", "lost keyring pw");
const sshDir = join(dir, "ssh");
mkdirSync(sshDir);
writeFileSync(join(sshDir, "id_ed25519"), KEY);
writeFileSync(join(sshDir, "id_ed25519.pub"), `${PUB}\n`);
const said: string[] = [];
const r = await changeAllPasswords(
{ noSync: true, email: true },
{
vault,
keyring,
sshDir,
recovery: () => server.client,
// recovery code, one-time code, then Enter twice: keyring passphrase and recovery key both lost
ask: answers(server.inbox[0]!, "12345678", "", ""),
askNew: async () => "one password",
say: (l) => said.push(l)
}
);
expect(r).toMatchObject({ vault: "changed", keyring: "created", keyringEscrowed: true, emailRearmed: true, keysReimported: ["id_ed25519"], keysLost: [] });
await expect(unlockVault(vault.readMeta()!, "one password")).resolves.toBeInstanceOf(Uint8Array);
await expect(unlockVault(vault.readMeta()!, "lost vault pw")).rejects.toThrow();
// A new offline recovery key; the old one is dead.
await expect(unlockWithRecoveryKey(vault.readMeta()!, r.vaultRecoveryKey!)).resolves.toBeInstanceOf(Uint8Array);
await expect(unlockWithRecoveryKey(vault.readMeta()!, vaultRecovery)).rejects.toThrow();
// The key file from disk is back in the keyring, under the one password.
const kk = await unlockKeyring(keyring.readMeta()!, { passphrase: "one password" });
expect((await openEntry(kk, keyring.find("id_ed25519")!)).privateKey).toBe(KEY);
// Email recovery was re-armed with a new code.
expect(server.inbox).toHaveLength(2);
expect(said.join("\n")).toMatch(/old keyring is kept at/);
}, 60_000);
it("the second time asks for nothing but the two emailed codes: the keyring opens from the vault", async () => {
const { server } = await enrolled("vault pw", "keyring pw");
await changeAllPasswords(
{ noSync: true },
{ vault, keyring, ask: answers("vault pw", "keyring pw"), askNew: async () => "first", say: () => {} }
);
const r = await changeAllPasswords(
{ noSync: true, email: true },
{ vault, keyring, recovery: () => server.client, ask: answers(server.inbox[0]!, "12345678"), askNew: async () => "second", say: () => {} }
);
expect(r).toMatchObject({ vault: "changed", keyring: "changed", keysReimported: [] });
const kk = await unlockKeyring(keyring.readMeta()!, { passphrase: "second" });
expect((await openEntry(kk, keyring.find("id_ed25519")!)).privateKey).toBe(KEY);
}, 60_000);
it("reports a key that is not on this machine's disk as lost from the new keyring", async () => {
const { server } = await enrolled("a", "b");
const r = await changeAllPasswords(
{ noSync: true, email: true },
{ vault, keyring, sshDir: join(dir, "nowhere"), recovery: () => server.client, ask: answers(server.inbox[0]!, "12345678", "", ""), askNew: async () => "n", say: () => {} }
);
expect(r.keysLost).toEqual(["id_ed25519"]);
expect(r.keysReimported).toEqual([]);
}, 60_000);
it("changes nothing on a wrong one-time code", async () => {
const { server } = await enrolled("a", "b");
const before = JSON.stringify(vault.readMeta());
await expect(
changeAllPasswords(
{ noSync: true, email: true },
{ vault, keyring, recovery: () => server.client, ask: answers(server.inbox[0]!, "00000000"), askNew: async () => "n", say: () => {} }
)
).rejects.toThrow(/one-time code/);
expect(JSON.stringify(vault.readMeta())).toBe(before);
}, 60_000);
it("a failed push to the account does not undo the reset; it says what to run", async () => {
const { server } = await enrolled("a", "b");
const said: string[] = [];
const broken = () => ({ label: "down" }) as never;
const r = await changeAllPasswords(
{ email: true },
{ vault, keyring, sshDir: join(dir, "nowhere"), recovery: () => server.client, vaultRemote: broken, remote: () => undefined, ask: answers(server.inbox[0]!, "12345678", "", ""), askNew: async () => "n", say: (l) => said.push(l) }
);
expect(r.vault).toBe("changed");
expect(r.vaultSynced).toBe(false);
expect(said.join("\n")).toMatch(/Could not read the account's vault first/);
expect(said.join("\n")).toMatch(/Vault sync skipped\. Run: logicsrc vault sync/);
await expect(unlockVault(vault.readMeta()!, "n")).resolves.toBeInstanceOf(Uint8Array);
}, 60_000);
it("needs a signed-in account", async () => {
await seed("a", "b");
await expect(
changeAllPasswords({ noSync: true, email: true }, { vault, keyring, recovery: () => undefined, ask: answers(), askNew: async () => "n", say: () => {} })
).rejects.toThrow(/logicsrc login/);
}, 60_000);
});
/** The account's copy of the vault, in memory (the shape of opencreds' own sync test remote). */
function fakeVaultAccount() {
let held: RemoteVault | null = null;
const rows = new Map<string, { envelope: string | null; revision: number; seq: number }>();
let seq = 0;
const snapshot = (): RemoteVault | null => (held ? JSON.parse(JSON.stringify(held)) : null);
const item = (id: string): RemoteItem => {
const r = rows.get(id);
if (!r) return { id, envelope: null, revision: 0, seq: 0 };
return { id, envelope: r.envelope ? { ...JSON.parse(r.envelope), revision: r.revision } : null, revision: r.revision, seq: r.seq };
};
const remote: SyncRemote = {
label: "test-account",
async getVault() {
return snapshot();
},
async putMeta(meta, baseRevision) {
const current = held?.metaRevision ?? 0;
if (current !== baseRevision) return { ok: false, vault: snapshot() };
held = { meta: JSON.parse(JSON.stringify(meta)), metaRevision: current + 1, folders: held?.folders ?? null };
return { ok: true, revision: current + 1 };
},
async putFolders(blob, baseRevision) {
if (!held) return { ok: false, vault: null };
const current = held.folders?.revision ?? 0;
if (current !== baseRevision) return { ok: false, vault: snapshot() };
held.folders = { ...blob, revision: current + 1 };
return { ok: true, revision: current + 1 };
},
async listItems(since) {
const items = [...rows.keys()].map(item).filter((i) => i.seq >= since).sort((a, b) => a.seq - b.seq);
return { items, cursor: items.reduce((m, i) => Math.max(m, i.seq), since) };
},
async putItems(changes) {
const applied: Array<{ id: string; revision: number; seq: number }> = [];
const conflicts: RemoteItem[] = [];
for (const c of changes) {
const current = rows.get(c.id)?.revision ?? 0;
if (current !== c.baseRevision || (c.baseRevision > 0 && !rows.has(c.id))) {
conflicts.push(item(c.id));
continue;
}
const { revision: _r, ...rest } = c.envelope ?? ({} as Envelope);
rows.set(c.id, { envelope: c.envelope ? JSON.stringify(rest) : null, revision: current + 1, seq: ++seq });
applied.push({ id: c.id, revision: current + 1, seq });
}
return { applied, conflicts };
},
async reset() {
held = null;
rows.clear();
}
};
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<string, string>();
const state = { enrolls: 0, polls: 0, approveAfterPolls: 2 };
const client: EmailRecoveryClient = {
label: "fake.test",
async status() {
return { enrolled: Boolean(enrollment), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5, assisted: Boolean(enrollment?.assisted), stepupMethods: { passkey: true, coinpay: false } };
},
async checkout() {
return { url: "https://pay.test/1", priceUsd: 5 };
},
async enroll(p: EscrowEnrollment) {
state.enrolls++;
enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt, assisted: p.assisted === true, userShare: p.assisted ? p.userShare : undefined };
otp = null;
return { enrolled: true, email: "m***@example.com", assisted: p.assisted === true };
},
async start() {
otp = { code: "12345678", used: false };
return { sent: true, email: "m***@example.com" };
},
async claim(code: string, stepupId?: string) {
if (!stepupId || stepups.get(stepupId) !== "approved") throw new EmailRecoveryError("Confirm the recovery in your browser first", 403, "stepup_required");
if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code");
otp.used = true;
stepups.set(stepupId, "used");
const { assisted: _a, ...material } = enrollment!;
return { ...material };
},
async stepup() {
stepups.set("su_1", "pending");
return { id: "su_1", url: "https://fake.test/recover/confirm/su_1", expiresIn: 600 };
},
async stepupStatus(id: string) {
// The person confirms in the browser a moment later.
if (++state.polls >= state.approveAfterPolls && stepups.get(id) === "pending") stepups.set(id, "approved");
return { status: stepups.get(id) ?? "expired" };
},
async disable() {
enrollment = null;
return { disabled: true };
}
};
return { client, state, assisted: () => Boolean(enrollment?.assisted) };
}
describe("logicsrc passwd --email with assisted recovery", () => {
it("asks for no enrollment-email code: a browser confirmation and the one-time code are enough", async () => {
await seed("lost", "also lost");
const server = fakeAssistedRecovery();
await enrollEmailRecovery(server.client, vault.readMeta()!, await unlockVault(vault.readMeta()!, "lost"), { assisted: true });
const said: string[] = [];
const r = await changeAllPasswords(
{ noSync: true, email: true },
{
vault,
keyring,
sshDir: join(dir, "nowhere"),
recovery: () => server.client,
sleep: async () => {},
// Only the one-time code, then Enter twice for the lost keyring. No recovery code prompt.
ask: answers("12345678", "", ""),
askNew: async () => "one password",
say: (l) => said.push(l)
}
);
expect(r).toMatchObject({ vault: "changed", keyring: "created", emailRearmed: true, assistedRecovery: true });
await expect(unlockVault(vault.readMeta()!, "one password")).resolves.toBeInstanceOf(Uint8Array);
expect(said.join("\n")).toMatch(/https:\/\/fake\.test\/recover\/confirm\/su_1/);
expect(said.join("\n")).not.toMatch(/enrollment email|email-recovery code/);
// Re-armed the same way: still assisted.
expect(server.state.enrolls).toBe(2);
expect(server.assisted()).toBe(true);
}, 60_000);
it("gives up cleanly, changing nothing, when the link is never confirmed", async () => {
await seed("lost", "also lost");
const server = fakeAssistedRecovery();
await enrollEmailRecovery(server.client, vault.readMeta()!, await unlockVault(vault.readMeta()!, "lost"), { assisted: true });
server.state.approveAfterPolls = Number.POSITIVE_INFINITY;
const before = JSON.stringify(vault.readMeta());
let polls = 0;
const realNow = Date.now;
await expect(
changeAllPasswords(
{ noSync: true, email: true },
{
vault,
keyring,
recovery: () => server.client,
// Each wait jumps the clock past the link's lifetime.
sleep: async () => {
if (++polls > 1) Date.now = () => realNow() + 11 * 60 * 1000;
},
ask: answers(),
askNew: async () => "n",
say: () => {}
}
).finally(() => {
Date.now = realNow;
})
).rejects.toThrow(/expired before it was confirmed/);
expect(JSON.stringify(vault.readMeta())).toBe(before);
}, 60_000);
});
describe("logicsrc passwd across machines", () => {
it("an email reset on a machine that is behind the account still wins everywhere", async () => {
const account = fakeVaultAccount();
const recovery = fakeRecovery();
// Machine A makes the vault, turns email recovery on, and syncs.
const created = await createVault("original");
vault.writeMeta(created.meta);
await enrollEmailRecovery(recovery.client, created.meta, created.userKey);
await pushVault(vault, account.remote, created.userKey);
// Machine B gets it, then falls behind: A changes the password again.
const b = createVaultStore(join(dir, "vault-b"));
const bKeyring = new KeyringStore(join(dir, "keyring-b"));
await pullVault(b, account.remote);
await changeAllPasswords(
{},
{ vault, keyring, vaultRemote: () => account.remote, remote: () => undefined, ask: answers("original"), askNew: async () => "set on A", say: () => {} }
);
await expect(unlockVault(account.meta()!, "set on A")).resolves.toBeInstanceOf(Uint8Array);
// B knows no password at all and resets by email.
const r = await changeAllPasswords(
{ email: true },
{
vault: b,
keyring: bKeyring,
sshDir: join(dir, "nowhere"),
recovery: () => recovery.client,
vaultRemote: () => account.remote,
remote: () => undefined,
ask: answers(recovery.inbox[0]!, "12345678"),
askNew: async () => "set on B",
say: () => {}
}
);
expect(r).toMatchObject({ vault: "changed", vaultSynced: true, keyring: "created", keyringEscrowed: true });
// B, the account, and then A after its next sync all open with B's password.
await expect(unlockVault(b.readMeta()!, "set on B")).resolves.toBeInstanceOf(Uint8Array);
await expect(unlockVault(account.meta()!, "set on B")).resolves.toBeInstanceOf(Uint8Array);
await expect(unlockVault(account.meta()!, "set on A")).rejects.toThrow();
await pullVault(vault, account.remote);
await expect(unlockVault(vault.readMeta()!, "set on B")).resolves.toBeInstanceOf(Uint8Array);
// The keyring's key went to the account inside the vault, as ciphertext.
expect(account.has(keyringEscrowId(bKeyring.readMeta()!))).toBe(true);
}, 90_000);
});