RecoveryWordEntry.tsx

12.7 KB · raw

1import {2  createSignal,3  For,4  Show,5} from "solid-js";6import { sendMessage } from "../App";7import { RecoveryRuneBackground } from "../components/RecoveryRuneBackground";8import { getWordSuggestions } from "../../shared/recovery-words";9import type { RecoveryResult } from "../../shared/types";1011const TOTAL_WORDS = 12;1213interface RecoveryWordEntryViewProps {14  onCancel: () => void;15  onRecoveryComplete: () => void | Promise<void>;16}1718export function RecoveryWordEntryView(props: RecoveryWordEntryViewProps) {19  // Each word slot: the full trimmed input value20  const [words, setWords] = createSignal<string[]>(Array(TOTAL_WORDS).fill(""));21  // Autocomplete suggestions for each slot22  const [suggestions, setSuggestions] = createSignal<(string | null)[]>(23    Array(TOTAL_WORDS).fill(null)24  );25  const [error, setError] = createSignal("");26  const [loading, setLoading] = createSignal(false);27  const [step, setStep] = createSignal<"words" | "new-password" | "complete-locked">("words");28  // New password for step 229  const [newPassword, setNewPassword] = createSignal("");30  const [confirmPassword, setConfirmPassword] = createSignal("");31  const [newPasswordError, setNewPasswordError] = createSignal("");32  const [newPasswordLoading, setNewPasswordLoading] = createSignal(false);3334  // Which word index (0-based) is currently focused for autocomplete35  const [activeIndex, setActiveIndex] = createSignal<number | null>(null);3637  function onWordInput(idx: number, value: string) {38    const normalised = value.toLowerCase().trim();39    const updated = [...words()];40    updated[idx] = value; // keep raw for input display41    setWords(updated);4243    // Update suggestions for this slot44    const sug = normalised.length >= 2 ? getWordSuggestions(normalised, 5) : [];45    const newSug = [...suggestions()];46    newSug[idx] = sug.length > 0 ? sug[0] : null;47    setSuggestions(newSug);4849    // Clear error on typing50    if (error()) setError("");5152    // Auto-fill suggestion on tab-like behaviour: if user types first chars53    // that match exactly one word, auto-complete54    if (sug.length === 1 && sug[0]!.startsWith(normalised)) {55      const final = [...words()];56      final[idx] = sug[0]!;57      setWords(final);58      const emptySug = [...suggestions()];59      emptySug[idx] = null;60      setSuggestions(emptySug);61      // Move focus to next empty slot62      const next = findNextEmpty(final);63      if (next !== null) focusSlot(next);64    }65  }6667  function onWordKeyDown(idx: number, event: KeyboardEvent) {68    if (event.key === "Tab" && !event.shiftKey) {69      event.preventDefault();70      const next = findNextEmpty(words());71      if (next !== null) {72        focusSlot(next);73      } else if (suggestions()[idx]) {74        // Tab on a slot with a suggestion: accept it75        const final = [...words()];76        final[idx] = suggestions()[idx]!;77        setWords(final);78        setSuggestions((s) => {79          const u = [...s];80          u[idx] = null;81          return u;82        });83        focusSlot(idx);84      }85    } else if (event.key === "ArrowDown" && suggestions()[idx]) {86      event.preventDefault();87      setActiveIndex(idx);88    } else if (event.key === "Escape") {89      setSuggestions((s) => {90        const u = [...s];91        u[idx] = null;92        return u;93      });94      setActiveIndex(null);95    } else if (event.key === "Enter") {96      // Accept suggestion if one is active97      if (activeIndex() !== null) {98        const final = [...words()];99        final[activeIndex()!] = suggestions()[activeIndex()!]!;100        setWords(final);101        setActiveIndex(null);102        setSuggestions((s) => {103          const u = [...s];104          u[activeIndex()!] = null;105          return u;106        });107      } else {108        void submitWords();109      }110    }111  }112113114  function findNextEmpty(w: string[]): number {115    return w.findIndex((v) => !v.trim());116  }117118  function focusSlot(idx: number) {119    const el = document.getElementById(`recovery-word-${idx}`);120    if (el) setTimeout(() => el.focus(), 30);121  }122123  async function submitWords() {124    if (loading()) return;125    const normalised = words().map((w) => w.toLowerCase().trim());126127    // Validate all filled128    const empty = normalised.findIndex((w) => !w);129    if (empty !== -1) {130      setError(`word ${empty + 1} is empty`);131      focusSlot(empty);132      return;133    }134135    setLoading(true);136    setError("");137138    try {139      // Validate against the word list first so we can reject obvious typos140      // before asking the background to do the checksum/recovery work.141      const { findInvalidWords } = await import("../../shared/recovery-words");142      const invalid = findInvalidWords(normalised);143      if (invalid.length > 0) {144        setError(`"${invalid[0].word}" is not a valid recovery word`);145        return;146      }147148      // Ask the background to validate the checksum + try to unwrap.149      const res = (await sendMessage({150        type: "VALIDATE_RECOVERY_WORDS",151        payload: { words: normalised },152      })) as { ok: boolean; data?: { valid: boolean; invalid: { index: number }[] } };153154      if (!res.ok) {155        setError("could not verify recovery words");156        return;157      }158      if (!res.data?.valid) {159        setError("invalid recovery words — check for typos");160        return;161      }162163      setStep("new-password");164    } catch {165      setError("could not verify recovery words");166    } finally {167      setLoading(false);168    }169  }170171  async function submitNewPassword() {172    if (!newPassword().trim()) {173      setNewPasswordError("password is required");174      return;175    }176    if (newPassword().length < 12) {177      setNewPasswordError("password must be at least 12 characters");178      return;179    }180    if (newPassword() !== confirmPassword()) {181      setNewPasswordError("passwords do not match");182      return;183    }184185    setNewPasswordLoading(true);186    setNewPasswordError("");187    let passwordCommitted = false;188189    try {190      const res = (await sendMessage({191        type: "RECOVER_WITH_WORDS",192        payload: { words: words().map((w) => w.toLowerCase().trim()), newPassword: newPassword() },193      })) as { ok: boolean; error?: string; data?: RecoveryResult };194195      if (!res.ok) {196        if (res.error === "recovery_not_setup") {197          setNewPasswordError("this vault was created before recovery was available — restore from backup instead");198        } else if (res.error === "recovery_requires_password_unlock") {199          setNewPasswordError("unlock once with your current password to enable word recovery, or restore from a backup or paired device");200        } else if (res.error === "recovery_data_unavailable") {201          setNewPasswordError("the recovery data could not open this vault. restore from a backup or paired device");202        } else if (res.error === "recovery_requires_lock") {203          setNewPasswordError("lock the vault before recovering it");204        } else if (res.error === "invalid_recovery_words") {205          setNewPasswordError("invalid recovery words");206        } else {207          setNewPasswordError(getDisplayError(res.error, "recovery failed"));208        }209        return;210      }211212      passwordCommitted = true;213      if (res.data?.unlocked === false) {214        setStep("complete-locked");215        return;216      }217      await Promise.resolve(props.onRecoveryComplete());218    } catch (error) {219      if (passwordCommitted) {220        console.warn("[Peach] recovery password saved; navigation failed:", error);221        setStep("complete-locked");222      }223      else setNewPasswordError("recovery failed");224    } finally {225      setNewPasswordLoading(false);226    }227  }228229  return (230    <section231      class="peach-screen peach-theme lock-screen lock-screen--recovery"232      data-motion-phase="enter"233    >234      <RecoveryRuneBackground />235236      <header class="peach-screen-header peach-recovery-nav">237        <button238          class="peach-newvault-back"239          type="button"240          onClick={() => {241            if (step() === "new-password") {242              setStep("words");243            } else {244              props.onCancel();245            }246          }}247          aria-label="Back"248        >249          <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">250            <path d="M7 2L3 5.5L7 9" />251          </svg>252          back253        </button>254      </header>255256      <Show when={step() === "words"}>257        <div class="peach-recovery-header">258          <h1 class="peach-onboarding-headline">recover your vault</h1>259          <p class="peach-hint">enter your 12 recovery words</p>260        </div>261262        <div class="peach-recovery-grid">263          <For each={Array.from({ length: TOTAL_WORDS }, (_, i) => i)}>264            {(i) => (265              <div class="peach-recovery-word-slot">266                <span class="peach-recovery-word-index">{i + 1}</span>267                <input268                  id={`recovery-word-${i}`}269                  class="peach-recovery-word-input"270                  type="text"271                  autocomplete="off"272                  autocorrect="off"273                  autocapitalize="none"274                  spellcheck={false}275                  value={words()[i]}276                  placeholder="—"277                  onInput={(e) => onWordInput(i, (e.target as HTMLInputElement).value)}278                  onKeyDown={(e) => onWordKeyDown(i, e)}279                  onFocus={() => setActiveIndex(i)}280                  onBlur={() => setTimeout(() => setActiveIndex(null), 150)}281                />282              </div>283            )}284          </For>285        </div>286287        <Show when={error()}>288          <p class="peach-hint peach-hint-error">{error()}</p>289        </Show>290291        <button292          class="peach-btn peach-btn--accent peach-btn--md peach-recovery-submit"293          onClick={() => void submitWords()}294          disabled={loading()}295        >296          {loading() ? "verifying..." : "verify words"}297        </button>298      </Show>299300      <Show when={step() === "new-password"}>301        <div class="peach-recovery-header">302          <h1 class="peach-onboarding-headline">new master password</h1>303          <p class="peach-hint">your recovery words are valid — now choose a new password</p>304        </div>305306        <div class="peach-recovery-new-password-form">307          <div class="peach-newvault-field">308            <label class="peach-label" for="recovery-new-password">309              new master password310            </label>311            <input312              id="recovery-new-password"313              class="peach-underline-input peach-unlock-input"314              type="password"315              autocomplete="new-password"316              value={newPassword()}317              onInput={(e) => setNewPassword((e.target as HTMLInputElement).value)}318              onKeyDown={(e) => {319                if (e.key === "Enter") void submitNewPassword();320              }}321            />322          </div>323324          <div class="peach-newvault-field">325            <label class="peach-label" for="recovery-confirm-password">326              confirm password327            </label>328            <input329              id="recovery-confirm-password"330              class="peach-underline-input peach-unlock-input"331              type="password"332              autocomplete="new-password"333              value={confirmPassword()}334              onInput={(e) => setConfirmPassword((e.target as HTMLInputElement).value)}335              onKeyDown={(e) => {336                if (e.key === "Enter") void submitNewPassword();337              }}338            />339          </div>340341          <Show when={newPasswordError()}>342            <p class="peach-hint peach-hint-error">{newPasswordError()}</p>343          </Show>344        </div>345346        <button347          class="peach-btn peach-btn--accent peach-btn--md peach-recovery-submit"348          onClick={() => void submitNewPassword()}349          disabled={newPasswordLoading()}350        >351          {newPasswordLoading() ? "recovering..." : "recover vault"}352        </button>353      </Show>354355      <Show when={step() === "complete-locked"}>356        <div class="peach-recovery-header">357          <h1 class="peach-onboarding-headline">your new password is saved</h1>358          <p class="peach-hint">use your new password to unlock your vault.</p>359        </div>360        <button class="peach-btn peach-btn--accent peach-btn--md" onClick={props.onCancel}>361          back to unlock362        </button>363      </Show>364    </section>365  );366}367368function getDisplayError(error: string | undefined, fallback: string): string {369  if (!error) return fallback;370  switch (error) {371    case "no_vault":372      return "no vault found";373    case "recovery_not_setup":374      return "recovery not set up for this vault";375    case "invalid_recovery_words":376      return "invalid recovery words";377    default:378      return fallback;379  }380}