feat(passwd): the reset reaches every copy the account owns (#303)

An account has one personal vault and one keyring, plus a local copy on each
machine. `logicsrc passwd` (and `--email`) changed this machine and left the
rest to manual commands: `vault sync`, then `keyring sync --use-remote` on
every other machine.

- passwd pulls the account's vault first and pushes it after. Without the
  pull, a password set on another machine since the last sync won on the next
  pull ("the account's wins") and silently replaced the one just chosen. It
  also lets a freshly logged-in machine with no local vault reset by email.
- `keyring sync` takes the account's keyring without a flag in the two cases
  where nothing can be lost: the same keyring under a newer password, or a
  newer keyring that holds every key this machine has (the old one is still
  backed up). Anything else stays a question, as before.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-12-02 21:50:07 -08:00 • committed by GitHub
parent ef965b0aaa
commit f1944ac101
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 269 additions and 7 deletions

View file

@ -26,12 +26,42 @@ export interface KeyringSyncReport {
deleted: string[];
createdRemote: boolean;
adoptedRemote: boolean;
/** The account's copy was the same keyring under a newer password (`logicsrc passwd` elsewhere); its wrap was taken. */
adoptedPassword?: boolean;
/** The account's copy was a newer keyring holding every key this one had (a reset elsewhere); it replaced this one. */
adoptedReset?: boolean;
backup?: string;
}
const stamp = (e: KeyringEntry): number => Math.max(Date.parse(e.updatedAt) || 0, e.deletedAt ? Date.parse(e.deletedAt) || 0 : 0);
const sameKeyring = (a: VaultMeta, b: VaultMeta): boolean => a.kdfSalt === b.kdfSalt && a.protectedUserKey === b.protectedUserKey;
const when = (iso: string | undefined): number => Date.parse(iso ?? "") || 0;
/**
* A password change or reset on another machine (`logicsrc passwd`, `passwd --email`)
* must reach this one without a flag, or "one password" is true on one machine only.
* Two cases are safe to take from the account unasked:
* - "password": the same keyring (same createdAt), re-wrapped later. Same user key, same entries.
* - "reset": a keyring created later that already holds every key this one has, so nothing
* is lost by setting this one aside (it is still backed up).
* Anything else stays a question for a person.
*/
export function accountSupersedes(
local: VaultMeta,
remote: VaultMeta,
localEntries: KeyringEntry[],
remoteEntries: KeyringEntry[]
): "password" | "reset" | undefined {
if (local.createdAt && local.createdAt === remote.createdAt) {
return when(remote.updatedAt) > when(local.updatedAt) ? "password" : undefined;
}
if (when(remote.createdAt) <= when(local.createdAt)) return undefined;
const held = new Set(remoteEntries.filter((e) => !e.deletedAt && e.envelope).map((e) => e.fingerprint));
const live = localEntries.filter((e) => !e.deletedAt && e.envelope);
return live.every((e) => e.fingerprint && held.has(e.fingerprint)) ? "reset" : undefined;
}
export async function syncKeyring(
store: KeyringStore,
remote: KeyringRemote,
@ -52,6 +82,14 @@ export async function syncKeyring(
await remote.wipe();
remoteMeta = null;
remoteEntries = [];
} else if (accountSupersedes(localMeta, remoteMeta, store.allEntries(), remoteEntries) === "password") {
store.writeMeta(remoteMeta);
localMeta = remoteMeta;
report.adoptedPassword = true;
} else if (accountSupersedes(localMeta, remoteMeta, store.allEntries(), remoteEntries) === "reset") {
report.backup = store.backup();
localMeta = undefined;
report.adoptedReset = true;
} else {
throw new KeyringDivergedError(
`This machine's keyring and the one in your account (${remote.label}) are different keyrings (different passphrase/salt). ` +
@ -96,7 +134,8 @@ export async function syncKeyring(
export function describeKeyringSync(r: KeyringSyncReport, label: string): string {
const parts = [
r.adoptedRemote ? "took the account's keyring" : "",
r.adoptedPassword ? "took the new password set on another machine" : "",
r.adoptedReset ? "took the keyring that was reset on another machine" : r.adoptedRemote ? "took the account's keyring" : "",
r.createdRemote ? "created the account copy" : "",
r.pushed.length ? `pushed ${r.pushed.length} (${r.pushed.join(", ")})` : "",
r.pulled.length ? `pulled ${r.pulled.length} (${r.pulled.join(", ")})` : "",

View file

@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, w
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { VaultMeta } from "@logicsrc/opencreds";
import { rewrapUserKey, type VaultMeta } from "@logicsrc/opencreds";
import {
KeyringStore,
authorizedKeysLines,
@ -197,6 +197,61 @@ describe.skipIf(!hasSshKeygen)("sync", () => {
expect(a.find("id_ed25519")).toBeUndefined();
});
it("takes a password changed on another machine without a flag (same keyring, newer wrap)", async () => {
const key = throwawayKey(dir);
const account = fakeAccount();
const a = new KeyringStore(join(dir, "pw-a"));
const created = await createKeyring("old");
a.writeMeta(created.meta);
a.write(await sealEntry(created.userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey }));
await syncKeyring(a, account);
const b = new KeyringStore(join(dir, "pw-b"));
await syncKeyring(b, account);
// `logicsrc passwd` on a: re-wrap, then replace the account's copy.
const rewrapped = await rewrapUserKey(created.meta, created.userKey, "new");
a.writeMeta({ ...rewrapped, updatedAt: new Date(Date.now() + 2000).toISOString() });
await syncKeyring(a, account, "use-local");
const r = await syncKeyring(b, account);
expect(r.adoptedPassword).toBe(true);
expect(r.backup).toBeUndefined();
const bKey = await unlockKeyring(b.readMeta()!, { passphrase: "new" });
expect((await openEntry(bKey, b.get("id_ed25519"))).privateKey).toBe(key.privateKey);
});
it("takes a keyring reset on another machine when it holds every key this one has, and keeps a backup", async () => {
const key = throwawayKey(dir);
const account = fakeAccount();
const b = new KeyringStore(join(dir, "reset-b"));
const old = await createKeyring("forgotten");
b.writeMeta({ ...old.meta, createdAt: "2026-01-01T00:00:00.000Z" });
b.write(await sealEntry(old.userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey }));
// `logicsrc passwd --email` on another machine: a new keyring with the same key in it.
const fresh = await createKeyring("one password");
await account.putMeta(fresh.meta);
await account.putEntry(await sealEntry(fresh.userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey }));
const r = await syncKeyring(b, account);
expect(r.adoptedReset).toBe(true);
expect(r.backup && existsSync(r.backup)).toBe(true);
const bKey = await unlockKeyring(b.readMeta()!, { passphrase: "one password" });
expect((await openEntry(bKey, b.get("id_ed25519"))).privateKey).toBe(key.privateKey);
});
it("still asks when the newer account keyring would lose a key this machine has", async () => {
const key = throwawayKey(dir);
const account = fakeAccount();
const b = new KeyringStore(join(dir, "keep-b"));
const old = await createKeyring("forgotten");
b.writeMeta({ ...old.meta, createdAt: "2026-01-01T00:00:00.000Z" });
b.write(await sealEntry(old.userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey }));
await account.putMeta((await createKeyring("one password")).meta);
await expect(syncKeyring(b, account)).rejects.toBeInstanceOf(KeyringDivergedError);
expect(b.find("id_ed25519")).toBeTruthy();
});
it("refuses to merge two different keyrings unless told which wins", async () => {
const account = fakeAccount();
const first = await createKeyring("one");

View file

@ -11,12 +11,18 @@ import {
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";
@ -259,6 +265,21 @@ describe("logicsrc passwd --email", () => {
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(
@ -266,3 +287,107 @@ describe("logicsrc passwd --email", () => {
).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) };
}
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);
});

View file

@ -16,17 +16,20 @@ import {
recoverUserKeyByEmail,
resetRecoveryKey,
rewrapUserKey,
pullVault,
pushVault,
stableUuid,
toBase64,
unlockVault,
unlockWithRecoveryKey,
type EmailRecoveryClient,
type SyncRemote,
type VaultMeta,
type VaultStore
} from "@logicsrc/opencreds";
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";
import { accountRecoveryFor, accountRemoteFor } from "./vault-sync.js";
/**
* `logicsrc passwd`: one password for the personal vault and the SSH keyring.
@ -106,6 +109,8 @@ export interface PasswdDeps {
vault?: VaultStore;
keyring?: KeyringStore;
remote?: () => KeyringRemote | undefined;
/** The account's copy of the vault, pushed in the same run so every machine gets the new password. */
vaultRemote?: (store: VaultStore) => SyncRemote | 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. */
@ -120,6 +125,8 @@ export interface PasswdResult {
keyring: "changed" | "created" | "missing";
keyringRecoveryKey?: string;
keyringSynced: boolean;
/** The account's copy of the vault carries the new password (other machines take it on their next sync). */
vaultSynced: 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. */
@ -259,6 +266,20 @@ export async function changeAllPasswords(
const say = deps.say ?? ((line: string) => console.error(line));
const remoteFor = deps.remote ?? accountKeyringRemote;
// 0. The account's vault first. A password set on another machine since the last
// sync would otherwise win over the one chosen here ("the account's wins" on a
// later pull), and a machine with no local vault yet gets one to reset.
const vaultRemote = opts.noSync ? undefined : (deps.vaultRemote ?? accountRemoteFor)(vault);
let pulled = false;
if (vaultRemote) {
try {
await pullVault(vault, vaultRemote);
pulled = true;
} catch (e) {
say(`Could not read the account's vault first (${(e as Error).message}); changing this machine's copy only.`);
}
}
// 1. Open what exists, before asking for anything new.
const vaultMeta = vault.readMeta();
let opened: { userKey: Uint8Array; password?: string } | undefined;
@ -299,6 +320,7 @@ export async function changeAllPasswords(
vault: "missing",
keyring: "missing",
keyringSynced: false,
vaultSynced: false,
keyringEscrowed: false,
keysReimported: [],
keysLost: []
@ -369,7 +391,21 @@ export async function changeAllPasswords(
}
}
// 4. Replace the account's keyring copy, which still carries the old wrap.
// 4. The account's copies, in this same run: the reset is for everything the
// account owns, and other machines only ever see the account's copy.
if (result.vault === "changed" && opened && vaultRemote) {
if (pulled) {
try {
await pushVault(vault, vaultRemote, opened.userKey);
result.vaultSynced = true;
} catch (e) {
say(`Vault sync skipped: ${(e as Error).message}. Run: logicsrc vault sync`);
}
} else {
say("Vault sync skipped. Run: logicsrc vault sync");
}
}
// 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) {
@ -396,7 +432,9 @@ export function registerPasswdCommand(program: Command): void {
`
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 \`logicsrc vault sync\`, and the keyring change on their next
\`logicsrc keyring sync\` (no flag needed: a newer password or a reset keyring that
holds every key the machine has is taken from the account).
logicsrc passwd you know the current password (or have the recovery keys)
logicsrc passwd --email you know nothing: needs \`logicsrc login\` and email recovery
@ -409,7 +447,9 @@ Each run stores the keyring's key as an item in your vault, so the next
.action(async (opts: { resetKeyring?: boolean; sync?: boolean; email?: boolean }) => {
try {
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)" : ""}.`);
console.error(
`Vault: ${r.vault}${r.vaultSynced ? " (account copy updated)" : ""}. 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}`);
}
@ -426,7 +466,10 @@ Each run stores the keyring's key as an item in your vault, so the next
} 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.");
if (r.vault === "changed" && !r.vaultSynced) console.error("Run `logicsrc vault sync` to send the vault change to your account.");
if (r.vaultSynced || r.keyringSynced) {
console.error("Your other machines take the new password on their next `logicsrc vault sync` and `logicsrc keyring sync`.");
}
} catch (e) {
console.error((e as Error).message);
process.exitCode = 1;