mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-04 02:29:06 +00:00
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>
This commit is contained in:
parent
896eba3c07
commit
6ff3089088
16 changed files with 799 additions and 62 deletions
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@logicsrc/cli",
|
||||
"version": "0.17.0",
|
||||
"version": "0.18.0",
|
||||
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
|
|
|||
|
|
@ -344,6 +344,116 @@ function fakeVaultAccount() {
|
|||
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();
|
||||
|
|
|
|||
|
|
@ -10,10 +10,9 @@ import {
|
|||
encryptItem,
|
||||
enrollEmailRecovery,
|
||||
fromBase64,
|
||||
parseRecoveryCode,
|
||||
obtainUserKeyByEmail,
|
||||
promptNewSecret,
|
||||
promptSecret,
|
||||
recoverUserKeyByEmail,
|
||||
resetRecoveryKey,
|
||||
rewrapUserKey,
|
||||
pullVault,
|
||||
|
|
@ -113,6 +112,8 @@ export interface PasswdDeps {
|
|||
vaultRemote?: (store: VaultStore) => SyncRemote | undefined;
|
||||
/** Email recovery for the vault (`--email`). */
|
||||
recovery?: (store: VaultStore) => EmailRecoveryClient | undefined;
|
||||
/** Test seam for the wait while a browser confirmation is pending. */
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
/** Where the keyring's key files live on disk, to refill a keyring that had to be reset. */
|
||||
sshDir?: string;
|
||||
ask?: (label: string) => Promise<string>;
|
||||
|
|
@ -133,6 +134,8 @@ export interface PasswdResult {
|
|||
emailRearmed?: boolean;
|
||||
emailRearmedTo?: string;
|
||||
emailRearmError?: string;
|
||||
/** The account uses assisted recovery (browser confirmation, no enrollment-email code). */
|
||||
assistedRecovery?: boolean;
|
||||
/** 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. */
|
||||
|
|
@ -140,25 +143,26 @@ export interface PasswdResult {
|
|||
keysLost: string[];
|
||||
}
|
||||
|
||||
/** Open the vault with the two emailed codes. Nothing is written here. */
|
||||
/** Open the vault through email recovery (assisted or with the emailed recovery code). Nothing is written here. */
|
||||
async function openVaultByEmail(
|
||||
vault: VaultStore,
|
||||
meta: VaultMeta,
|
||||
client: EmailRecoveryClient,
|
||||
ask: (l: string) => Promise<string>,
|
||||
say: (line: string) => void
|
||||
): Promise<Uint8Array> {
|
||||
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);
|
||||
}
|
||||
say: (line: string) => void,
|
||||
sleep?: (ms: number) => Promise<void>
|
||||
): Promise<{ userKey: Uint8Array; assisted: boolean }> {
|
||||
return obtainUserKeyByEmail({
|
||||
store: vault,
|
||||
meta,
|
||||
client,
|
||||
say,
|
||||
prompts: {
|
||||
recoveryCode: () => ask("Recovery code from the enrollment email: "),
|
||||
oneTimeCode: () => ask("One-time code from the email just sent: "),
|
||||
sleep
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** With `--email` the old keyring passphrase may be gone too: every prompt can be skipped, and skipping all of them means a reset. */
|
||||
|
|
@ -284,11 +288,14 @@ export async function changeAllPasswords(
|
|||
const vaultMeta = vault.readMeta();
|
||||
let opened: { userKey: Uint8Array; password?: string } | undefined;
|
||||
let recoveryClient: EmailRecoveryClient | undefined;
|
||||
let assistedRecovery = false;
|
||||
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) };
|
||||
const viaEmail = await openVaultByEmail(vault, vaultMeta, recoveryClient, ask, say, deps.sleep);
|
||||
opened = { userKey: viaEmail.userKey };
|
||||
assistedRecovery = viaEmail.assisted;
|
||||
} else if (vaultMeta) {
|
||||
opened = await openVault(vaultMeta, ask);
|
||||
}
|
||||
|
|
@ -382,7 +389,9 @@ export async function changeAllPasswords(
|
|||
// 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);
|
||||
// Re-armed the way it was: an account on assisted recovery stays on it.
|
||||
const enrolled = await enrollEmailRecovery(recoveryClient, currentVaultMeta, opened.userKey, { assisted: assistedRecovery });
|
||||
result.assistedRecovery = assistedRecovery;
|
||||
result.emailRearmed = Boolean(enrolled.enrolled);
|
||||
result.emailRearmedTo = enrolled.email;
|
||||
} catch (e) {
|
||||
|
|
@ -461,8 +470,11 @@ Each run stores the keyring's key as an item in your vault, so the next
|
|||
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 <file>`);
|
||||
}
|
||||
if (r.keyringEscrowed) console.error("The keyring's key is stored in your vault: next time `logicsrc passwd --email` opens both.");
|
||||
if (r.emailRearmed) {
|
||||
if (r.emailRearmed && r.assistedRecovery) {
|
||||
console.error("Assisted recovery is armed again. You are done: next time you need the emailed one-time code and a passkey or CoinPay sign-in, nothing else.");
|
||||
} else 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.`);
|
||||
console.error("Delete your email? Turn on assisted recovery so no old email is ever needed: logicsrc vault recovery enable --assisted");
|
||||
} else if (r.emailRearmError) {
|
||||
console.error(`Email recovery is OFF now and could not be re-armed (${r.emailRearmError}). Run: logicsrc vault recovery enable`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -166,14 +166,22 @@ export function createRecoveryClient(
|
|||
},
|
||||
async enroll(payload: EscrowEnrollment) {
|
||||
const body = await call("POST", "/enroll", payload);
|
||||
return { enrolled: Boolean(body.enrolled), email: String(body.email ?? "") };
|
||||
return { enrolled: Boolean(body.enrolled), email: String(body.email ?? ""), assisted: body.assisted === true };
|
||||
},
|
||||
async start() {
|
||||
const body = await call("POST", "/start");
|
||||
return { sent: Boolean(body.sent), email: typeof body.email === "string" ? body.email : undefined };
|
||||
},
|
||||
async claim(code: string) {
|
||||
return (await call("POST", "/claim", { code })) as unknown as EscrowMaterial;
|
||||
async claim(code: string, stepupId?: string) {
|
||||
return (await call("POST", "/claim", stepupId ? { code, stepup: stepupId } : { code })) as unknown as EscrowMaterial;
|
||||
},
|
||||
async stepup() {
|
||||
const body = await call("POST", "/stepup");
|
||||
return { id: String(body.id), url: String(body.url), expiresIn: Number(body.expiresIn) || 600 };
|
||||
},
|
||||
async stepupStatus(id: string) {
|
||||
const body = await call("GET", `/stepup/${encodeURIComponent(id)}`);
|
||||
return { status: String(body.status), method: typeof body.method === "string" ? body.method : null };
|
||||
},
|
||||
async disable() {
|
||||
const body = await call("DELETE", "");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue