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>
This commit is contained in:
Anthony Ettinger 2026-12-02 06:36:54 -08:00 • committed by GitHub
parent 267973f439
commit cb0a938e89
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 255 additions and 0 deletions

View file

@ -37,6 +37,7 @@ import {
} from "./teams.js";
import { registerKeysCommands } from "./keys.js";
import { registerKeyringCommands } from "./keyring-cmd.js";
import { registerPasswdCommand } from "./passwd.js";
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
import { credentialsRotateAction } from "./rotate.js";
import { teamsQueueDueAction, teamsRotateFromQueue, teamsRotateKeysAction, teamsRotationAction, teamsRotationApproveAction, teamsRotationSetAction } from "./rotate-keys.js";
@ -1460,6 +1461,7 @@ async function runYoloArcade(game: string, repo?: string) {
registerKeysCommands(program);
registerKeyringCommands(program);
registerPasswdCommand(program);
// LOGICSRC_API_KEY: prepare the key's identity (first use registers a machine
// key's own public key) before any command that talks to the credentials app.

View file

@ -0,0 +1,92 @@
import { mkdtempSync, rmSync } 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 { KeyringStore, createKeyring, openEntry, sealEntry, unlockKeyring } from "./keyring.js";
import { changeAllPasswords } 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");
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();
await expect(unlockKeyring(keyring.readMeta()!, { passphrase: "new" })).resolves.toBeInstanceOf(Uint8Array);
}, 60_000);
});

161
packages/cli/src/passwd.ts Normal file
View file

@ -0,0 +1,161 @@
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;
}
});
}