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", "");
|
||||
|
|
|
|||
|
|
@ -537,9 +537,6 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions
|
|||
|
||||
async function recoverByEmail(store: VaultStore, client: EmailRecoveryClient): Promise<void> {
|
||||
requireMeta(store);
|
||||
process.stderr.write(
|
||||
'Email recovery needs the recovery code from the "Your LogicSRC vault email-recovery code" email.\n',
|
||||
);
|
||||
let result: EmailRecoveryResult;
|
||||
try {
|
||||
result = await runEmailRecovery({
|
||||
|
|
@ -615,6 +612,15 @@ vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`))
|
|||
` Enrolled ${status.enrolled ? `yes, since ${status.enrolledAt ?? "?"}` : `no${status.purchased ? ` (\`${cli} recovery enable\`)` : ""}`}\n`,
|
||||
);
|
||||
if (status.email) process.stdout.write(` Email ${status.email}\n`);
|
||||
if (status.enrolled) {
|
||||
const m = status.stepupMethods;
|
||||
const have = [m?.passkey ? "passkey" : "", m?.coinpay ? "CoinPay" : ""].filter(Boolean).join(" or ");
|
||||
process.stdout.write(
|
||||
status.assisted
|
||||
? ` Second proof a ${have || "passkey or CoinPay"} sign-in in the browser (assisted recovery: the server can open this vault)\n`
|
||||
: ` Second proof the recovery code in the enrollment email${have ? ` (or switch to ${have}: \`${cli} recovery enable --assisted\`)` : ""}\n`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -637,7 +643,11 @@ vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`))
|
|||
recovery
|
||||
.command("enable")
|
||||
.description("enroll this vault in email recovery; running it again re-keys and emails a new code")
|
||||
.action(async function (this: Command) {
|
||||
.option(
|
||||
"--assisted",
|
||||
"no old email needed: recover with the emailed one-time code plus a passkey or CoinPay sign-in. The server then keeps both halves of the recovery key and is able to open this vault",
|
||||
)
|
||||
.action(async function (this: Command, opts: { assisted?: boolean }) {
|
||||
await run(async () => {
|
||||
const store = storeFor(this);
|
||||
const client = recoveryClient(store);
|
||||
|
|
@ -652,13 +662,30 @@ vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`))
|
|||
);
|
||||
}
|
||||
const userKey = await unlock(store);
|
||||
let result: { enrolled: boolean; email: string };
|
||||
if (opts.assisted && status.stepupMethods && !status.stepupMethods.passkey && !status.stepupMethods.coinpay) {
|
||||
fail(
|
||||
"Assisted recovery confirms with a passkey or a connected CoinPay account, and this account has neither. " +
|
||||
"Add a passkey or sign in with CoinPay on the account's Settings page, then run this again.",
|
||||
EXIT.USAGE,
|
||||
);
|
||||
}
|
||||
let result: { enrolled: boolean; email: string; assisted?: boolean };
|
||||
try {
|
||||
result = await enrollEmailRecovery(client, meta, userKey);
|
||||
result = await enrollEmailRecovery(client, meta, userKey, { assisted: Boolean(opts.assisted) });
|
||||
} catch (err) {
|
||||
const e = err as EmailRecoveryError;
|
||||
fail(`${e.message}${e.checkoutUrl ? `\n\n ${e.checkoutUrl}\n` : ""}`, EXIT.USAGE);
|
||||
}
|
||||
if (opts.assisted) {
|
||||
process.stdout.write(
|
||||
"Assisted recovery is on. To get back in you need two things: the one-time code we email at that moment, " +
|
||||
"and a passkey or CoinPay sign-in in the browser. No old email is needed.\n" +
|
||||
"The trade: the server now keeps both halves of your recovery key (sealed) and is able to open this vault. " +
|
||||
`Go back to the stricter setup any time with \`${cli} recovery enable\`.\n` +
|
||||
(status.enrolled ? "The previous recovery code no longer works.\n" : ""),
|
||||
);
|
||||
return;
|
||||
}
|
||||
process.stdout.write(
|
||||
`Email recovery is on. Your recovery code was emailed to ${result.email}.\n` +
|
||||
"Keep that email: it is half of the way back in, and it is not stored anywhere else.\n" +
|
||||
|
|
|
|||
|
|
@ -70,6 +70,12 @@ export interface EscrowEnrollment {
|
|||
serverShare: string;
|
||||
userShare: string;
|
||||
vaultCreatedAt: string;
|
||||
/**
|
||||
* Assisted recovery (opt-in): ask the server to keep U too, sealed, and to release it
|
||||
* after the one-time code plus a passkey or CoinPay sign-in. Custodial: the server then
|
||||
* holds everything that opens the vault.
|
||||
*/
|
||||
assisted?: boolean;
|
||||
}
|
||||
|
||||
/** What the server releases on a successful claim. */
|
||||
|
|
@ -78,6 +84,8 @@ export interface EscrowMaterial {
|
|||
escrowIv: string;
|
||||
serverShare: string;
|
||||
vaultCreatedAt: string;
|
||||
/** Only on an assisted claim (a confirmed step-up): U, base64. */
|
||||
userShare?: string;
|
||||
}
|
||||
|
||||
export interface EmailRecoveryStatus {
|
||||
|
|
@ -87,6 +95,18 @@ export interface EmailRecoveryStatus {
|
|||
email: string | null;
|
||||
purchased: boolean;
|
||||
priceUsd: number;
|
||||
/** Assisted recovery is on: no enrollment-email code needed, a browser confirmation instead. */
|
||||
assisted?: boolean;
|
||||
/** What the account can confirm with. */
|
||||
stepupMethods?: { passkey: boolean; coinpay: boolean };
|
||||
}
|
||||
|
||||
/** A browser confirmation of an assisted recovery. */
|
||||
export interface RecoveryStepup {
|
||||
id: string;
|
||||
url: string;
|
||||
/** Seconds until the link dies. */
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
/** The account's email-recovery endpoints. The logicsrc CLI provides one. */
|
||||
|
|
@ -97,7 +117,11 @@ export interface EmailRecoveryClient {
|
|||
/** Throws EmailRecoveryError with status 402 and a checkoutUrl when not purchased. */
|
||||
enroll(payload: EscrowEnrollment): Promise<{ enrolled: boolean; email: string }>;
|
||||
start(): Promise<{ sent: boolean; email?: string }>;
|
||||
claim(code: string): Promise<EscrowMaterial>;
|
||||
/** With `stepupId` (assisted recovery) the material carries U as well. */
|
||||
claim(code: string, stepupId?: string): Promise<EscrowMaterial>;
|
||||
/** Assisted recovery: open a confirmation and read its status. Absent on a client that cannot. */
|
||||
stepup?(): Promise<RecoveryStepup>;
|
||||
stepupStatus?(id: string): Promise<{ status: string; method?: string | null }>;
|
||||
disable(): Promise<{ disabled: boolean }>;
|
||||
}
|
||||
|
||||
|
|
@ -195,8 +219,10 @@ export async function enrollEmailRecovery(
|
|||
client: EmailRecoveryClient,
|
||||
meta: VaultMeta,
|
||||
userKey: Uint8Array,
|
||||
): Promise<{ enrolled: boolean; email: string }> {
|
||||
opts: { assisted?: boolean } = {},
|
||||
): Promise<{ enrolled: boolean; email: string; assisted?: boolean }> {
|
||||
const prepared = await prepareEnrollment(meta, userKey);
|
||||
if (opts.assisted) prepared.payload.assisted = true;
|
||||
try {
|
||||
return await client.enroll(prepared.payload);
|
||||
} finally {
|
||||
|
|
@ -338,6 +364,73 @@ export interface EmailRecoveryPrompts {
|
|||
oneTimeCode(email: string | undefined): Promise<string>;
|
||||
/** The new master password, already confirmed. */
|
||||
newPassword(): Promise<string>;
|
||||
/** Test seam for the wait between confirmation checks. */
|
||||
sleep?(ms: number): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The vault's user key through email recovery, by whichever second proof the
|
||||
* account uses. Nothing on disk changes here.
|
||||
*
|
||||
* - Assisted recovery on: a link to confirm in a browser (passkey or CoinPay),
|
||||
* then the emailed one-time code. No enrollment-email code is asked for.
|
||||
* - Otherwise: the recovery code from the enrollment email (checked first, so a
|
||||
* typo costs nothing), then the emailed one-time code.
|
||||
*/
|
||||
export async function obtainUserKeyByEmail(opts: {
|
||||
store: VaultStore;
|
||||
meta: VaultMeta;
|
||||
client: EmailRecoveryClient;
|
||||
prompts: Pick<EmailRecoveryPrompts, "recoveryCode" | "oneTimeCode" | "sleep">;
|
||||
say?: (line: string) => void;
|
||||
}): Promise<{ userKey: Uint8Array; assisted: boolean }> {
|
||||
const { store, meta, client, prompts } = opts;
|
||||
const say = opts.say ?? (() => {});
|
||||
const status = await client.status().catch(() => undefined);
|
||||
|
||||
if (status?.assisted && client.stepup && client.stepupStatus) {
|
||||
const stepup = await client.stepup();
|
||||
say("Confirm this recovery in a browser, with your passkey or your CoinPay account:");
|
||||
say(`\n ${stepup.url}\n`);
|
||||
say(`Waiting for the confirmation (the link works for ${Math.max(1, Math.round(stepup.expiresIn / 60))} minutes)...`);
|
||||
const sleep = prompts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const deadline = Date.now() + stepup.expiresIn * 1000;
|
||||
for (;;) {
|
||||
const s = await client.stepupStatus(stepup.id);
|
||||
if (s.status === "approved") break;
|
||||
if (s.status !== "pending" || Date.now() > deadline) {
|
||||
throw new EmailRecoveryError("The confirmation link expired before it was confirmed. Run this again.", undefined, "stepup_expired");
|
||||
}
|
||||
await sleep(2000);
|
||||
}
|
||||
say("Confirmed.");
|
||||
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 prompts.oneTimeCode(started.email)).replace(/\s+/g, "");
|
||||
const material = await client.claim(code, stepup.id);
|
||||
if (!material.userShare) {
|
||||
throw new EmailRecoveryError("The account did not release the recovery key. Run this again.", undefined, "stepup_required");
|
||||
}
|
||||
const userShare = fromBase64(material.userShare);
|
||||
material.userShare = "";
|
||||
try {
|
||||
return { userKey: await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() }), assisted: true };
|
||||
} finally {
|
||||
wipe(userShare);
|
||||
}
|
||||
}
|
||||
|
||||
say('This needs the recovery code from your newest "Your LogicSRC vault email-recovery code" email.');
|
||||
const userShare = await parseRecoveryCode(await prompts.recoveryCode());
|
||||
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 prompts.oneTimeCode(started.email)).replace(/\s+/g, "");
|
||||
const material = await client.claim(code);
|
||||
return { userKey: await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() }), assisted: false };
|
||||
} finally {
|
||||
wipe(userShare);
|
||||
}
|
||||
}
|
||||
|
||||
export interface EmailRecoveryResult {
|
||||
|
|
@ -346,6 +439,8 @@ export interface EmailRecoveryResult {
|
|||
/** The new offline recovery key, to print once. */
|
||||
recoveryKey: string;
|
||||
reenrolled: boolean;
|
||||
/** Assisted recovery was on, and stays on after the re-arm. */
|
||||
assisted?: boolean;
|
||||
reenrolledEmail?: string;
|
||||
reenrollError?: string;
|
||||
}
|
||||
|
|
@ -370,18 +465,7 @@ export async function runEmailRecovery(opts: {
|
|||
if (!meta) throw new EmailRecoveryError(`No vault at ${store.baseDir}`, undefined, "no_vault");
|
||||
assertProfile(meta, ["user"]);
|
||||
|
||||
const userShare = await parseRecoveryCode(await prompts.recoveryCode());
|
||||
const userKey = await (async () => {
|
||||
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 prompts.oneTimeCode(started.email)).replace(/\s+/g, "");
|
||||
const material = await client.claim(code);
|
||||
return await recoverUserKeyByEmail({ meta, material, userShare, envelopes: store.listEnvelopes() });
|
||||
} finally {
|
||||
wipe(userShare);
|
||||
}
|
||||
})();
|
||||
const { userKey, assisted } = await obtainUserKeyByEmail({ store, meta, client, prompts, say });
|
||||
|
||||
const password = await prompts.newPassword();
|
||||
if (!password) throw new EmailRecoveryError("A master password is required", undefined, "no_password");
|
||||
|
|
@ -389,9 +473,9 @@ export async function runEmailRecovery(opts: {
|
|||
const reset = await resetRecoveryKey(rewrapped, userKey);
|
||||
store.writeMeta(reset.meta);
|
||||
|
||||
const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false };
|
||||
const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false, assisted };
|
||||
try {
|
||||
const enrolled = await enrollEmailRecovery(client, reset.meta, userKey);
|
||||
const enrolled = await enrollEmailRecovery(client, reset.meta, userKey, { assisted });
|
||||
result.reenrolled = Boolean(enrolled.enrolled);
|
||||
result.reenrolledEmail = enrolled.email;
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -193,6 +193,7 @@ export {
|
|||
parseRecoveryCode,
|
||||
prepareEnrollment,
|
||||
recoverUserKeyByEmail,
|
||||
obtainUserKeyByEmail,
|
||||
runEmailRecovery,
|
||||
sealEscrow,
|
||||
splitEscrowKey,
|
||||
|
|
@ -201,6 +202,7 @@ export {
|
|||
type EmailRecoveryPrompts,
|
||||
type EmailRecoveryResult,
|
||||
type EmailRecoveryStatus,
|
||||
type RecoveryStepup,
|
||||
type EscrowEnrollment,
|
||||
type EscrowMaterial,
|
||||
} from "./email-recovery.js";
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue