From ef965b0aaae414c164984c8d462e935054d14eca Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Wed, 2 Dec 2026 21:42:04 -0800 Subject: [PATCH] feat(passwd): `logicsrc passwd --email` resets the vault and the keyring with one password (#302) Email recovery reset the vault only. The SSH keyring kept its old passphrase, so someone who had forgotten everything recovered the vault and was then refused by `keyring restore` ("Wrong keyring passphrase"). - `logicsrc passwd --email`: opens the vault with the two emailed codes, then puts the vault and the keyring under one new password. New vault recovery key, email recovery re-armed, same end state as `vault recover --email`. - Every `passwd` run stores the keyring's user key as an item in the vault (found by a stable id, verified against a keyring entry before use), so the vault's way back in is the keyring's too and nobody is asked a second secret. - A keyring nothing opens is set aside (kept as keyring.bak-NNN) and started fresh; keys whose files are still under ~/.ssh with the same fingerprint are put back, the rest are named. - The re-arm email after a recovery had the first-time wording ("run logicsrc vault recover --email"), which read as an instruction to recover again: three recoveries in five minutes on one account. It now says the recovery is complete and there is nothing to do. The CLI says so too. Co-authored-by: Claude Fable 5.2 --- apps/pwa/src/lib/vault-recovery.mjs | 35 ++- apps/pwa/test/vault-recovery.test.mjs | 20 ++ docs/opencreds/cli.md | 1 + packages/cli/src/passwd.test.ts | 180 +++++++++++++++- packages/cli/src/passwd.ts | 298 ++++++++++++++++++++++++-- packages/opencreds/src/commands.ts | 3 +- 6 files changed, 517 insertions(+), 20 deletions(-) diff --git a/apps/pwa/src/lib/vault-recovery.mjs b/apps/pwa/src/lib/vault-recovery.mjs index e1368061..13587b77 100644 --- a/apps/pwa/src/lib/vault-recovery.mjs +++ b/apps/pwa/src/lib/vault-recovery.mjs @@ -287,7 +287,38 @@ export function parseEnrollment(body) { return { escrowBlob: body.escrowBlob, escrowIv: body.escrowIv, serverShare, userShare, vaultCreatedAt: createdAt }; } -export function enrollmentEmail(code) { +/** A recovery that finished in the last half hour: this enrollment is the automatic re-arm after it. */ +const REARM_WINDOW_MS = 30 * 60 * 1000; + +async function followsRecovery(userId, now) { + const last = await get(`SELECT action, created_at FROM vault_recovery_audit WHERE user_id = ? ORDER BY created_at DESC LIMIT 1`, [userId]).catch(() => null); + return Boolean(last && last.action === "claim" && now - Number(last.created_at) <= REARM_WINDOW_MS); +} + +/** + * The mail that carries U. After a recovery the same mail read as "run recover + * --email", and people ran it again, and got another: so the re-arm says the + * recovery is finished and there is nothing to do. + */ +export function enrollmentEmail(code, { afterRecovery = false } = {}) { + if (afterRecovery) { + return { + subject: "Your LogicSRC vault email-recovery code was replaced — recovery complete, nothing to do", + text: + "Your LogicSRC personal vault was just recovered by email and has a new master password. " + + "You are done: there is nothing to run now.\n\n" + + "Using a recovery code spends it, so here is the replacement, for the next time you ever need it:\n\n" + + ` ${code}\n\n` + + "Keep this email and delete the older recovery-code emails: those codes no longer work.\n\n" + + "Only if you lose your master password again, run `logicsrc passwd --email` (or `logicsrc vault recover --email`) " + + "and type this code when it asks.\n\n" + + "LogicSRC does not store this code. It is one half of the key to your vault: the other half is on our " + + "server, and neither half opens anything alone. Someone who has this email AND can sign in to your " + + "LogicSRC account could recover your vault, so keep this mailbox secure.\n\n" + + "If you did not just recover your vault, someone else did: sign in, turn email recovery off (Settings, or " + + "`logicsrc vault recovery disable`), change your password and secure this mailbox.", + }; + } return { subject: "Your LogicSRC vault email-recovery code — keep this email", text: @@ -320,7 +351,7 @@ export async function enroll(user, parsed, ctx = {}, now = Date.now()) { ); let sent = false; try { - const mail = enrollmentEmail(renderRecoveryCode(parsed.userShare)); + const mail = enrollmentEmail(renderRecoveryCode(parsed.userShare), { afterRecovery: await followsRecovery(user.id, now) }); sent = await sendMail(user.email, mail.subject, mail.text); } finally { parsed.userShare.fill(0); diff --git a/apps/pwa/test/vault-recovery.test.mjs b/apps/pwa/test/vault-recovery.test.mjs index a1ebe12e..a4a344f4 100644 --- a/apps/pwa/test/vault-recovery.test.mjs +++ b/apps/pwa/test/vault-recovery.test.mjs @@ -360,3 +360,23 @@ test("the Settings card: a Buy button before the purchase, the CLI hint after, 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"); +}); diff --git a/docs/opencreds/cli.md b/docs/opencreds/cli.md index 4f4b915c..d437f202 100644 --- a/docs/opencreds/cli.md +++ b/docs/opencreds/cli.md @@ -60,6 +60,7 @@ logicsrc vault recovery buy # CoinPay checkout link ($5, lifetime) logicsrc vault recovery enable # enroll; emails a recovery code to keep logicsrc vault recovery disable # server deletes its escrow share and blob logicsrc vault recover --email # recovery code + fresh one-time code, then a new password +logicsrc passwd --email # the same two codes, then ONE new password for the vault and the SSH keyring ``` An opt-in, paid account feature; the standalone `opencreds` binary has no diff --git a/packages/cli/src/passwd.test.ts b/packages/cli/src/passwd.test.ts index 23ab4bf2..6c81fd97 100644 --- a/packages/cli/src/passwd.test.ts +++ b/packages/cli/src/passwd.test.ts @@ -1,10 +1,26 @@ -import { mkdtempSync, rmSync } from "node:fs"; +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 { createVault, createVaultStore, unlockVault, type VaultStore } from "@logicsrc/opencreds"; +import { + EmailRecoveryError, + createItem, + createVault, + createVaultStore, + encryptItem, + enrollEmailRecovery, + formatRecoveryCode, + fromBase64, + rewrapUserKey, + unlockVault, + unlockWithRecoveryKey, + type EmailRecoveryClient, + type EscrowEnrollment, + type EscrowMaterial, + type VaultStore +} from "@logicsrc/opencreds"; import { KeyringStore, createKeyring, openEntry, sealEntry, unlockKeyring } from "./keyring.js"; -import { changeAllPasswords } from "./passwd.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"; @@ -91,4 +107,162 @@ describe("logicsrc passwd", () => { 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("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); }); diff --git a/packages/cli/src/passwd.ts b/packages/cli/src/passwd.ts index 36446f36..f290e8f7 100644 --- a/packages/cli/src/passwd.ts +++ b/packages/cli/src/passwd.ts @@ -1,17 +1,32 @@ +import { existsSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; import type { Command } from "commander"; import { auditEvent, + createItem, createVaultStore, + decryptItem, + encryptItem, + enrollEmailRecovery, + fromBase64, + parseRecoveryCode, promptNewSecret, promptSecret, + recoverUserKeyByEmail, + resetRecoveryKey, rewrapUserKey, + stableUuid, + toBase64, unlockVault, unlockWithRecoveryKey, + type EmailRecoveryClient, type VaultMeta, type VaultStore } from "@logicsrc/opencreds"; -import { KeyringStore, createKeyring, unlockKeyring } from "./keyring.js"; +import { KeyringStore, createKeyring, fingerprintOf, openEntry, sealEntry, unlockKeyring, type KeyringEntry } from "./keyring.js"; import { accountKeyringRemote, syncKeyring, type KeyringRemote } from "./keyring-sync.js"; +import { accountRecoveryFor } from "./vault-sync.js"; /** * `logicsrc passwd`: one password for the personal vault and the SSH keyring. @@ -23,12 +38,78 @@ import { accountKeyringRemote, syncKeyring, type KeyringRemote } from "./keyring * keyring's sync compares the wrapped key itself, so after a re-wrap the * account copy is replaced (the `keyring sync --use-local` path): its entries * are the same ciphertext under the same user key. + * + * `--email` is the way back in with nothing remembered: the vault opens with the + * two emailed codes (email recovery), and the keyring opens with its own key, + * which every `passwd` run stores as an item inside the vault (the escrow below). + * A keyring nothing can open is set aside and started fresh, and any of its keys + * still on disk under ~/.ssh are put back into the new one. */ +/** The vault item that holds the keyring's user key. Found by id, never by a scan. */ +export const KEYRING_ESCROW_NAME = "LogicSRC keyring key (keeps `logicsrc passwd --email` able to open the keyring)"; +const ESCROW_KIND = "logicsrc-keyring-key"; + +export function keyringEscrowId(keyringMeta: VaultMeta): string { + return stableUuid("logicsrc-keyring-escrow", keyringMeta.createdAt ?? keyringMeta.kdfSalt); +} + +/** Does this key open the keyring? True when there is no entry to try it on (nothing to lose). */ +async function opensKeyring(keyring: KeyringStore, key: Uint8Array): Promise { + const probe = keyring.entries().find((e) => e.envelope); + if (!probe) return true; + try { + await openEntry(key, probe); + return true; + } catch { + return false; + } +} + +/** The keyring's user key, from the copy kept in the vault. Undefined when there is none or it is for another keyring. */ +export async function readKeyringEscrow( + vault: VaultStore, + vaultMeta: VaultMeta, + vaultKey: Uint8Array, + keyring: KeyringStore, + keyringMeta: VaultMeta +): Promise { + const envelope = vault.readEnvelope(keyringEscrowId(keyringMeta)); + if (!envelope || envelope.deletedAt) return undefined; + try { + const item = await decryptItem(vaultKey, envelope, vaultMeta.namespace); + const body = JSON.parse(item.notes || "{}") as { kind?: string; userKey?: string }; + if (body.kind !== ESCROW_KIND || !body.userKey) return undefined; + const key = fromBase64(body.userKey); + return (await opensKeyring(keyring, key)) ? key : undefined; + } catch { + return undefined; + } +} + +export async function writeKeyringEscrow( + vault: VaultStore, + vaultMeta: VaultMeta, + vaultKey: Uint8Array, + keyringMeta: VaultMeta, + keyringKey: Uint8Array +): Promise { + const item = createItem("note", { + name: KEYRING_ESCROW_NAME, + notes: JSON.stringify({ kind: ESCROW_KIND, v: 1, keyringCreatedAt: keyringMeta.createdAt ?? null, userKey: toBase64(keyringKey) }) + }); + item.id = keyringEscrowId(keyringMeta); + vault.writeEnvelope(await encryptItem(vaultKey, item, vaultMeta.namespace)); +} + export interface PasswdDeps { vault?: VaultStore; keyring?: KeyringStore; remote?: () => KeyringRemote | undefined; + /** Email recovery for the vault (`--email`). */ + recovery?: (store: VaultStore) => EmailRecoveryClient | undefined; + /** Where the keyring's key files live on disk, to refill a keyring that had to be reset. */ + sshDir?: string; ask?: (label: string) => Promise; askNew?: (label: string, repeat: string) => Promise; say?: (line: string) => void; @@ -39,6 +120,95 @@ export interface PasswdResult { keyring: "changed" | "created" | "missing"; keyringRecoveryKey?: string; keyringSynced: boolean; + /** `--email`: the vault's new offline recovery key (the old one stops working). */ + vaultRecoveryKey?: string; + /** `--email`: whether email recovery was re-armed with a new code, and where it was sent. */ + emailRearmed?: boolean; + emailRearmedTo?: string; + emailRearmError?: string; + /** The keyring's key is now kept in the vault, so `passwd --email` can open it next time. */ + keyringEscrowed: boolean; + /** After a reset: keys put back from disk, and keys that were only in the old keyring. */ + keysReimported: string[]; + keysLost: string[]; +} + +/** Open the vault with the two emailed codes. Nothing is written here. */ +async function openVaultByEmail( + vault: VaultStore, + meta: VaultMeta, + client: EmailRecoveryClient, + ask: (l: string) => Promise, + say: (line: string) => void +): Promise { + say('Email reset needs the recovery code from your newest "Your LogicSRC vault email-recovery code" email.'); + const userShare = await parseRecoveryCode(await ask("Recovery code from the enrollment email: ")); + try { + const started = await client.start(); + say(`A one-time code was emailed to ${started.email ?? "your account email"}. It expires in 15 minutes.`); + const code = (await ask("One-time code from the email just sent: ")).replace(/\s+/g, ""); + const material = await client.claim(code); + return await recoverUserKeyByEmail({ meta, material, userShare, envelopes: vault.listEnvelopes() }); + } finally { + userShare.fill(0); + } +} + +/** With `--email` the old keyring passphrase may be gone too: every prompt can be skipped, and skipping all of them means a reset. */ +async function openKeyringOrGiveUp(meta: VaultMeta, ask: (l: string) => Promise, say: (line: string) => void): Promise { + say("The keyring's key is not in your vault yet, so it needs its own passphrase or recovery key this once."); + const passphrase = await ask("Current keyring passphrase (Enter if you lost it): "); + if (passphrase) { + try { + return await unlockKeyring(meta, { passphrase }); + } catch { + say("That is not the keyring passphrase."); + } + } + const recoveryKey = await ask("Keyring recovery key (Enter if you lost it too): "); + if (recoveryKey) { + try { + return await unlockKeyring(meta, { recoveryKey }); + } catch { + say("That recovery key does not open the keyring."); + } + } + return undefined; +} + +/** Put back, from disk, the keys a reset keyring used to hold: same file name, same fingerprint. */ +async function reimportFromDisk( + keyring: KeyringStore, + key: Uint8Array, + previous: KeyringEntry[], + sshDir: string +): Promise<{ reimported: string[]; lost: string[] }> { + const reimported: string[] = []; + const lost: string[] = []; + for (const entry of previous) { + try { + const file = join(sshDir, entry.filename); + const publicKey = existsSync(`${file}.pub`) ? readFileSync(`${file}.pub`, "utf8").trim() : ""; + if (!existsSync(file) || !publicKey || !entry.fingerprint || fingerprintOf(publicKey) !== entry.fingerprint) { + lost.push(entry.name); + continue; + } + keyring.write( + await sealEntry(key, { + name: entry.name, + privateKey: readFileSync(file, "utf8"), + publicKey, + type: entry.type, + filename: entry.filename, + comment: entry.comment + }) + ); + reimported.push(entry.name); + } catch { + lost.push(entry.name); + } + } + return { reimported, lost }; } async function openVault(meta: VaultMeta, ask: (l: string) => Promise): Promise<{ userKey: Uint8Array; password?: string }> { @@ -76,7 +246,10 @@ async function openKeyring( return unlockKeyring(meta, { recoveryKey }); } -export async function changeAllPasswords(opts: { resetKeyring?: boolean; noSync?: boolean }, deps: PasswdDeps = {}): Promise { +export async function changeAllPasswords( + opts: { resetKeyring?: boolean; noSync?: boolean; email?: boolean }, + deps: PasswdDeps = {} +): Promise { const vault = deps.vault ?? createVaultStore(); const keyring = deps.keyring ?? new KeyringStore(); const ask = deps.ask ?? ((l: string) => promptSecret(l)); @@ -88,37 +261,112 @@ export async function changeAllPasswords(opts: { resetKeyring?: boolean; noSync? // 1. Open what exists, before asking for anything new. const vaultMeta = vault.readMeta(); - const opened = vaultMeta ? await openVault(vaultMeta, ask) : undefined; + let opened: { userKey: Uint8Array; password?: string } | undefined; + let recoveryClient: EmailRecoveryClient | undefined; + if (opts.email) { + if (!vaultMeta) throw new Error("No personal vault on this machine. Run `logicsrc login` and `logicsrc vault sync` first, then this again."); + recoveryClient = (deps.recovery ?? accountRecoveryFor)(vault); + if (!recoveryClient) throw new Error("Email reset works through your account. Run `logicsrc login` first, then this again."); + opened = { userKey: await openVaultByEmail(vault, vaultMeta, recoveryClient, ask, say) }; + } else if (vaultMeta) { + opened = await openVault(vaultMeta, ask); + } if (!vaultMeta) say("No personal vault on this machine (logicsrc vault init / vault sync makes one); only the keyring changes."); const keyringMeta = keyring.readMeta(); let keyringKey: Uint8Array | undefined; - if (keyringMeta && !opts.resetKeyring) keyringKey = await openKeyring(keyringMeta, opened?.password, ask); + let resetKeyring = Boolean(opts.resetKeyring); + if (keyringMeta && !resetKeyring) { + // The copy in the vault first: with it nobody is asked for a second secret. + if (vaultMeta && opened) keyringKey = await readKeyringEscrow(vault, vaultMeta, opened.userKey, keyring, keyringMeta); + if (!keyringKey && opts.email) { + keyringKey = await openKeyringOrGiveUp(keyringMeta, ask, say); + if (!keyringKey) { + resetKeyring = true; + say("Nothing opens the old keyring, so it is set aside and a new one starts under the new password."); + } + } else if (!keyringKey) { + keyringKey = await openKeyring(keyringMeta, opened?.password, ask); + } + } // 2. The new password, once. const password = await askNew("New password (one for the vault and the keyring): ", "Repeat: "); if (!password) throw new Error("The password cannot be empty."); // 3. Re-wrap. Nothing is written until both are open, so a wrong answer changes nothing. - const result: PasswdResult = { vault: "missing", keyring: "missing", keyringSynced: false }; + const result: PasswdResult = { + vault: "missing", + keyring: "missing", + keyringSynced: false, + keyringEscrowed: false, + keysReimported: [], + keysLost: [] + }; + let currentVaultMeta = vaultMeta; if (vaultMeta && opened) { - vault.writeMeta(await rewrapUserKey(vaultMeta, opened.userKey, password)); - vault.appendAudit(auditEvent({ action: "vault.rekey", namespace: vaultMeta.namespace })); + let next = await rewrapUserKey(vaultMeta, opened.userKey, password); + if (opts.email) { + // The same end state as `vault recover --email`: a new offline recovery key. + const reset = await resetRecoveryKey(next, opened.userKey); + next = reset.meta; + result.vaultRecoveryKey = reset.recoveryKey; + } + vault.writeMeta(next); + currentVaultMeta = next; + vault.appendAudit( + auditEvent( + opts.email + ? { action: "vault.recovery_reset", namespace: vaultMeta.namespace, reason: "email-recovery" } + : { action: "vault.rekey", namespace: vaultMeta.namespace } + ) + ); result.vault = "changed"; } + let currentKeyringMeta: VaultMeta | undefined; if (keyringMeta && keyringKey) { - keyring.writeMeta(await rewrapUserKey(keyringMeta, keyringKey, password)); + currentKeyringMeta = await rewrapUserKey(keyringMeta, keyringKey, password); + keyring.writeMeta(currentKeyringMeta); result.keyring = "changed"; - } else if (opts.resetKeyring || !keyringMeta) { + } else if (resetKeyring || !keyringMeta) { // backup() moves the whole dir away, sync.json included: keep the cloud // setting, or the fresh keyring never replaces the account's copy. const cloud = keyringMeta ? keyring.readSync().cloud : false; - if (keyringMeta) keyring.backup(); + const previous = keyringMeta ? keyring.entries() : []; + if (keyringMeta) say(`The old keyring is kept at ${keyring.backup()}.`); const created = await createKeyring(password); keyring.writeMeta(created.meta); keyring.writeSync({ ...keyring.readSync(), cloud }); + currentKeyringMeta = created.meta; + keyringKey = created.userKey; result.keyring = "created"; result.keyringRecoveryKey = created.recoveryKey; + const refill = await reimportFromDisk(keyring, created.userKey, previous, deps.sshDir ?? join(homedir(), ".ssh")); + result.keysReimported = refill.reimported; + result.keysLost = refill.lost; + } + + // Keep the keyring's key in the vault: from now on the vault's own way back in + // (password, recovery key or email) is the keyring's too. + if (currentVaultMeta && opened && currentKeyringMeta && keyringKey) { + try { + await writeKeyringEscrow(vault, currentVaultMeta, opened.userKey, currentKeyringMeta, keyringKey); + result.keyringEscrowed = true; + } catch (e) { + say(`Could not store the keyring's key in the vault: ${(e as Error).message}`); + } + } + + // Email recovery was spent by the claim: arm it again with fresh shares. + if (opts.email && recoveryClient && currentVaultMeta && opened) { + try { + const enrolled = await enrollEmailRecovery(recoveryClient, currentVaultMeta, opened.userKey); + result.emailRearmed = Boolean(enrolled.enrolled); + result.emailRearmedTo = enrolled.email; + } catch (e) { + result.emailRearmed = false; + result.emailRearmError = (e as Error).message; + } } // 4. Replace the account's keyring copy, which still carries the old wrap. @@ -140,22 +388,44 @@ export function registerPasswdCommand(program: Command): void { program .command("passwd") .description("One password for your personal vault and SSH keyring: asks for the current ones once, then the new one.") - .option("--reset-keyring", "Start a new, empty keyring under the new password (when its passphrase and recovery key are both lost)") + .option("--email", "Forgot everything: open the vault with the codes emailed to your account, then put the vault and the keyring under one new password") + .option("--reset-keyring", "Start a new keyring under the new password (when its passphrase and recovery key are both lost)") .option("--no-sync", "Do not replace the account's keyring copy") .addHelpText( "after", ` Not one stored item is re-encrypted: each store's key is re-wrapped under the new password. Your recovery keys keep working. Other machines pick up the vault -change on their next sync; for the keyring run there: logicsrc keyring sync --use-remote` +change on their next sync; for the keyring run there: logicsrc keyring sync --use-remote + + logicsrc passwd you know the current password (or have the recovery keys) + logicsrc passwd --email you know nothing: needs \`logicsrc login\` and email recovery + turned on (logicsrc vault recovery enable) + +Each run stores the keyring's key as an item in your vault, so the next +\`passwd --email\` opens the keyring too. A keyring nothing can open is set aside +(not deleted) and started fresh; its keys still under ~/.ssh are put back.` ) - .action(async (opts: { resetKeyring?: boolean; sync?: boolean }) => { + .action(async (opts: { resetKeyring?: boolean; sync?: boolean; email?: boolean }) => { try { - const r = await changeAllPasswords({ resetKeyring: opts.resetKeyring, noSync: opts.sync === false }); + const r = await changeAllPasswords({ resetKeyring: opts.resetKeyring, noSync: opts.sync === false, email: opts.email }); console.error(`Vault: ${r.vault}. Keyring: ${r.keyring}${r.keyringSynced ? " (account copy replaced)" : ""}.`); + if (r.vaultRecoveryKey) { + console.error(`NEW VAULT RECOVERY KEY (shown once, store it offline; the old one no longer works):\n ${r.vaultRecoveryKey}`); + } if (r.keyringRecoveryKey) { console.error(`KEYRING RECOVERY KEY (shown once, store it offline):\n ${r.keyringRecoveryKey}`); } + if (r.keysReimported.length) console.error(`Put back into the keyring from ~/.ssh: ${r.keysReimported.join(", ")}.`); + if (r.keysLost.length) { + console.error(`Not on this machine's disk, so not in the new keyring: ${r.keysLost.join(", ")}. Add them where the files are: logicsrc keyring add `); + } + if (r.keyringEscrowed) console.error("The keyring's key is stored in your vault: next time `logicsrc passwd --email` opens both."); + if (r.emailRearmed) { + console.error(`Email recovery is armed again: a NEW recovery code was emailed to ${r.emailRearmedTo ?? "your account email"}. The code you just used no longer works. You are done: that email is only the replacement to keep.`); + } else if (r.emailRearmError) { + console.error(`Email recovery is OFF now and could not be re-armed (${r.emailRearmError}). Run: logicsrc vault recovery enable`); + } if (r.vault === "changed") console.error("Run `logicsrc vault sync` to send the vault change to your account."); } catch (e) { console.error((e as Error).message); diff --git a/packages/opencreds/src/commands.ts b/packages/opencreds/src/commands.ts index 9be74075..cc403e03 100644 --- a/packages/opencreds/src/commands.ts +++ b/packages/opencreds/src/commands.ts @@ -566,7 +566,8 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions if (result.reenrolled) { process.stdout.write( `Email recovery is re-armed: a NEW recovery code was emailed to ${result.reenrolledEmail}. ` + - "The code you just used no longer works.\n", + "The code you just used no longer works.\n" + + "You are done. That email is only the replacement code to keep: it does not ask you to recover again.\n", ); return; }