vault: opt-in paid email recovery for the personal vault ($5 lifetime)

A second way back into a logicsrc personal vault when the master password and
the offline recovery key are both gone, without the server holding anything
that alone (even with the DB and server env) opens the vault.

Client (packages/opencreds): random escrow key E encrypts the user key K
(AES-256-GCM, AAD "<ns>:vault:email-escrow:v1|<createdAt>"); E is split into
S (random, to the server) and U = E XOR S (emailed once as a checksummed
Crockford recovery code, never stored). `recover --email` checks the code's
check group first, asks the server for a one-time code, claims S, recombines
E, proves K against an item, sets a new password, issues a new offline
recovery key and re-enrolls with fresh shares (warns loudly if that fails).
New `recovery status|buy|enable|disable` commands; the CLI client lives in
packages/cli/src/vault-sync.ts.

Server (apps/pwa): /api/opencreds/recovery/{checkout,enroll,start,claim} +
status/disable. S is sealed under VAULT_ESCROW_KEY (versioned for rotation,
AAD binds the user). Enrollment is pending until the email with U is sent,
else rolled back. One-time codes: 8 digits, HMAC at rest, 15 min, 5 tries,
single use, 3 starts/hour; claims are audited and announced by email.
Purchase via CoinPay checkout (purpose vault_recovery); /api/coinpay/webhook
now verifies once and dispatches by purpose, auto_rotation unchanged.
Settings card with status and a Buy button. Migration 014 in both dialects.

Docs: security.md and crypto.md "Email recovery (opt-in, paid)" sections with
the honest trade-off; cli.md command reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-11-30 15:20:54 +00:00
parent 4e4fedd35e
commit 8528634e09
21 changed files with 2368 additions and 7 deletions

View file

@ -1,6 +1,6 @@
import type { Command } from "commander";
import { registerCredsCommands } from "@logicsrc/opencreds/commands";
import { accountRemoteFor } from "./vault-sync.js";
import { accountRecoveryFor, accountRemoteFor } from "./vault-sync.js";
/**
* `logicsrc vault …`
@ -53,6 +53,14 @@ gets it with: logicsrc login, then logicsrc vault sync.
logicsrc vault sync --status what is synced, what is waiting
LOGICSRC_VAULT_SYNC=off turn it off (a --home vault never syncs)
Lost the master password? The offline recovery key from init works:
logicsrc vault recover
Email recovery (opt-in, $5 lifetime) is a second way back in, through your account email:
logicsrc vault recovery buy CoinPay checkout link
logicsrc vault recovery enable emails you a recovery code to keep
logicsrc vault recover --email that code + a fresh emailed one-time code
logicsrc vault recovery status | disable
Help for any command: logicsrc vault <command> --help (or: logicsrc vault help <command>)
`;
@ -68,5 +76,5 @@ export function registerOpenCredsCommands(program: Command): void {
.addHelpText("after", VAULT_GUIDE);
// Logged in: the vault syncs to the account around every command.
registerCredsCommands(vault, { remote: accountRemoteFor });
registerCredsCommands(vault, { remote: accountRemoteFor, emailRecovery: accountRecoveryFor });
}

View file

@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { EmailRecoveryError } from "@logicsrc/opencreds";
import { createRecoveryClient } from "./vault-sync.js";
type Call = { url: string; method: string; auth: string | null; body: unknown };
function fakeFetch(answers: Record<string, { status: number; body: unknown }>) {
const calls: Call[] = [];
const impl = (async (url: string, init: RequestInit = {}) => {
const method = init.method ?? "GET";
calls.push({
url,
method,
auth: new Headers(init.headers).get("authorization"),
body: init.body ? JSON.parse(String(init.body)) : undefined,
});
const answer = answers[`${method} ${new URL(url).pathname}`] ?? { status: 404, body: { error: "nope" } };
return new Response(JSON.stringify(answer.body), { status: answer.status });
}) as unknown as typeof fetch;
return { impl, calls };
}
describe("the email-recovery client", () => {
it("talks to /api/opencreds/recovery with the person's key", async () => {
const { impl, calls } = fakeFetch({
"GET /api/opencreds/recovery": { status: 200, body: { enrolled: true, enrolledAt: "2026-11-30T00:00:00.000Z", email: "m***@x.test", purchased: true, priceUsd: 5 } },
"POST /api/opencreds/recovery/claim": { status: 200, body: { escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" } },
"DELETE /api/opencreds/recovery": { status: 200, body: { disabled: true } },
});
const client = createRecoveryClient("https://app.example/", "lsk_test", "me@x.test", impl);
expect(client.label).toBe("app.example (me@x.test)");
expect((await client.status()).enrolled).toBe(true);
expect(await client.claim("12345678")).toEqual({ escrowBlob: "b", escrowIv: "i", serverShare: "s", vaultCreatedAt: "c" });
expect(await client.disable()).toEqual({ disabled: true });
expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([
"GET https://app.example/api/opencreds/recovery",
"POST https://app.example/api/opencreds/recovery/claim",
"DELETE https://app.example/api/opencreds/recovery",
]);
expect(calls.every((c) => c.auth === "Bearer lsk_test")).toBe(true);
expect(calls[1]!.body).toEqual({ code: "12345678" });
});
it("surfaces a 402 with the checkout link", async () => {
const { impl } = fakeFetch({
"POST /api/opencreds/recovery/enroll": {
status: 402,
body: { error: "Email recovery is a $5 lifetime add-on and is not purchased yet.", code: "payment_required", checkoutUrl: "https://coinpay.test/pay/cs_1" },
},
});
const client = createRecoveryClient("https://app.example", "lsk_test", undefined, impl);
const err = await client
.enroll({ escrowBlob: "", escrowIv: "", serverShare: "", userShare: "", vaultCreatedAt: "" })
.catch((e: unknown) => e);
expect(err).toBeInstanceOf(EmailRecoveryError);
expect((err as EmailRecoveryError).status).toBe(402);
expect((err as EmailRecoveryError).code).toBe("payment_required");
expect((err as EmailRecoveryError).checkoutUrl).toBe("https://coinpay.test/pay/cs_1");
});
});

View file

@ -1,6 +1,18 @@
import { join, resolve } from "node:path";
import { homedir } from "node:os";
import type { Envelope, RemoteItem, RemoteVault, SyncRemote, VaultMeta, VaultStore } from "@logicsrc/opencreds";
import { EmailRecoveryError } from "@logicsrc/opencreds";
import type {
EmailRecoveryClient,
EmailRecoveryStatus,
Envelope,
EscrowEnrollment,
EscrowMaterial,
RemoteItem,
RemoteVault,
SyncRemote,
VaultMeta,
VaultStore,
} from "@logicsrc/opencreds";
import { readIdentity, resolveApiUrl } from "@logicsrc/plugin-credential-sharing";
/**
@ -92,3 +104,80 @@ export function createAccountRemote(apiUrl: string, token: string, email?: strin
},
};
}
/**
* Email recovery for the personal vault (`logicsrc vault recovery …`,
* `logicsrc vault recover --email`): apps/pwa /api/opencreds/recovery.
*
* Same scope rule as sync: it protects the account's vault, so a --home vault
* gets it only with LOGICSRC_VAULT_SYNC=on. Turning sync off does not turn
* recovery off; the two are independent.
*/
export function accountRecoveryFor(store: VaultStore): EmailRecoveryClient | undefined {
const setting = (process.env.LOGICSRC_VAULT_SYNC || "").toLowerCase();
if (setting !== "on" && resolve(store.baseDir) !== resolve(defaultVaultDir())) return undefined;
const identity = readIdentity();
if (!identity?.apiToken) return undefined;
return createRecoveryClient(resolveApiUrl(identity), identity.apiToken, identity.email);
}
export function createRecoveryClient(
apiUrl: string,
token: string,
email?: string,
fetchImpl: typeof fetch = fetch,
): EmailRecoveryClient {
const base = apiUrl.replace(/\/+$/, "");
const host = (() => {
try {
return new URL(base).host;
} catch {
return base;
}
})();
async function call(method: string, path: string, body?: unknown): Promise<Record<string, unknown>> {
const res = await fetchImpl(`${base}/api/opencreds/recovery${path}`, {
method,
headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(body ? { "content-type": "application/json" } : {}) },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(30_000),
});
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok) {
throw new EmailRecoveryError(
String(json.error || `${host} answered HTTP ${res.status}`),
res.status,
typeof json.code === "string" ? json.code : undefined,
typeof json.checkoutUrl === "string" ? json.checkoutUrl : undefined,
);
}
return json;
}
return {
label: email ? `${host} (${email})` : host,
async status() {
return (await call("GET", "")) as unknown as EmailRecoveryStatus;
},
async checkout() {
const body = await call("POST", "/checkout");
return { url: String(body.url), priceUsd: Number(body.priceUsd) };
},
async enroll(payload: EscrowEnrollment) {
const body = await call("POST", "/enroll", payload);
return { enrolled: Boolean(body.enrolled), email: String(body.email ?? "") };
},
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 disable() {
const body = await call("DELETE", "");
return { disabled: Boolean(body.disabled) };
},
};
}

View file

@ -285,3 +285,13 @@ describe("validate", () => {
expect(result.code).toBe(2);
});
});
describe("email recovery in the standalone binary", () => {
it("is an account feature: recover --email and recovery commands exit 1 and point at logicsrc login", async () => {
for (const args of [["recover", "--email"], ["recovery", "status"], ["recovery", "enable"]]) {
const result = await cli(args);
expect(result.code, args.join(" ")).toBe(1);
expect(result.stderr).toMatch(/logicsrc login/);
}
});
});

View file

@ -58,6 +58,13 @@ import { createVault, resetRecoveryKey, rewrapUserKey, unlockVault, unlockWithRe
import { formatDiagnostics, hasErrors, validateDocument } from "./validate.js";
import { DivergedVaultError, describeSync, pullVault, pushVault, readSyncState, syncVault, type SyncRemote } from "./sync.js";
import type { VaultStore } from "./store.js";
import {
enrollEmailRecovery,
runEmailRecovery,
type EmailRecoveryClient,
type EmailRecoveryError,
type EmailRecoveryResult,
} from "./email-recovery.js";
/** Exit codes are part of the contract; see docs/opencreds/cli.md. */
export const EXIT = {
@ -302,6 +309,12 @@ export interface RegisterOptions {
* `opencreds` binary passes nothing, so it never syncs.
*/
remote?: (store: VaultStore) => SyncRemote | undefined;
/**
* The account's email-recovery endpoints, if any (opt-in, paid). Called per
* command; return undefined when there is no logged-in account. Without it,
* `recover --email` and `recovery …` explain that they need `logicsrc login`.
*/
emailRecovery?: (store: VaultStore) => EmailRecoveryClient | undefined;
}
// Commands that never touch a vault on disk, plus `sync`, which syncs itself.
@ -474,12 +487,33 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions
});
});
const recoveryClient = (store: VaultStore): EmailRecoveryClient => {
const client = options.emailRecovery?.(store);
if (!client) {
fail(
options.emailRecovery
? "Email recovery needs your account: run `logicsrc login` first. It protects the default vault only."
: "Email recovery is an account feature: use `logicsrc vault` after `logicsrc login`.",
EXIT.USAGE,
);
}
return client;
};
parent
.command("recover")
.description("unlock with the recovery key and set a new master password")
.action(async function (this: Command) {
.description("unlock with the recovery key (or --email) and set a new master password")
.option("--email", "recover through your account email instead of the offline recovery key (needs `recovery enable` first)")
.addHelpText("after", examples(`
$CLI recover type the offline recovery key printed by \`init\`
$CLI recover --email the code from your enrollment email + a fresh emailed one-time code (works locked)`))
.action(async function (this: Command, opts: { email?: boolean }) {
await run(async () => {
const store = storeFor(this);
if (opts.email) {
await recoverByEmail(store, recoveryClient(store));
return;
}
const meta = requireMeta(store);
const recoveryKey = await promptSecret("Recovery key: ");
let userKey: Uint8Array;
@ -499,6 +533,154 @@ export function registerCredsCommands(parent: Command, options: RegisterOptions
});
});
// ------------------------------------------------------ email recovery ---
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({
store,
client,
say: (line) => process.stderr.write(`${line}\n`),
prompts: {
recoveryCode: () => promptSecret("Recovery code from the enrollment email: "),
oneTimeCode: () => promptSecret("One-time code from the email just sent: "),
newPassword: () => promptNewSecret("New master password: ", "Repeat: "),
},
});
} catch (err) {
const code = (err as EmailRecoveryError).code;
fail((err as Error).message, code === "recovery_code_mismatch" || code === "escrow_stale" ? EXIT.CRYPTO : EXIT.USAGE);
}
unlockedKey = result.userKey;
store.appendAudit(
auditEvent({ action: "vault.recovery_reset", namespace: result.meta.namespace, reason: "email-recovery" }),
);
process.stdout.write(`Master password changed through email recovery. Not one item was re-encrypted.\n\n`);
process.stdout.write(` New recovery key ${result.recoveryKey}\n\n`);
process.stdout.write("Write it down now; it will not be shown again. The old recovery key no longer works.\n");
if (result.reenrolled) {
process.stdout.write(
`Email recovery is re-armed: a NEW recovery code was emailed to ${result.reenrolledEmail}. ` +
"The code you just used no longer works.\n",
);
return;
}
process.stderr.write(
"\n!!! WARNING: your vault is recovered, but email recovery could NOT be re-armed" +
(result.reenrollError ? ` (${result.reenrollError})` : "") +
".\n!!! The recovery code you just used may still work on the server. Run `" + cli + " recovery enable`\n" +
"!!! now to replace it, or `" + cli + " recovery disable` to turn email recovery off.\n",
);
}
const recovery = parent
.command("recovery")
.description("email recovery (opt-in, $5 lifetime): get back in through your account email if the password is lost")
.addHelpText("after", examples(`
$CLI recovery status enrolled? since when? which email? purchased?
$CLI recovery buy print the CoinPay checkout link ($5, lifetime)
$CLI recovery enable enroll this vault (unlocks it); emails you a recovery code to keep
$CLI recovery disable turn it off; the server deletes its escrow share and copy
$CLI recover --email the day you need it: works with the vault locked
What the server keeps: a copy of your vault key encrypted under a random key E,
and one half of E (S), encrypted under the server's own key. The other half is
the recovery code in the enrollment email; the server never stores it.
Recovering needs that email plus a fresh one-time code. Without enrollment the
vault stays zero-knowledge. See docs/opencreds/security.md for the trade-off.`));
recovery
.command("status")
.description("is email recovery enrolled and purchased (works locked)")
.option("--json", "machine-readable output")
.action(async function (this: Command, opts: { json?: boolean }) {
await run(async () => {
const client = recoveryClient(storeFor(this));
const status = await client.status();
if (opts.json) {
process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
return;
}
process.stdout.write(` Account ${client.label}\n`);
process.stdout.write(
` Purchased ${status.purchased ? "yes (lifetime)" : `no ($${status.priceUsd} lifetime: \`${cli} recovery buy\`)`}\n`,
);
process.stdout.write(
` Enrolled ${status.enrolled ? `yes, since ${status.enrolledAt ?? "?"}` : `no${status.purchased ? ` (\`${cli} recovery enable\`)` : ""}`}\n`,
);
if (status.email) process.stdout.write(` Email ${status.email}\n`);
});
});
recovery
.command("buy")
.description("print the CoinPay checkout link for email recovery ($5 lifetime)")
.action(async function (this: Command) {
await run(async () => {
const client = recoveryClient(storeFor(this));
const status = await client.status();
if (status.purchased) {
process.stdout.write(`Email recovery is already purchased. Turn it on with \`${cli} recovery enable\`.\n`);
return;
}
const { url, priceUsd } = await client.checkout();
process.stdout.write(`Pay $${priceUsd} (lifetime) here, then run \`${cli} recovery enable\`:\n\n ${url}\n`);
});
});
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) {
await run(async () => {
const store = storeFor(this);
const client = recoveryClient(store);
const meta = requireMeta(store);
const status = await client.status();
if (!status.purchased) {
const checkout = await client.checkout().catch(() => undefined);
fail(
`Email recovery is a $${status.priceUsd} lifetime add-on and is not purchased yet.` +
(checkout ? ` Pay here, then run this again:\n\n ${checkout.url}\n` : ` Run \`${cli} recovery buy\`.`),
EXIT.USAGE,
);
}
const userKey = await unlock(store);
let result: { enrolled: boolean; email: string };
try {
result = await enrollEmailRecovery(client, meta, userKey);
} catch (err) {
const e = err as EmailRecoveryError;
fail(`${e.message}${e.checkoutUrl ? `\n\n ${e.checkoutUrl}\n` : ""}`, EXIT.USAGE);
}
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" +
(status.enrolled ? "The previous recovery code no longer works.\n" : ""),
);
});
});
recovery
.command("disable")
.description("turn email recovery off; the server deletes its escrow share and copy")
.action(async function (this: Command) {
await run(async () => {
const client = recoveryClient(storeFor(this));
const { disabled } = await client.disable();
process.stdout.write(
disabled
? "Email recovery is off. The server deleted its share, so the emailed recovery code is useless now.\n"
: "Email recovery was not enabled.\n",
);
});
});
// ---------------------------------------------------------------- items ---
const add = parent
@ -1109,7 +1291,9 @@ function registerSync(
: `vault sync: skipped (${message}); changes stay on this machine and go up next time.`,
);
};
const autosync = (command: Command) => !NO_AUTOSYNC.has(command.name()) && process.env.OPENCREDS_SYNC !== "off";
// `recovery …` talks to the account, not the vault files: nothing to sync around it.
const autosync = (command: Command) =>
!NO_AUTOSYNC.has(command.name()) && command.parent?.name() !== "recovery" && process.env.OPENCREDS_SYNC !== "off";
parent.hook("preAction", async (_self, command) => {
if (!autosync(command)) return;

View file

@ -0,0 +1,318 @@
/**
* Email recovery: the XOR split, the escrow copy, the recovery code format, and
* the whole `recover --email` flow against a fake account server that behaves
* like apps/pwa (stores S and the blob, mails U and one-time codes, never keeps U).
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
EmailRecoveryError,
RecoveryCodeMismatchError,
combineEscrowKey,
enrollEmailRecovery,
formatRecoveryCode,
openEscrow,
parseRecoveryCode,
prepareEnrollment,
recoverUserKeyByEmail,
runEmailRecovery,
sealEscrow,
splitEscrowKey,
xorBytes,
type EmailRecoveryClient,
type EscrowEnrollment,
type EscrowMaterial,
} from "./email-recovery.js";
import { createItem, encryptItem } from "./items.js";
import { fromBase64, randomBytes, toBase64 } from "./primitives.js";
import { createVaultStore } from "./store.js";
import { createVault, unlockVault, unlockWithRecoveryKey } from "./vault-key.js";
const FAST = { kdf: "pbkdf2-sha256" as const, iterations: 100_000 };
const dirs: string[] = [];
afterEach(() => {
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
});
describe("the XOR split", () => {
it("splits E into two shares that recombine, and neither share is E", () => {
const E = randomBytes(32);
const { serverShare, userShare } = splitEscrowKey(E);
expect(serverShare).not.toEqual(E);
expect(userShare).not.toEqual(E);
expect(combineEscrowKey(serverShare, userShare)).toEqual(E);
expect(xorBytes(userShare, E)).toEqual(serverShare);
});
it("gives a fresh server share every time", () => {
const E = randomBytes(32);
expect(splitEscrowKey(E).serverShare).not.toEqual(splitEscrowKey(E).serverShare);
});
it("refuses shares of the wrong size", () => {
expect(() => splitEscrowKey(randomBytes(16))).toThrow();
expect(() => combineEscrowKey(randomBytes(32), randomBytes(31))).toThrow();
});
});
describe("the escrow copy of the user key", () => {
it("round-trips K under E, bound to the vault", async () => {
const { meta, userKey } = await createVault("pw", { params: FAST });
const sealed = await sealEscrow(userKey, meta);
const material = { ...sealed, vaultCreatedAt: meta.createdAt! };
expect(await openEscrow(sealed.escrowKey, material, meta.namespace)).toEqual(userKey);
// Another vault's createdAt is different associated data: the tag fails.
await expect(openEscrow(sealed.escrowKey, { ...material, vaultCreatedAt: "2001-01-01T00:00:00Z" }, meta.namespace)).rejects.toBeInstanceOf(
RecoveryCodeMismatchError,
);
});
it("a wrong U fails cleanly with a mismatch error, not a crypto stack", async () => {
const { meta, userKey } = await createVault("pw", { params: FAST });
const { payload } = await prepareEnrollment(meta, userKey);
const material: EscrowMaterial = { ...payload };
const wrongU = randomBytes(32);
const err = await recoverUserKeyByEmail({ meta, material, userShare: wrongU }).catch((e) => e);
expect(err).toBeInstanceOf(RecoveryCodeMismatchError);
expect(err.message).toMatch(/doesn't match/);
// The right U opens it.
expect(await recoverUserKeyByEmail({ meta, material, userShare: fromBase64(payload.userShare) })).toEqual(userKey);
});
it("refuses material enrolled for a different vault", async () => {
const a = await createVault("pw", { params: FAST });
const b = await createVault("pw", { params: FAST });
const { payload } = await prepareEnrollment(a.meta, a.userKey);
const err = await recoverUserKeyByEmail({
meta: { ...b.meta, createdAt: "2030-01-01T00:00:00Z" },
material: payload,
userShare: fromBase64(payload.userShare),
}).catch((e) => e);
expect(err).toBeInstanceOf(EmailRecoveryError);
expect(err.code).toBe("vault_mismatch");
});
it("wipes E, S and U on request", async () => {
const { meta, userKey } = await createVault("pw", { params: FAST });
const prepared = await prepareEnrollment(meta, userKey);
expect(fromBase64(prepared.payload.userShare).some((b) => b !== 0)).toBe(true);
prepared.wipe(); // no throw; the base64 copies in the payload are what gets sent
});
});
describe("the recovery code", () => {
it("is twelve groups of five and parses back to U", async () => {
const U = randomBytes(32);
const code = await formatRecoveryCode(U);
expect(code).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){11}$/);
expect(await parseRecoveryCode(code)).toEqual(U);
});
it("tolerates case, spaces, missing dashes and Crockford's confusables", async () => {
const U = randomBytes(32);
const code = await formatRecoveryCode(U);
const sloppy = code.toLowerCase().replace(/-/g, " ").replace(/0/g, "o").replace(/1/g, "l");
expect(await parseRecoveryCode(sloppy)).toEqual(U);
});
it("catches a typo with the check group, before anything is spent", async () => {
const U = randomBytes(32);
const code = await formatRecoveryCode(U);
// Change one data character to a different valid one.
const i = 7;
const swapped = code[i] === "A" ? "B" : "A";
const typo = code.slice(0, i) + swapped + code.slice(i + 1);
const err = await parseRecoveryCode(typo).catch((e) => e);
expect(err).toBeInstanceOf(EmailRecoveryError);
expect(err.code).toBe("recovery_code_typo");
// A typo in the check group itself is caught too.
const last = code.at(-1) === "Z" ? "Y" : "Z";
expect((await parseRecoveryCode(code.slice(0, -1) + last).catch((e) => e)).code).toBe("recovery_code_typo");
});
it("rejects the wrong length and bad characters", async () => {
expect((await parseRecoveryCode("ABCDE-FGHJK").catch((e) => e)).code).toBe("recovery_code_invalid");
const code = await formatRecoveryCode(randomBytes(32));
expect((await parseRecoveryCode(code.replace(/^./, "U")).catch((e) => e)).code).toBe("recovery_code_invalid");
});
});
/** A fake apps/pwa: keeps S and the blob, "mails" U and one-time codes, and never stores U. */
function fakeServer() {
let enrollment: (EscrowMaterial & { active: boolean }) | null = null;
let otp: { code: string; used: boolean } | null = null;
const inbox: string[] = [];
const state = { starts: 0, claims: 0, failEnroll: false };
const client: EmailRecoveryClient = {
label: "fake.test (me@example.com)",
async status() {
return { enrolled: Boolean(enrollment?.active), enrolledAt: null, email: "m***@example.com", purchased: true, priceUsd: 5 };
},
async checkout() {
return { url: "https://coinpay.test/pay/cs_1", priceUsd: 5 };
},
async enroll(p: EscrowEnrollment) {
if (state.failEnroll) throw new EmailRecoveryError("Could not send the enrollment email", 502, "email_failed");
enrollment = { escrowBlob: p.escrowBlob, escrowIv: p.escrowIv, serverShare: p.serverShare, vaultCreatedAt: p.vaultCreatedAt, active: true };
inbox.push(await formatRecoveryCode(fromBase64(p.userShare)));
otp = null;
return { enrolled: true, email: "m***@example.com" };
},
async start() {
if (!enrollment?.active) throw new EmailRecoveryError("not enrolled", 404, "not_enrolled");
state.starts++;
otp = { code: String(Math.floor(Math.random() * 1e8)).padStart(8, "0"), used: false };
return { sent: true, email: "m***@example.com" };
},
async claim(code: string) {
state.claims++;
if (!otp || otp.used || otp.code !== code) throw new EmailRecoveryError("Wrong one-time code", 401, "wrong_code");
otp.used = true;
const { active: _active, ...material } = enrollment!;
return material;
},
async disable() {
const was = Boolean(enrollment?.active);
enrollment = null;
return { disabled: was };
},
};
return { client, inbox, state, otp: () => otp?.code ?? "" };
}
async function vaultOnDisk() {
const dir = mkdtempSync(join(tmpdir(), "opencreds-email-recovery-"));
dirs.push(dir);
const store = createVaultStore(dir);
const created = await createVault("old master password", { params: FAST });
store.writeMeta(created.meta);
const item = createItem("login", { name: "GitHub", login: { username: "me", password: "hunter2" } });
store.writeEnvelope(await encryptItem(created.userKey, item, created.meta.namespace));
return { store, ...created };
}
describe("recover --email, end to end against a fake server", () => {
it("new password unlocks; the old password and the old recovery key do not; the used code is dead", async () => {
const { store, meta, userKey, recoveryKey: oldRecoveryKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const enrolledCode = server.inbox.at(-1)!;
const said: string[] = [];
const result = await runEmailRecovery({
store,
client: server.client,
say: (l) => said.push(l),
prompts: {
recoveryCode: async () => enrolledCode,
oneTimeCode: async () => server.otp(),
newPassword: async () => "brand new master password",
},
});
expect(result.userKey).toEqual(userKey);
expect(result.recoveryKey).not.toBe(oldRecoveryKey);
expect(said.join("\n")).toMatch(/one-time code was emailed to m\*\*\*@example\.com/);
const onDisk = store.readMeta()!;
expect(onDisk.createdAt).toBe(meta.createdAt);
expect(await unlockVault(onDisk, "brand new master password")).toEqual(userKey);
await expect(unlockVault(onDisk, "old master password")).rejects.toThrow(/Wrong master password/);
await expect(unlockWithRecoveryKey(onDisk, oldRecoveryKey)).rejects.toThrow(/Wrong recovery key/);
expect(await unlockWithRecoveryKey(onDisk, result.recoveryKey)).toEqual(userKey);
// Re-armed with fresh shares: a new code was mailed and the old one no longer opens anything.
expect(result.reenrolled).toBe(true);
expect(server.inbox).toHaveLength(2);
expect(server.inbox[1]).not.toBe(enrolledCode);
await server.client.start();
const material = await server.client.claim(server.otp());
await expect(
recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(enrolledCode) }),
).rejects.toBeInstanceOf(RecoveryCodeMismatchError);
expect(
await recoverUserKeyByEmail({ meta: onDisk, material, userShare: await parseRecoveryCode(server.inbox[1]!) }),
).toEqual(userKey);
});
it("a wrong recovery code: clear mismatch error, the one-time code is spent, the vault untouched", async () => {
const { store, meta, userKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const before = JSON.stringify(store.readMeta());
const otherCode = await formatRecoveryCode(randomBytes(32)); // well-formed, just not ours
let asked = false;
const err = await runEmailRecovery({
store,
client: server.client,
prompts: {
recoveryCode: async () => otherCode,
oneTimeCode: async () => server.otp(),
newPassword: async () => {
asked = true;
return "x";
},
},
}).catch((e) => e);
expect(err).toBeInstanceOf(RecoveryCodeMismatchError);
expect(err.message).toMatch(/doesn't match/);
expect(asked).toBe(false);
expect(server.state.claims).toBe(1);
await expect(server.client.claim(server.otp())).rejects.toThrow(/Wrong one-time code/); // spent
expect(JSON.stringify(store.readMeta())).toBe(before);
expect((await server.client.status()).enrolled).toBe(true); // the purchase and enrollment stand
});
it("a typo in the recovery code costs nothing: no one-time code is requested", async () => {
const { store, meta, userKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const code = server.inbox.at(-1)!;
const typo = code.slice(0, 3) + (code[3] === "A" ? "B" : "A") + code.slice(4);
const err = await runEmailRecovery({
store,
client: server.client,
prompts: { recoveryCode: async () => typo, oneTimeCode: async () => "", newPassword: async () => "x" },
}).catch((e) => e);
expect(err.code).toBe("recovery_code_typo");
expect(server.state.starts).toBe(0);
});
it("if re-enrolling fails the vault is still recovered, and the result says so", async () => {
const { store, meta, userKey } = await vaultOnDisk();
const server = fakeServer();
await enrollEmailRecovery(server.client, meta, userKey);
const code = server.inbox.at(-1)!;
server.state.failEnroll = true;
const result = await runEmailRecovery({
store,
client: server.client,
prompts: { recoveryCode: async () => code, oneTimeCode: async () => server.otp(), newPassword: async () => "new pw" },
});
expect(result.reenrolled).toBe(false);
expect(result.reenrollError).toMatch(/enrollment email/);
expect(await unlockVault(store.readMeta()!, "new pw")).toEqual(userKey);
});
it("the server never receives E, and U only in the enroll call", async () => {
const { meta, userKey } = await vaultOnDisk();
const seen: EscrowEnrollment[] = [];
const server = fakeServer();
const spy: EmailRecoveryClient = {
...server.client,
enroll: async (p) => {
seen.push({ ...p });
return server.client.enroll(p);
},
};
await enrollEmailRecovery(spy, meta, userKey);
const p = seen[0]!;
const E = combineEscrowKey(fromBase64(p.serverShare), fromBase64(p.userShare));
for (const value of Object.values(p)) expect(value).not.toBe(toBase64(E));
expect(await openEscrow(E, p, meta.namespace)).toEqual(userKey);
});
});

View file

@ -0,0 +1,401 @@
/**
* Email recovery (opt-in, paid): a way back into a personal vault after the
* master password AND the offline recovery key are gone, through the account's
* mailbox.
*
* The client generates a random escrow key E and encrypts the user key K under
* it. E is then split into two XOR shares:
*
* S random 32 bytes held by the server, encrypted under its escrow key
* U E XOR S mailed to the account once, as a recovery code; never stored
*
* Neither share alone says anything about E (each is uniformly random on its
* own), so neither the database, nor the database plus the server's env, nor
* the enrollment email alone opens the vault. Recovering needs U (the user's
* mailbox, from enrollment) and S, which the server releases only against a
* fresh one-time code mailed at recovery time.
*
* The server sees U in transit once, at enrollment, to put it in the email. A
* live server compromise at that moment, or an attacker holding both the
* mailbox and a live server, can recover the vault; that is the trade this
* feature makes, and why it is opt-in. See docs/opencreds/security.md.
*/
import { decryptItem } from "./items.js";
import { emailEscrowLabel } from "./kdf.js";
import { aesGcmDecrypt, aesGcmEncrypt, fromBase64, KEY_BYTES, randomBytes, sha256, toBase64, utf8Encode } from "./primitives.js";
import type { VaultStore } from "./store.js";
import type { Envelope, VaultMeta } from "./types.js";
import { assertProfile, resetRecoveryKey, rewrapUserKey } from "./vault-key.js";
/** Crockford base32, the same alphabet as the offline recovery key. */
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
/** U is 256 bits; 55 characters carry 275, the last 19 always zero, so the groups come out even. */
export const RECOVERY_CODE_DATA_CHARS = 55;
/** One trailing group of five is a 25-bit checksum, so a typo is caught before anything is spent. */
export const RECOVERY_CODE_CHECK_CHARS = 5;
export const RECOVERY_CODE_CHARS = RECOVERY_CODE_DATA_CHARS + RECOVERY_CODE_CHECK_CHARS;
/** Domain separation for the checksum hash; the server renders codes with the same rule. */
export const RECOVERY_CODE_CHECK_PREFIX = "opencreds:email-recovery-code:v1";
/** Something went wrong in a way the person can act on. */
export class EmailRecoveryError extends Error {
constructor(
message: string,
readonly status?: number,
readonly code?: string,
readonly checkoutUrl?: string,
) {
super(message);
}
}
/** The recovery code decrypted nothing: it is not the code for this enrollment. */
export class RecoveryCodeMismatchError extends EmailRecoveryError {
constructor() {
super(
"That recovery code doesn't match this vault's email recovery. Use the code from the most recent " +
"\"vault email-recovery code\" email; an older one stops working when recovery is re-enabled.",
undefined,
"recovery_code_mismatch",
);
}
}
/** What the client sends to enroll. U (`userShare`) is mailed by the server and never stored. */
export interface EscrowEnrollment {
escrowBlob: string;
escrowIv: string;
serverShare: string;
userShare: string;
vaultCreatedAt: string;
}
/** What the server releases on a successful claim. */
export interface EscrowMaterial {
escrowBlob: string;
escrowIv: string;
serverShare: string;
vaultCreatedAt: string;
}
export interface EmailRecoveryStatus {
enrolled: boolean;
enrolledAt: string | null;
/** Masked, e.g. a***@example.com. */
email: string | null;
purchased: boolean;
priceUsd: number;
}
/** The account's email-recovery endpoints. The logicsrc CLI provides one. */
export interface EmailRecoveryClient {
label: string;
status(): Promise<EmailRecoveryStatus>;
checkout(): Promise<{ url: string; priceUsd: number }>;
/** 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>;
disable(): Promise<{ disabled: boolean }>;
}
// ------------------------------------------------------------- shares ---
export function xorBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
if (a.length !== b.length) throw new Error("XOR shares must be the same length");
const out = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) out[i] = a[i]! ^ b[i]!;
return out;
}
/** Split E into a random server share S and the user share U = E XOR S. */
export function splitEscrowKey(escrowKey: Uint8Array): { serverShare: Uint8Array; userShare: Uint8Array } {
if (escrowKey.length !== KEY_BYTES) throw new Error(`The escrow key must be ${KEY_BYTES} bytes`);
const serverShare = randomBytes(KEY_BYTES);
return { serverShare, userShare: xorBytes(escrowKey, serverShare) };
}
/** E = S XOR U. */
export function combineEscrowKey(serverShare: Uint8Array, userShare: Uint8Array): Uint8Array {
if (serverShare.length !== KEY_BYTES || userShare.length !== KEY_BYTES) {
throw new Error(`Both escrow shares must be ${KEY_BYTES} bytes`);
}
return xorBytes(serverShare, userShare);
}
/** Overwrite key material that is no longer needed. Best effort: JS gives no stronger guarantee. */
export function wipe(...buffers: Array<Uint8Array | undefined>): void {
for (const b of buffers) b?.fill(0);
}
// --------------------------------------------------------------- escrow ---
/** AAD binds the escrow copy to its purpose and to one vault (createdAt survives password changes). */
export function escrowAad(namespace: string, vaultCreatedAt: string): Uint8Array {
return utf8Encode(`${emailEscrowLabel(namespace)}|${vaultCreatedAt}`);
}
/** Encrypt the user key under a fresh random escrow key E. */
export async function sealEscrow(
userKey: Uint8Array,
meta: VaultMeta,
): Promise<{ escrowKey: Uint8Array; escrowBlob: string; escrowIv: string }> {
assertProfile(meta, ["user"]);
if (!meta.createdAt) throw new Error("This vault has no createdAt; it cannot be enrolled in email recovery");
const escrowKey = randomBytes(KEY_BYTES);
const { iv, ciphertext } = await aesGcmEncrypt(escrowKey, userKey, escrowAad(meta.namespace, meta.createdAt));
return { escrowKey, escrowBlob: toBase64(ciphertext), escrowIv: toBase64(iv) };
}
/** Decrypt the user key with E. A wrong E (a wrong U) fails the GCM tag: {@link RecoveryCodeMismatchError}. */
export async function openEscrow(
escrowKey: Uint8Array,
material: Pick<EscrowMaterial, "escrowBlob" | "escrowIv" | "vaultCreatedAt">,
namespace: string,
): Promise<Uint8Array> {
try {
return await aesGcmDecrypt(
escrowKey,
fromBase64(material.escrowIv),
fromBase64(material.escrowBlob),
escrowAad(namespace, material.vaultCreatedAt),
);
} catch {
throw new RecoveryCodeMismatchError();
}
}
/**
* Everything enrollment sends, plus a `wipe` that zeroes E, S and U. The
* payload's base64 strings cannot be zeroed; they live only until the request
* is sent.
*/
export async function prepareEnrollment(
meta: VaultMeta,
userKey: Uint8Array,
): Promise<{ payload: EscrowEnrollment; wipe: () => void }> {
const { escrowKey, escrowBlob, escrowIv } = await sealEscrow(userKey, meta);
const { serverShare, userShare } = splitEscrowKey(escrowKey);
return {
payload: {
escrowBlob,
escrowIv,
serverShare: toBase64(serverShare),
userShare: toBase64(userShare),
vaultCreatedAt: meta.createdAt!,
},
wipe: () => wipe(escrowKey, serverShare, userShare),
};
}
/** Enroll (or re-enroll) this vault. The server mails U and keeps S; a prior enrollment stops working. */
export async function enrollEmailRecovery(
client: EmailRecoveryClient,
meta: VaultMeta,
userKey: Uint8Array,
): Promise<{ enrolled: boolean; email: string }> {
const prepared = await prepareEnrollment(meta, userKey);
try {
return await client.enroll(prepared.payload);
} finally {
prepared.wipe();
prepared.payload.userShare = "";
prepared.payload.serverShare = "";
}
}
// -------------------------------------------------------- recovery code ---
function encodeBits(bytes: Uint8Array, chars: number): string {
let out = "";
for (let i = 0; i < chars; i++) {
let v = 0;
for (let b = 0; b < 5; b++) {
const bit = i * 5 + b;
const byte = bit >> 3;
v = (v << 1) | (byte < bytes.length ? (bytes[byte]! >> (7 - (bit & 7))) & 1 : 0);
}
out += ALPHABET[v];
}
return out;
}
/** Decode `text` into `length` bytes; `padOk` is false when a bit past them is set. */
function decodeBits(text: string, length: number): { bytes: Uint8Array; padOk: boolean } {
const bytes = new Uint8Array(length);
let padOk = true;
for (let i = 0; i < text.length; i++) {
const v = ALPHABET.indexOf(text[i]!);
if (v < 0) throw new EmailRecoveryError(`Invalid character in recovery code: ${text[i]}`, undefined, "recovery_code_invalid");
for (let b = 0; b < 5; b++) {
const bit = i * 5 + b;
const set = (v >> (4 - b)) & 1;
const byte = bit >> 3;
if (byte < length) bytes[byte] = (bytes[byte] ?? 0) | (set << (7 - (bit & 7)));
else if (set) padOk = false;
}
}
return { bytes, padOk };
}
async function checkGroup(userShare: Uint8Array): Promise<string> {
const digest = await sha256(new Uint8Array([...utf8Encode(RECOVERY_CODE_CHECK_PREFIX), ...userShare]));
return encodeBits(digest, RECOVERY_CODE_CHECK_CHARS);
}
/**
* Render U for the enrollment email: 11 groups of data and one check group,
* twelve groups of five in all.
*/
export async function formatRecoveryCode(userShare: Uint8Array): Promise<string> {
if (userShare.length !== KEY_BYTES) throw new Error(`The user share must be ${KEY_BYTES} bytes`);
const text = encodeBits(userShare, RECOVERY_CODE_DATA_CHARS) + (await checkGroup(userShare));
return (text.match(/.{1,5}/g) ?? []).join("-");
}
/**
* Parse a recovery code back into U, tolerating case, spaces and dashes and
* Crockford's confusables. A typo fails the check group here, before the
* one-time code is asked for or spent.
*/
export async function parseRecoveryCode(input: string): Promise<Uint8Array> {
const clean = String(input || "")
.toUpperCase()
.replace(/[^0-9A-Z]/g, "")
.replace(/O/g, "0")
.replace(/[IL]/g, "1");
if (clean.length !== RECOVERY_CODE_CHARS) {
throw new EmailRecoveryError(
`That recovery code has ${clean.length} characters; it should have ${RECOVERY_CODE_CHARS} (12 groups of 5). ` +
"Copy it again from the enrollment email.",
undefined,
"recovery_code_invalid",
);
}
const { bytes, padOk } = decodeBits(clean.slice(0, RECOVERY_CODE_DATA_CHARS), KEY_BYTES);
const check = clean.slice(RECOVERY_CODE_DATA_CHARS);
if (!padOk || check !== (await checkGroup(bytes))) {
wipe(bytes);
throw new EmailRecoveryError(
"That recovery code has a typo (its last group, the check group, does not match). Copy it again from the enrollment email.",
undefined,
"recovery_code_typo",
);
}
return bytes;
}
// ------------------------------------------------------------- recovery ---
/**
* K from the server's material and the user's code. Checks the material is for
* this vault, and that K actually opens an item when there is one to try.
*/
export async function recoverUserKeyByEmail(input: {
meta: VaultMeta;
material: EscrowMaterial;
userShare: Uint8Array;
envelopes?: Envelope[];
}): Promise<Uint8Array> {
const { meta, material, userShare } = input;
assertProfile(meta, ["user"]);
if (material.vaultCreatedAt !== meta.createdAt) {
throw new EmailRecoveryError(
`Email recovery was enrolled for a different vault (created ${material.vaultCreatedAt}); this one was created ${meta.createdAt ?? "?"}.`,
undefined,
"vault_mismatch",
);
}
const serverShare = fromBase64(material.serverShare);
const escrowKey = combineEscrowKey(serverShare, userShare);
try {
const userKey = await openEscrow(escrowKey, material, meta.namespace);
const probe = input.envelopes?.[0];
if (probe) {
try {
await decryptItem(userKey, probe, meta.namespace);
} catch {
wipe(userKey);
throw new EmailRecoveryError(
"The escrowed key does not open this vault's items. Nothing was changed.",
undefined,
"escrow_stale",
);
}
}
return userKey;
} finally {
wipe(serverShare, escrowKey);
}
}
export interface EmailRecoveryPrompts {
/** The recovery code from the enrollment email. */
recoveryCode(): Promise<string>;
/** The 8-digit one-time code mailed by `start`. */
oneTimeCode(email: string | undefined): Promise<string>;
/** The new master password, already confirmed. */
newPassword(): Promise<string>;
}
export interface EmailRecoveryResult {
meta: VaultMeta;
userKey: Uint8Array;
/** The new offline recovery key, to print once. */
recoveryKey: string;
reenrolled: boolean;
reenrolledEmail?: string;
reenrollError?: string;
}
/**
* The whole `recover --email` flow over a store and a client.
*
* Order matters: the recovery code is checked (checksum) before a one-time code
* is requested, so a typo costs nothing; the one-time code is spent on claim;
* nothing on disk changes until K is proven. After the new password is set,
* email recovery is re-armed with fresh shares, so the code just used is dead.
*/
export async function runEmailRecovery(opts: {
store: VaultStore;
client: EmailRecoveryClient;
prompts: EmailRecoveryPrompts;
say?: (line: string) => void;
}): Promise<EmailRecoveryResult> {
const { store, client, prompts } = opts;
const say = opts.say ?? (() => {});
const meta = store.readMeta();
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 password = await prompts.newPassword();
if (!password) throw new EmailRecoveryError("A master password is required", undefined, "no_password");
const rewrapped = await rewrapUserKey(meta, userKey, password);
const reset = await resetRecoveryKey(rewrapped, userKey);
store.writeMeta(reset.meta);
const result: EmailRecoveryResult = { meta: reset.meta, userKey, recoveryKey: reset.recoveryKey, reenrolled: false };
try {
const enrolled = await enrollEmailRecovery(client, reset.meta, userKey);
result.reenrolled = Boolean(enrolled.enrolled);
result.reenrolledEmail = enrolled.email;
} catch (err) {
result.reenrollError = (err as Error).message;
}
return result;
}

View file

@ -53,6 +53,7 @@ export {
wrapLabel,
authLabel,
recoveryLabel,
emailEscrowLabel,
itemLabel,
databaseLabel,
assertUsableNamespace,
@ -177,6 +178,33 @@ export {
type SyncState,
} from "./sync.js";
export {
EmailRecoveryError,
RecoveryCodeMismatchError,
RECOVERY_CODE_CHARS,
RECOVERY_CODE_CHECK_CHARS,
RECOVERY_CODE_CHECK_PREFIX,
RECOVERY_CODE_DATA_CHARS,
combineEscrowKey,
enrollEmailRecovery,
escrowAad,
formatRecoveryCode,
openEscrow,
parseRecoveryCode,
prepareEnrollment,
recoverUserKeyByEmail,
runEmailRecovery,
sealEscrow,
splitEscrowKey,
xorBytes,
type EmailRecoveryClient,
type EmailRecoveryPrompts,
type EmailRecoveryResult,
type EmailRecoveryStatus,
type EscrowEnrollment,
type EscrowMaterial,
} from "./email-recovery.js";
export { auditEvent, fingerprint, type AuditInput } from "./audit.js";
export {

View file

@ -58,6 +58,15 @@ export function recoveryLabel(namespace: Namespace): string {
return `${namespace}:vault:recovery:v1`;
}
/**
* Associated data for the email-recovery escrow copy of the user key. Not an
* HKDF label: the escrow key is random, not derived, so the label only binds
* the ciphertext to its purpose (and, with the vault's createdAt, to one vault).
*/
export function emailEscrowLabel(namespace: Namespace): string {
return `${namespace}:vault:email-escrow:v1`;
}
export function itemLabel(namespace: Namespace, version: number, id: string): string {
return `${namespace}:vault:item:${version}:${id}`;
}