diff --git a/apps/web/src/components/SeedSave.tsx b/apps/web/src/components/SeedSave.tsx
new file mode 100644
index 0000000..a8087a5
--- /dev/null
+++ b/apps/web/src/components/SeedSave.tsx
@@ -0,0 +1,90 @@
+// "Print" / "Save as text file" for the recovery phrase (onboarding + Settings).
+// Paper is the safe copy, so Print leads; the file is behind a warning, because
+// file-stealing malware hunts for exactly this kind of file. Printing shows only
+// the .seed-print sheet below (index.css hides the app), so a printout or "Save as
+// PDF" holds the words and nothing else.
+import { useState } from "react";
+import { createPortal } from "react-dom";
+import { saveSeedFile } from "../services/seed-file";
+
+export default function SeedSave({ words }: { words: string[] }) {
+ const [asking, setAsking] = useState(false);
+ const [result, setResult] = useState(null);
+
+ // The warning's own button is the click that opens the save dialog (it needs a
+ // fresh click, which a confirm() popup in between wouldn't give it).
+ async function save() {
+ setAsking(false);
+ setResult(null);
+ try {
+ const r = await saveSeedFile(words);
+ if (r === "saved") setResult("Saved.");
+ if (r === "downloaded") {
+ setResult(
+ "It's in your Downloads folder. Move it somewhere offline, like a USB stick, then delete it from Downloads.",
+ );
+ }
+ } catch (e) {
+ setResult(e instanceof Error ? `Couldn't save the file: ${e.message}` : "Couldn't save the file.");
+ }
+ }
+
+ const secondary = "rounded-lg bg-raised px-3 py-1.5 text-xs text-text-secondary transition-colors hover:bg-border-strong";
+ return (
+ <>
+
+
+
+
+ {asking ? (
+
+
+ Malware that steals files looks for exactly this kind of file. Anyone who gets it can take
+ over your account, and there’s no way to lock them out again.
+
+
+ Save it straight to a USB stick or an encrypted drive — not Downloads, the Desktop or a
+ cloud-synced folder — and never email or message it.
+
+
+
+
+
+
+ ) : (
+
+ Best: print it and keep the paper somewhere safe. A file or PDF opens your account just like
+ the words do.
+
+ )}
+ {result &&
{result}
}
+ {createPortal(
+
+
Privex recovery phrase
+
+ Anyone who has these words can take over your Privex account. Keep this paper somewhere
+ safe. Privex will never ask you for these words.
+
+
+ {words.map((w, i) => (
+
{w}
+ ))}
+
+
,
+ document.body,
+ )}
+ >
+ );
+}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 5b738f0..463b9ad 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -202,3 +202,34 @@
66% { background-position: 8px -6px; }
100% { background-position: 0 0; }
}
+
+/* Recovery-phrase printout (SeedSave): while it's on the page, printing shows only
+ it - black on white, whatever the theme. */
+.seed-print {
+ display: none;
+}
+@media print {
+ html:has(.seed-print),
+ html:has(.seed-print) body {
+ background: #fff !important;
+ }
+ body:has(> .seed-print) > :not(.seed-print) {
+ display: none !important;
+ }
+ .seed-print {
+ display: block;
+ color: #000;
+ font: 12pt/1.5 system-ui, sans-serif;
+ }
+ .seed-print h1 {
+ font-size: 18pt;
+ font-weight: 600;
+ margin-bottom: 8pt;
+ }
+ .seed-print ol {
+ columns: 3;
+ margin-top: 16pt;
+ list-style: decimal inside;
+ font: 14pt/2 ui-monospace, monospace;
+ }
+}
diff --git a/apps/web/src/onboarding/flow.ts b/apps/web/src/onboarding/flow.ts
index 2b653b5..af7c480 100644
--- a/apps/web/src/onboarding/flow.ts
+++ b/apps/web/src/onboarding/flow.ts
@@ -138,7 +138,7 @@ export async function completeRegistration(
}
/** STEP 6: ensure a live session (re-auth if the in-memory token was lost to a
- * refresh), strip the mnemonic from storage, and enter the app. */
+ * refresh), mark onboarding done, and enter the app. */
export async function finishOnboarding(crypto: CryptoApi = workerCrypto): Promise {
const bundle = await loadBundle();
if (!bundle) throw new Error("no identity to finalize");
diff --git a/apps/web/src/onboarding/store.ts b/apps/web/src/onboarding/store.ts
index f5ef19e..be2f322 100644
--- a/apps/web/src/onboarding/store.ts
+++ b/apps/web/src/onboarding/store.ts
@@ -2,7 +2,7 @@
// persisted AES-GCM-encrypted under the WebCrypto master key so a closed browser
// resumes with the SAME keys (stable px_id). Plaintext key material never lands
// in IndexedDB. A coarse progress marker lives in the (non-sensitive) settings
-// table; the seed mnemonic is stripped from storage once onboarding completes.
+// table. The seed mnemonic stays in the encrypted bundle (see finalizeIdentity).
import { db } from "../db";
import { getMasterKey } from "../crypto/keystore";
import { encryptString, decryptString } from "../db/encrypted-db";
diff --git a/apps/web/src/screens/Onboarding.tsx b/apps/web/src/screens/Onboarding.tsx
index 2c3601d..f8c53ec 100644
--- a/apps/web/src/screens/Onboarding.tsx
+++ b/apps/web/src/screens/Onboarding.tsx
@@ -4,18 +4,19 @@
// server in the clear.
//
// Flow: welcome → keys (forge + identicon reveal) → register (PoW) → secure
-// (recovery) → safety orientation → enter. finishOnboarding() strips the mnemonic
-// and signs in, so it runs at the end of the recovery step; the safety step is a
+// (recovery) → safety orientation → enter. finishOnboarding() signs in, so it
+// runs at the end of the recovery step; the safety step is a
// post-signin orientation shown once (progress is already "done" on reload).
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Link, useNavigate } from "react-router-dom";
import { completeRegistration, finishOnboarding, generateIdentity } from "../onboarding/flow";
import { loadBundle, loadProgress } from "../onboarding/store";
import { checkConfirm, pickConfirmIndices } from "../onboarding/seed-confirm";
-import { enableOpaqueRecovery, opaqueRecoveryStatus } from "../services/recovery";
+import { enableOpaqueRecovery, opaqueRecoveryStatus, PASSWORD_MANAGER_NOTE } from "../services/recovery";
import { db } from "../db";
import Avatar from "../components/Avatar";
import { SEED_SAVED_KEY } from "../components/FinishSetup";
+import SeedSave from "../components/SeedSave";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { ArrowLeftIcon, CheckIcon, KeyIcon, LockIcon, ShieldCheckIcon, WarningTriangleIcon } from "../components/icons";
@@ -150,6 +151,7 @@ export default function Onboarding() {
if (step === "password")
return (
{
setError(null);
@@ -344,10 +346,12 @@ function Registering({
// --- STEP 4 (sub): password recovery ---
function PasswordStep({
+ userId,
onSubmit,
onBack,
error,
}: {
+ userId: string;
onSubmit: (pw: string) => Promise;
onBack: () => void;
error: string | null;
@@ -386,46 +390,56 @@ function PasswordStep({
your password can unlock — we can’t read it.
}
);
@@ -485,7 +499,7 @@ function RecoveryStep({
void db.settings.put({ key: SEED_SAVED_KEY, value: true });
void finish();
} else {
- setConfirmError("Those words don't match. Check your written copy.");
+ setConfirmError("Those words don't match. Check your saved copy.");
}
}
@@ -506,8 +520,8 @@ function RecoveryStep({
{!revealed ? (
<>
- 24 words that are your account. Write them down and keep them offline — we
- will never show them again, and never ask for them.
+ 24 words that are your account. Keep a copy offline — on paper, or as a file
+ or printout. We’ll never ask you for them.
))}
+
Store these somewhere safe before continuing.
>
) : (
diff --git a/apps/web/src/screens/Recovery.tsx b/apps/web/src/screens/Recovery.tsx
index 890a1d4..b3a1644 100644
--- a/apps/web/src/screens/Recovery.tsx
+++ b/apps/web/src/screens/Recovery.tsx
@@ -1,7 +1,7 @@
-// Account recovery (docs 4.2). Restore an identity on a fresh device:
-// A - password (OPAQUE), B - emergency contacts (deferred), C - seed phrase.
-// Message history is NOT restored (it lives only on devices).
-import { useEffect, useState } from "react";
+// Account recovery (docs 4.2 / 6). Restore an identity on a fresh device with a
+// password (OPAQUE), the seed phrase, or emergency contacts. Message history comes
+// back only from an encrypted history backup, offered once the account is back.
+import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
pollContactRecovery,
@@ -10,12 +10,16 @@ import {
startContactRecovery,
type RecoverySession,
} from "../services/recovery";
+import { backupStatus, restoreHistory } from "../services/history-backup";
+import { parseSeedText } from "../services/seed-file";
import { ArrowLeftIcon } from "../components/icons";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import * as api from "../api/client";
type Tab = "password" | "seed" | "contacts";
+const STATUS_TIMEOUT_MS = 10_000;
+
function Shell({ children }: { children: React.ReactNode }) {
return (
@@ -29,17 +33,50 @@ export default function Recovery() {
const [tab, setTab] = useState("password");
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
+ const [offerRestore, setOfferRestore] = useState(false);
+
+ const enter = () => nav("/", { replace: true });
- async function run(fn: () => Promise) {
+ // Back in: offer the encrypted history backup if there is one. (Settings →
+ // Recovery makes this same status call every time it opens.)
+ async function recovered() {
+ let count = 0;
+ let timer: ReturnType | undefined;
+ try {
+ // Bounded: the account is already back, so a stalled request mustn't hold
+ // this screen on "Recovering…".
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error("backup status timed out")), STATUS_TIMEOUT_MS);
+ });
+ count = (await Promise.race([backupStatus(), timeout])).count;
+ } catch {
+ // No status, nothing to offer - restore stays available in Settings.
+ } finally {
+ clearTimeout(timer);
+ }
+ if (count > 0) setOfferRestore(true);
+ else enter();
+ }
+
+ async function run(fn: () => Promise) {
setBusy(true);
setError(null);
try {
await fn();
- nav("/", { replace: true });
} catch (e) {
setError(e instanceof Error ? e.message : "Recovery failed.");
setBusy(false);
+ return;
}
+ await recovered();
+ }
+
+ if (offerRestore) {
+ return (
+
+
+
+ );
}
return (
@@ -47,8 +84,8 @@ export default function Recovery() {
Recover your account
- Your identity is restored from your master key. Message history stays on your devices and
- won’t be recovered.
+ This brings back your Privex ID and keys. Your chats come back only if you turned on
+ encrypted chat backup.
@@ -71,8 +108,8 @@ export default function Recovery() {
}
@@ -80,59 +117,139 @@ export default function Recovery() {
);
}
-function PasswordRecovery({ busy, onRun }: { busy: boolean; onRun: (fn: () => Promise) => void }) {
+type RunFn = (fn: () => Promise) => void;
+
+function PasswordRecovery({ busy, onRun }: { busy: boolean; onRun: RunFn }) {
const [pxId, setPxId] = useState("");
const [password, setPassword] = useState("");
+ const id = pxId.trim().toLowerCase();
+ const ready = !busy && !!id && !!password;
+ // A real form with username + current-password, so a password manager can fill
+ // (and save) the ID and password together.
return (
-
+
+
);
}
-function SeedRecovery({ busy, onRun }: { busy: boolean; onRun: (fn: () => Promise) => void }) {
- const [phrase, setPhrase] = useState("");
- const wordCount = phrase.trim() ? phrase.trim().split(/\s+/).length : 0;
+/** bip39's errors count words from 0 and read like a stack trace. */
+function friendlySeedError(e: unknown): Error {
+ const msg = e instanceof Error ? e.message : String(e);
+ const unknown = /unknown word \(word (\d+)\)/.exec(msg);
+ if (unknown) {
+ return new Error(`Word ${Number(unknown[1]) + 1} isn't a recovery-phrase word. Check its spelling.`);
+ }
+ if (msg.includes("invalid checksum")) {
+ return new Error("These words aren't a valid recovery phrase. One may be misspelled or out of order.");
+ }
+ return e instanceof Error ? e : new Error(msg);
+}
+
+// A saved phrase file is under 1 KB; anything this big isn't one.
+const MAX_SEED_FILE = 16 * 1024;
+
+function SeedRecovery({ busy, onRun, onEdit }: { busy: boolean; onRun: RunFn; onEdit: () => void }) {
+ const [phrase, setPhraseState] = useState("");
+ const setPhrase = (v: string) => {
+ setPhraseState(v);
+ onEdit(); // the last attempt's error no longer applies
+ };
+ const [fileError, setFileError] = useState(null);
+ // Pasting the saved file, the numbered list or the bare words all work.
+ const words = parseSeedText(phrase);
+
+ // Read on this device as plain text - never uploaded, never kept. Only the
+ // words parsed out of it are used.
+ async function openFile(file: File | undefined) {
+ setFileError(null);
+ if (!file) return;
+ if (file.size > MAX_SEED_FILE) {
+ setFileError("That file is too big to be a saved recovery phrase.");
+ return;
+ }
+ const found = parseSeedText(await file.text());
+ if (found.length !== 24) {
+ setFileError("Couldn't find 24 words in that file. You can paste or type them instead.");
+ return;
+ }
+ setPhrase(found.join(" "));
+ }
+
return (
@@ -731,6 +744,7 @@ function SeedPhraseView() {
))}
Store these offline. We will never ask for them.
+
copy(phraseText)}
diff --git a/apps/web/src/services/recovery.ts b/apps/web/src/services/recovery.ts
index 145a643..955f4a1 100644
--- a/apps/web/src/services/recovery.ts
+++ b/apps/web/src/services/recovery.ts
@@ -5,7 +5,8 @@
// auth.
// Both re-derive the SAME identity keys (same px_id) from the master seed, then
// re-provision fresh prekeys (SPK + OPKs are ephemeral) so the recovered device can
-// receive messages again. Message history is NOT restored - it lives only on devices.
+// receive messages again. Message history comes back only from the opt-in encrypted
+// history backup (the Recovery screen offers it).
import * as api from "../api/client";
import { cryptoCall } from "../workers/crypto-client";
import { useAuth } from "../store/auth";
@@ -133,6 +134,15 @@ async function requireRecoverySession(): Promise<{ bundle: IdentityBundle; token
return { bundle, token };
}
+/** Shown wherever a recovery password is set. The form lets password managers save
+ * it under the Privex ID, and that pair is everything a takeover needs - so the
+ * risk to name is malware reading the browser's own password store, which is
+ * what stolen-data logs are made of. */
+export const PASSWORD_MANAGER_NOTE =
+ "Saving this in a password manager? Use a separate app with its own master password, " +
+ "not your browser's built-in one: malware steals browser-saved passwords, and with your " +
+ "Privex ID this password is all it takes to open your account.";
+
export async function opaqueRecoveryStatus(): Promise {
const token = useAuth.getState().sessionToken;
if (!token) throw new Error("not authenticated");
diff --git a/apps/web/src/services/seed-file.ts b/apps/web/src/services/seed-file.ts
new file mode 100644
index 0000000..7df8d6d
--- /dev/null
+++ b/apps/web/src/services/seed-file.ts
@@ -0,0 +1,84 @@
+// The recovery phrase as a text file (docs 6, path 4). Made and read on this
+// device only - no network, nothing kept. The file holds the words and how to
+// keep them safe: no Privex ID, no date, nothing it doesn't need.
+
+export const SEED_FILE_NAME = "privex-recovery-phrase.txt";
+
+/** Keep digits out of the prose: parseSeedText reads "number word" pairs. */
+export function seedFileText(words: string[]): string {
+ return [
+ "PRIVEX RECOVERY PHRASE",
+ "",
+ "Anyone who has these words can take over your Privex account.",
+ "Safest: print this or copy it onto paper, keep that somewhere safe, and delete this file.",
+ "Never keep it in cloud-synced folders, email, chats or screenshots.",
+ "Privex will never ask you for these words.",
+ "",
+ ...words.map((w, i) => `${i + 1}. ${w}`),
+ "",
+ "To recover: open Privex, choose Recover your account, then Seed phrase,",
+ "and open this file or paste the words.",
+ "",
+ ].join("\n");
+}
+
+// File System Access API (desktop Chrome/Edge); not in TypeScript's DOM types yet.
+type SaveFilePicker = (opts: {
+ suggestedName: string;
+ types: { description: string; accept: Record }[];
+}) => Promise;
+
+/** Save the file. Where the browser can ask where (desktop Chrome/Edge), the user
+ * picks the place - a USB stick, say - so it doesn't just land in Downloads.
+ * Elsewhere it's a normal download. Call from a click (the picker needs one). */
+export async function saveSeedFile(words: string[]): Promise<"saved" | "downloaded" | "cancelled"> {
+ const blob = new Blob([seedFileText(words)], { type: "text/plain;charset=utf-8" });
+ const pick = (globalThis as { showSaveFilePicker?: SaveFilePicker }).showSaveFilePicker;
+ if (pick) {
+ let handle: FileSystemFileHandle | undefined;
+ try {
+ handle = await pick({
+ suggestedName: SEED_FILE_NAME,
+ types: [{ description: "Text file", accept: { "text/plain": [".txt"] } }],
+ });
+ } catch (e) {
+ if ((e as { name?: string }).name === "AbortError") return "cancelled";
+ // The picker refused (e.g. the click's activation ran out): plain download below.
+ }
+ if (handle) {
+ // A failed write throws to the caller - never quietly download instead of
+ // saving where the user chose.
+ const out = await handle.createWritable();
+ await out.write(blob);
+ await out.close();
+ return "saved";
+ }
+ }
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = SEED_FILE_NAME;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000); // some browsers read it after click()
+ return "downloaded";
+}
+
+/** The words in pasted or uploaded text. A numbered list ("1. word", "1word", in any
+ * order) is read by number; anything else is every word in order. Case,
+ * punctuation and surrounding text don't matter. Two different words under one
+ * number give [] - there's no telling which is right. */
+export function parseSeedText(text: string): string[] {
+ const tokens = text.normalize("NFKD").toLowerCase().match(/\d+|[a-z]+/g) ?? [];
+ const isWord = (t: string) => /^[a-z]/.test(t);
+ const numbered: string[] = [];
+ for (let i = 0; i + 1 < tokens.length; i++) {
+ const n = Number(tokens[i]);
+ const w = tokens[i + 1];
+ if (isWord(tokens[i]) || !isWord(w) || n < 1 || n > 24) continue;
+ if (numbered[n - 1] !== undefined && numbered[n - 1] !== w) return [];
+ numbered[n - 1] = w;
+ }
+ const byNumber = numbered.filter(Boolean);
+ // A few stray digits in a plain phrase ("3able") don't make it a numbered list.
+ return byNumber.length >= 12 ? byNumber : tokens.filter(isWord);
+}
diff --git a/apps/web/src/test/seed-file.test.ts b/apps/web/src/test/seed-file.test.ts
new file mode 100644
index 0000000..45aa9c3
--- /dev/null
+++ b/apps/web/src/test/seed-file.test.ts
@@ -0,0 +1,85 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { parseSeedText, saveSeedFile, SEED_FILE_NAME, seedFileText } from "../services/seed-file";
+
+const words = (
+ "abandon ability able about above absent absorb abstract absurd abuse access accident " +
+ "account accuse achieve acid acoustic acquire across act action actor actress actual"
+).split(" ");
+
+describe("recovery phrase file", () => {
+ it("reads back its own file", () => {
+ expect(parseSeedText(seedFileText(words))).toEqual(words);
+ });
+
+ it("reads a plain phrase in any case, spacing or punctuation", () => {
+ expect(parseSeedText(` ${words.join(", ").toUpperCase()}\r\n`)).toEqual(words);
+ });
+
+ it("reads a numbered list by number, even run together and out of order", () => {
+ // Copying the on-screen grid gives "1abandon2ability…".
+ expect(parseSeedText(words.map((w, i) => `${i + 1}${w}`).reverse().join(""))).toEqual(words);
+ });
+
+ it("treats a stray digit in a plain phrase as noise", () => {
+ expect(parseSeedText(words.join(" ").replace(" able ", " 3able "))).toEqual(words);
+ });
+
+ it("refuses two different words under one number", () => {
+ expect(parseSeedText(`${seedFileText(words)}\n2. zoo`)).toEqual([]);
+ });
+});
+
+describe("saving the file", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ function stubDownload() {
+ const a = { href: "", download: "", click: vi.fn() };
+ vi.stubGlobal("document", { createElement: () => a });
+ return a;
+ }
+
+ it("writes where the user picked, without downloading", async () => {
+ const written: string[] = [];
+ vi.stubGlobal("showSaveFilePicker", async () => ({
+ createWritable: async () => ({
+ write: async (b: Blob) => void written.push(await b.text()),
+ close: async () => {},
+ }),
+ }));
+ const a = stubDownload();
+ expect(await saveSeedFile(words)).toBe("saved");
+ expect(written).toEqual([seedFileText(words)]);
+ expect(a.click).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when the user cancels the picker", async () => {
+ vi.stubGlobal("showSaveFilePicker", async () => {
+ throw new DOMException("cancelled", "AbortError");
+ });
+ const a = stubDownload();
+ expect(await saveSeedFile(words)).toBe("cancelled");
+ expect(a.click).not.toHaveBeenCalled();
+ });
+
+ it("downloads when there's no picker, or the picker refuses", async () => {
+ const a = stubDownload();
+ expect(await saveSeedFile(words)).toBe("downloaded");
+ expect(a.download).toBe(SEED_FILE_NAME);
+ vi.stubGlobal("showSaveFilePicker", async () => {
+ throw new DOMException("no user gesture", "SecurityError");
+ });
+ expect(await saveSeedFile(words)).toBe("downloaded");
+ expect(a.click).toHaveBeenCalledTimes(2);
+ });
+
+ it("fails loudly when writing to the picked place fails - no quiet download", async () => {
+ vi.stubGlobal("showSaveFilePicker", async () => ({
+ createWritable: async () => {
+ throw new Error("disk full");
+ },
+ }));
+ const a = stubDownload();
+ await expect(saveSeedFile(words)).rejects.toThrow("disk full");
+ expect(a.click).not.toHaveBeenCalled();
+ });
+});
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 74a3b1a..76af550 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -287,14 +287,14 @@ Designate 2–3 trusted Privex contacts. Master key split via Shamir's Secret Sh
### Path 4: Seed Phrase (Power User Fallback)
-24-word BIP-39 mnemonic generated at registration. Stored nowhere by Privex. Deterministically regenerates all keypairs. Optional — user chooses to write it down.
+24-word BIP-39 mnemonic generated at registration. Stored nowhere by Privex. Deterministically regenerates all keypairs. Optional — the user keeps a copy offline: written down, or saved as a text file or printout that the app makes on the device (nothing is sent anywhere). Recovery takes the words typed, pasted, or read from that file, locally.
```
Recovery order (try in order):
1. OPAQUE (password) — any device, any time
2. Linked device — requires another device still active
3. Emergency contacts — requires 2 of 3 contacts to approve
- 4. Seed phrase — requires the 24 words written down at registration
+ 4. Seed phrase — requires the 24 words saved at registration
```
---