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) => ( +
  1. {w}
  2. + ))} +
+
, + 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.

- - setPw(e.target.value)} - minLength={8} - autoComplete="new-password" - className="mt-1 w-full rounded-lg border border-border-strong bg-input px-3 py-2 outline-none focus:border-border-focus" - /> - {pw && scorer && ( -
-
-
+
{ + e.preventDefault(); + if (!busy && strongEnough && matches) void submit(); + }} + > + {/* Lets a password manager file this password under your Privex ID. */} + + + setPw(e.target.value)} + minLength={8} + autoComplete="new-password" + className="mt-1 w-full rounded-lg border border-border-strong bg-input px-3 py-2 outline-none focus:border-border-focus" + /> + {pw && scorer && ( +
+
+
+
+

+ {labels[score]} + {!strongEnough && " - needs to be Strong or better"} +

-

- {labels[score]} - {!strongEnough && " - needs to be Strong or better"} -

-
- )} + )} - - setConfirm(e.target.value)} - autoComplete="new-password" - className="mt-1 w-full rounded-lg border border-border-strong bg-input px-3 py-2 outline-none focus:border-border-focus" - /> - {confirm && !matches &&

Passwords don’t match.

} + + setConfirm(e.target.value)} + autoComplete="new-password" + className="mt-1 w-full rounded-lg border border-border-strong bg-input px-3 py-2 outline-none focus:border-border-focus" + /> + {confirm && !matches &&

Passwords don’t match.

} +

{PASSWORD_MANAGER_NOTE}

- + +
{error &&

{error}

} ); @@ -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() {
{tab === "password" && } - {tab === "seed" && } - {tab === "contacts" && } + {tab === "seed" && setError(null)} />} + {tab === "contacts" && void recovered()} />}
{error &&

{error}

} @@ -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 ( -
+
{ + e.preventDefault(); + if (ready) onRun(() => recoverWithPassword(id, password)); + }} + > setPxId(e.target.value)} placeholder="px_…" - maxLength={35} + aria-label="Privex ID" + maxLength={40} spellCheck={false} autoCapitalize="none" + autoComplete="username" className="w-full rounded-lg bg-input border border-border-strong px-3 py-2 font-mono text-sm outline-none focus:border-border-focus" /> setPassword(e.target.value)} placeholder="Recovery password" + aria-label="Recovery password" minLength={8} autoComplete="current-password" className="w-full rounded-lg bg-input border border-border-strong px-3 py-2 outline-none focus:border-border-focus" /> -
+ ); } -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 (