logicsrc/packages/cli/src/passwd.ts
Anthony Ettinger cb0a938e89
logicsrc passwd: one password for the vault and the SSH keyring (#300)
* feat(cli): logicsrc passwd: one password for the vault and the SSH keyring

The personal vault and the keyring each had their own password, so the
keyring prompt ("Keyring passphrase for id_ed25519") asked for a secret
nobody remembered. `logicsrc passwd` opens both (current password, or the
recovery key; it tries the vault password on the keyring first), asks for
one new password twice, and re-wraps both user keys under it. Not one item
is re-encrypted; recovery keys keep working. Nothing is written until both
stores are open.

The vault sync already follows a password change. The keyring sync compares
the wrapped key, so the account copy is replaced (the `keyring sync
--use-local` path). --reset-keyring starts a fresh keyring when its
passphrase and recovery key are both lost.

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

* passwd: LOGICSRC_NEW_PASSWORD, so one script asks once

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

* passwd: audit the re-wrap as vault.rekey

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 06:36:54 -08:00

161 lines
6.7 KiB
TypeScript

import type { Command } from "commander";
import {
auditEvent,
createVaultStore,
promptNewSecret,
promptSecret,
rewrapUserKey,
unlockVault,
unlockWithRecoveryKey,
type VaultMeta,
type VaultStore
} from "@logicsrc/opencreds";
import { KeyringStore, createKeyring, unlockKeyring } from "./keyring.js";
import { accountKeyringRemote, syncKeyring, type KeyringRemote } from "./keyring-sync.js";
/**
* `logicsrc passwd`: one password for the personal vault and the SSH keyring.
*
* Both are OpenCreds vaults: a random user key wrapped under a password. A
* password change re-wraps the same user key, so not one stored item is
* re-encrypted. The vault's sync follows a password change on its own (it
* identifies a vault by createdAt and adopts a newer meta revision). The
* 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.
*/
export interface PasswdDeps {
vault?: VaultStore;
keyring?: KeyringStore;
remote?: () => KeyringRemote | undefined;
ask?: (label: string) => Promise<string>;
askNew?: (label: string, repeat: string) => Promise<string>;
say?: (line: string) => void;
}
export interface PasswdResult {
vault: "changed" | "missing";
keyring: "changed" | "created" | "missing";
keyringRecoveryKey?: string;
keyringSynced: boolean;
}
async function openVault(meta: VaultMeta, ask: (l: string) => Promise<string>): Promise<{ userKey: Uint8Array; password?: string }> {
const password = await ask("Current vault password (Enter to use the recovery key instead): ");
if (password) {
try {
return { userKey: await unlockVault(meta, password), password };
} catch {
throw new Error("Wrong vault password. Run again and press Enter at the prompt to use the recovery key.");
}
}
const recoveryKey = await ask("Vault recovery key: ");
try {
return { userKey: await unlockWithRecoveryKey(meta, recoveryKey) };
} catch {
throw new Error("That recovery key does not open the vault.");
}
}
async function openKeyring(
meta: VaultMeta,
tryFirst: string | undefined,
ask: (l: string) => Promise<string>
): Promise<Uint8Array> {
if (tryFirst) {
try {
return await unlockKeyring(meta, { passphrase: tryFirst });
} catch {
/* the keyring had its own passphrase; ask for it */
}
}
const passphrase = await ask("Current keyring passphrase (Enter to use the keyring recovery key): ");
if (passphrase) return unlockKeyring(meta, { passphrase });
const recoveryKey = await ask("Keyring recovery key: ");
return unlockKeyring(meta, { recoveryKey });
}
export async function changeAllPasswords(opts: { resetKeyring?: boolean; noSync?: boolean }, deps: PasswdDeps = {}): Promise<PasswdResult> {
const vault = deps.vault ?? createVaultStore();
const keyring = deps.keyring ?? new KeyringStore();
const ask = deps.ask ?? ((l: string) => promptSecret(l));
// LOGICSRC_NEW_PASSWORD lets one script ask once and reuse the answer (for an SSH key too).
const askNew =
deps.askNew ?? (async (l: string, r: string) => process.env.LOGICSRC_NEW_PASSWORD || promptNewSecret(l, r));
const say = deps.say ?? ((line: string) => console.error(line));
const remoteFor = deps.remote ?? accountKeyringRemote;
// 1. Open what exists, before asking for anything new.
const vaultMeta = vault.readMeta();
const opened = vaultMeta ? await openVault(vaultMeta, ask) : undefined;
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);
// 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 };
if (vaultMeta && opened) {
vault.writeMeta(await rewrapUserKey(vaultMeta, opened.userKey, password));
vault.appendAudit(auditEvent({ action: "vault.rekey", namespace: vaultMeta.namespace }));
result.vault = "changed";
}
if (keyringMeta && keyringKey) {
keyring.writeMeta(await rewrapUserKey(keyringMeta, keyringKey, password));
result.keyring = "changed";
} else if (opts.resetKeyring || !keyringMeta) {
if (keyringMeta) keyring.backup();
const created = await createKeyring(password);
keyring.writeMeta(created.meta);
result.keyring = "created";
result.keyringRecoveryKey = created.recoveryKey;
}
// 4. Replace the account's keyring copy, which still carries the old wrap.
if (result.keyring !== "missing" && !opts.noSync && keyring.readSync().cloud) {
const remote = remoteFor();
if (remote) {
try {
await syncKeyring(keyring, remote, "use-local");
result.keyringSynced = true;
} catch (e) {
say(`Keyring sync skipped: ${(e as Error).message}. Run: logicsrc keyring sync --use-local`);
}
}
}
return result;
}
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("--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`
)
.action(async (opts: { resetKeyring?: boolean; sync?: boolean }) => {
try {
const r = await changeAllPasswords({ resetKeyring: opts.resetKeyring, noSync: opts.sync === false });
console.error(`Vault: ${r.vault}. Keyring: ${r.keyring}${r.keyringSynced ? " (account copy replaced)" : ""}.`);
if (r.keyringRecoveryKey) {
console.error(`KEYRING RECOVERY KEY (shown once, store it offline):\n ${r.keyringRecoveryKey}`);
}
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);
process.exitCode = 1;
}
});
}