RecoveryWordDisplay.tsx

11.0 KB · raw

1import { createSignal, createMemo, For, onCleanup, onMount, Show } from "solid-js";2import { sendMessage } from "../App";3import { PeachWordmark } from "../components/PeachMark";4import { RecoveryRuneBackground } from "../components/RecoveryRuneBackground";56interface RecoveryWordDisplayViewProps {7  onDone: () => void;8}910// Three random positions are confirmed each time this screen mounts, so a11// user can't get away with only memorizing a fixed set of slots.12function pickConfirmIndices(): number[] {13  const pool = Array.from({ length: 12 }, (_, i) => i);14  const rand = new Uint32Array(pool.length);15  crypto.getRandomValues(rand);16  for (let i = pool.length - 1; i > 0; i--) {17    const j = (rand[i] ?? 0) % (i + 1);18    const tmp = pool[i]!;19    pool[i] = pool[j]!;20    pool[j] = tmp;21  }22  return pool.slice(0, 3).sort((a, b) => a - b);23}2425export function RecoveryWordDisplayView(props: RecoveryWordDisplayViewProps) {26  // Chosen once per mount; the labels and the validation must agree.27  const confirmIndices = pickConfirmIndices();28  const [words, setWords] = createSignal<string[]>([]);29  const [error, setError] = createSignal("");30  const [loading, setLoading] = createSignal(true);31  const [needsPassword, setNeedsPassword] = createSignal(false);32  const [password, setPassword] = createSignal("");33  let requestEpoch = 0;34  let disposed = false;35  const [confirmWords, setConfirmWords] = createSignal(["", "", ""]);36  const [confirmError, setConfirmError] = createSignal("");37  const [confirmed, setConfirmed] = createSignal(false);38  // 5-second countdown before confirmation input is enabled39  const [countdown, setCountdown] = createSignal(5);40  let countdownTimer: ReturnType<typeof setInterval> | null = null;4142  onMount(async () => {43    await refreshWords();44    if (disposed) return;4546    // Start 5-second countdown47    let remaining = 5;48    countdownTimer = setInterval(() => {49      remaining -= 1;50      setCountdown(remaining);51      if (remaining <= 0 && countdownTimer) {52        clearInterval(countdownTimer);53        countdownTimer = null;54      }55    }, 1000);56  });5758  async function refreshWords(proof?: string): Promise<void> {59    const epoch = ++requestEpoch;60    setLoading(true);61    setError("");62    setPassword("");63    const current = () => epoch === requestEpoch && document.visibilityState !== "hidden";64    try {65      let res = await sendMessage({66        type: "GET_RECOVERY_WORDS",67        ...(proof ? { payload: { password: proof } } : {}),68      }) as { ok: boolean; data?: string[]; error?: string };69      if (!current()) return;70      if (res.error === "vault_locked" && proof) {71        const unlocked = await sendMessage({ type: "UNLOCK", payload: { password: proof } }) as { ok: boolean };72        if (!current()) return;73        if (!unlocked.ok) {74          setError("incorrect password");75          setNeedsPassword(true);76          return;77        }78        res = await sendMessage({ type: "GET_RECOVERY_WORDS", payload: { password: proof } }) as typeof res;79        if (!current()) return;80      }81      if (res.ok && res.data?.length === 12) {82        setWords(res.data);83        setNeedsPassword(false);84      } else {85        setNeedsPassword(true);86        if (res.error === "wrong_password") setError("incorrect password");87        else if (res.error !== "password_required" && res.error !== "vault_locked") setError("could not retrieve recovery words");88      }89    } catch {90      if (current()) {91        setNeedsPassword(true);92        setError("could not retrieve recovery words");93      }94    } finally {95      if (current()) setLoading(false);96    }97  }9899  function hideWords(): void {100    requestEpoch++;101    setWords([]);102    setConfirmed(false);103    setPassword("");104    setConfirmWords(["", "", ""]);105    setConfirmError("");106    setError("");107    setNeedsPassword(true);108    setLoading(false);109  }110111  const handleVisibilityChange = () => {112    if (document.visibilityState === "hidden") hideWords();113    else if (!confirmed()) void refreshWords();114  };115  const handleVaultMessage = (message: { type?: string }) => {116    if (message.type === "VAULT_LOCKED") hideWords();117  };118  document.addEventListener("visibilitychange", handleVisibilityChange);119  chrome.runtime?.onMessage?.addListener(handleVaultMessage);120121  onCleanup(() => {122    disposed = true;123    requestEpoch++;124    if (countdownTimer) clearInterval(countdownTimer);125    document.removeEventListener("visibilitychange", handleVisibilityChange);126    chrome.runtime?.onMessage?.removeListener?.(handleVaultMessage);127  });128129  async function handleConfirm() {130    const confirmed = confirmWords().map((w) => w.toLowerCase().trim());131    if (confirmed.some((w) => !w)) {132      setConfirmError("all three words are required");133      return;134    }135136    // Verify against stored words137    const stored = words();138    for (let i = 0; i < confirmIndices.length; i++) {139      const pos = confirmIndices[i]!;140      if (confirmed[i] !== stored[pos]) {141        setConfirmError(`word ${pos + 1} is incorrect`);142        return;143      }144    }145146    const epoch = requestEpoch;147    setConfirmed(true);148    setConfirmError("");149    // Successful confirmation ends the routing obligation.150    await sendMessage({ type: "CLEAR_RECOVERY_CONFIRM_PENDING" });151    // Small pause so user sees the success state, then proceed.152    await new Promise((r) => setTimeout(r, 600));153    if (epoch === requestEpoch && !disposed) props.onDone();154  }155156  const canConfirm = createMemo(() => words().length === 12 && countdown() <= 0 && !confirmed());157158  return (159    <section class="peach-screen peach-theme lock-screen lock-screen--recovery lock-screen--recovery-display">160      <RecoveryRuneBackground />161162      <header class="peach-screen-header">163        <div class="peach-wordmark-stack">164          <PeachWordmark class="peach-wordmark-wrap" />165        </div>166      </header>167168      <div class="peach-recovery-header">169        <h1 class="peach-onboarding-headline">save your recovery words</h1>170        <p class="peach-hint peach-hint--warning">171          write these down — you can view them again in Settings with your master password172        </p>173      </div>174175      <Show when={loading()}>176        <p class="peach-hint">loading...</p>177      </Show>178179      <Show when={error()}>180        <p class="peach-hint peach-hint-error">{error()}</p>181      </Show>182183      <Show when={needsPassword()}>184        <form onSubmit={(event) => { event.preventDefault(); if (password() && !loading()) void refreshWords(password()); }}>185          <label class="peach-label" for="recovery-reveal-password">master password</label>186          <input187            id="recovery-reveal-password"188            class="peach-input"189            type="password"190            autocomplete="current-password"191            value={password()}192            onInput={(event) => setPassword(event.currentTarget.value)}193            disabled={loading()}194          />195          <button type="submit" class="peach-btn peach-btn--accent peach-recovery-reveal-btn" disabled={loading() || !password()}>196            show recovery words197          </button>198        </form>199      </Show>200201      <Show when={!loading() && words().length === 12}>202        <div class="peach-recovery-words-display">203          <div class="peach-recovery-words-label">your 12 recovery words</div>204          <ol class="peach-recovery-word-list" start={1}>205            <For each={words()}>206              {(word, i) => (207                <li class="peach-recovery-word-item">208                  <span class="peach-recovery-word-num">{i() + 1}</span>209                  <span class="peach-recovery-word-text">{word}</span>210                </li>211              )}212            </For>213          </ol>214          <button215            type="button"216            class="peach-recovery-download-btn"217            onClick={() => void saveRecoveryWords(words())}218          >219            download as .txt220          </button>221        </div>222223        {/* Confirmation step */}224        <div class="peach-recovery-confirm">225          <Show when={!confirmed()}>226            <p class="peach-recovery-confirm-label">227              {countdown() > 0228                ? `type the highlighted words to confirm (${countdown()}s)`229                : "type the highlighted words to confirm"}230            </p>231          </Show>232          <Show when={confirmed()}>233            <p class="peach-hint peach-hint--success">✓ words verified</p>234          </Show>235236          <div class="peach-recovery-confirm-fields">237            <For each={confirmIndices}>238              {(pos, i) => (239                <div class="peach-recovery-confirm-field">240                  <span class="peach-recovery-confirm-num">241                    word {pos + 1}242                  </span>243                  <input244                    class="peach-recovery-word-input peach-recovery-confirm-input"245                    type="text"246                    autocomplete="off"247                    autocorrect="off"248                    autocapitalize="none"249                    spellcheck={false}250                    disabled={!canConfirm()}251                    value={confirmWords()[i()]}252                    onInput={(e) => {253                      const updated = [...confirmWords()];254                      updated[i()] = (e.target as HTMLInputElement).value;255                      setConfirmWords(updated);256                      if (confirmError()) setConfirmError("");257                    }}258                    onKeyDown={(e) => {259                      if (e.key === "Enter" && canConfirm()) void handleConfirm();260                    }}261                  />262                </div>263              )}264            </For>265          </div>266267          <Show when={confirmError()}>268            <p class="peach-hint peach-hint-error">{confirmError()}</p>269          </Show>270271          <button272            class="peach-btn peach-btn--accent peach-btn--md peach-recovery-confirm-btn"273            disabled={!canConfirm() || confirmed()}274            onClick={() => void handleConfirm()}275          >276            {confirmed() ? "verified ✓" : countdown() > 0 ? `wait ${countdown()}s` : "i wrote them down"}277          </button>278        </div>279      </Show>280    </section>281  );282}283284function recoveryWordsText(words: string[]): string {285  const numbered = words.map((w, i) => `${String(i + 1).padStart(2, " ")}. ${w}`).join("\n");286  return (287    "PEACH RECOVERY WORDS\n" +288    "====================\n\n" +289    "Anyone with these 12 words can recover your vault.\n" +290    "Store this somewhere only you can access.\n\n" +291    numbered + "\n"292  );293}294295// Desktop only — writes via a blob to a user-chosen save location. The native296// path deliberately does NOT use a file download: on Android the data:-URL297// download sink writes to world-readable public Downloads (audit MEDIUM), so298// native offers a clipboard copy (copyRecoveryWords) the user routes instead.299function saveRecoveryWords(words: string[]): void {300  const blob = new Blob([recoveryWordsText(words)], { type: "text/plain" });301  const a = document.createElement("a");302  a.download = "peach-recovery-words.txt";303  a.href = URL.createObjectURL(blob);304  setTimeout(() => URL.revokeObjectURL(a.href), 1000);305  document.body.appendChild(a);306  a.click();307  a.remove();308}