Lock.tsx

42.4 KB · raw

1import { For, Match, Show, Switch, createMemo, createSignal, onCleanup, onMount } from "solid-js";2import { sendMessage } from "../App";3import { PeachMark, PeachWordmark } from "../components/PeachMark";4import { RecoveryWordEntryView } from "./RecoveryWordEntry";5import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";6import { RuneBackground } from "../components/RuneBackground";7import { storageGet, storageSet } from "../../shared/storage";8import { isPeachScript, decodePeachScript, normalisePeachScript } from "../../crypto/peachScript";9import { parsePayload } from "../../crypto/peachPayload";10import { parseImportSource } from "../../shared/import";11import { isNativePlatform, nativePlugin } from "../../shared/native";1213const peachMarkImg = new Image();14peachMarkImg.src = `data:image/svg+xml,${encodeURIComponent(15  '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 240" fill="none">' +16  '<path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/>' +17  '<path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/>' +18  '<path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z" fill="#FFB082"/>' +19  '<path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z" fill="#E5805C"/>' +20  '<ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/>' +21  '</svg>'22)}`;2324// Lazy-load @zxcvbn-ts — heavy (dictionaries ~700 kB) and only needed during25// vault creation. Replaces the unmaintained [email protected] (LV-8); result.score26// keeps the same 0-4 scale so downstream UI is unchanged.27let _zxcvbn: ((password: string) => { score: number }) | null = null;28async function getZxcvbn() {29  if (_zxcvbn) return _zxcvbn;30  const [{ zxcvbn, zxcvbnOptions }, common, en] = await Promise.all([31    import("@zxcvbn-ts/core"),32    import("@zxcvbn-ts/language-common"),33    import("@zxcvbn-ts/language-en"),34  ]);35  zxcvbnOptions.setOptions({36    translations: en.translations,37    graphs: common.adjacencyGraphs,38    dictionary: { ...common.dictionary, ...en.dictionary },39  });40  _zxcvbn = (password: string) => zxcvbn(password);41  return _zxcvbn;42}4344interface LockProps {45  hasVault: boolean;46  ready: boolean;47  isPro?: boolean;48  /** When true, render the recovery-words display directly instead of the49   *  unlock UI. Used after a popup close+reopen during the create-vault50   *  recovery confirmation flow (peach_recovery_pending flag). */51  forceRecoveryWords?: boolean;52  onUnlock: () => void | Promise<void>;53  /** Optional escape hatch: rewind from the create-vault screen back to54   *  Onboarding. Only meaningful when the user reached create-vault from55   *  Onboarding in the first place. */56  onBackToOnboarding?: () => void;57  /** Optional: open the Peach Codex restore flow (camera scan of printed58   *  Codex pages). Surfaced as a small footer link on the new-vault screen. */59  onOpenCodexRestore?: () => void;60  /** Open directly on backup restore when onboarding routed the user there. */61  initialRestore?: boolean;62}6364type RestoreSurface = "restore" | null;65type RecoverSurface = "words" | "new-password" | null;6667export function LockView(props: LockProps) {68  const [password, setPassword] = createSignal("");69  const [confirmPassword, setConfirmPassword] = createSignal("");70  const [error, setError] = createSignal("");71  const [loading, setLoading] = createSignal(false);72  const [restoreSurface, setRestoreSurface] = createSignal<RestoreSurface>(73    props.initialRestore ? "restore" : null,74  );75  const [showPassword, setShowPassword] = createSignal(false);76  const [recoverSurface, setRecoverSurface] = createSignal<RecoverSurface>(null);77  // After vault creation succeeds, set this to show the recovery words screen.78  // Only meaningful when hasVault === false.79  const [showRecoveryWords, setShowRecoveryWords] = createSignal(props.forceRecoveryWords ?? false);8081  const MIN_LENGTH = 12;82  const MIN_ZXCVBN_SCORE = 2;8384  const [strengthScore, setStrengthScore] = createSignal<number | null>(null);85  const [biometricAvailable, setBiometricAvailable] = createSignal(false);86  const [biometricBusy, setBiometricBusy] = createSignal(false);87  const [pinAvailable, setPinAvailable] = createSignal(false);88  const [usingPin, setUsingPin] = createSignal(false);89  const [pin, setPin] = createSignal("");9091  const canCreate = createMemo(92    () =>93      password().length >= MIN_LENGTH &&94      confirmPassword().length >= MIN_LENGTH &&95      password() === confirmPassword() &&96      strengthScore() !== null &&97      strengthScore()! >= MIN_ZXCVBN_SCORE98  );99100  const passwordStrength = createMemo(() => {101    const score = strengthScore();102    if (score === null) return null;103    if (score <= 1) return "weak";104    if (score === 2) return "fair";105    if (score === 3) return "good";106    return "strong";107  });108109  const createBlockerMessage = createMemo(() => {110    if (!password()) return null;111    if (password().length < MIN_LENGTH) return `need ${MIN_LENGTH - password().length} more characters`;112    if (!confirmPassword()) return "confirm your password";113    if (password() !== confirmPassword()) return "passwords don't match";114    if (strengthScore() === null) return "checking strength…";115    if (strengthScore()! < MIN_ZXCVBN_SCORE) return "password too weak — use a longer passphrase";116    return null;117  });118119  // Update strength asynchronously when password changes120  createMemo(() => {121    const value = password();122    if (!value) { setStrengthScore(null); return; }123    getZxcvbn().then((zxcvbn) => {124      if (password() === value) setStrengthScore(zxcvbn(value).score);125    }).catch(() => {126      // zxcvbn unavailable — fall back to length-only heuristic127      if (password() === value) setStrengthScore(value.length >= 16 ? 3 : value.length >= 12 ? 2 : 1);128    });129  });130131  async function handleUnlock() {132    if (!password().trim()) return;133    setLoading(true);134    setError("");135    const response = await sendMessage({136      type: "UNLOCK",137      payload: { password: password() },138    });139    const result = response as { ok: boolean; error?: string };140    if (result.ok) {141      await props.onUnlock();142      setLoading(false);143      return;144    }145    setError(getDisplayError(result.error, "incorrect password"));146    setPassword("");147    const passwordField = document.querySelector(".lock-password-input") as HTMLInputElement | undefined;148    passwordField?.classList.add("shake");149    setTimeout(() => passwordField?.classList.remove("shake"), 300);150    setLoading(false);151  }152153  async function handlePinUnlock() {154    if (!/^\d{4,12}$/.test(pin())) return;155    setLoading(true);156    setError("");157    const response = await sendMessage({158      type: "UNLOCK_WITH_PIN",159      payload: { pin: pin() },160    });161    const result = response as { ok: boolean; error?: string };162    if (result.ok) {163      await props.onUnlock();164      setLoading(false);165      return;166    }167    setError(getDisplayError(result.error, "incorrect PIN"));168    setPin("");169    const pinField = document.querySelector(".lock-pin-input") as HTMLInputElement | undefined;170    pinField?.classList.add("shake");171    setTimeout(() => pinField?.classList.remove("shake"), 300);172    setLoading(false);173  }174175  async function checkPinAvailable(): Promise<void> {176    if (!props.hasVault) return;177    try {178      const response = await sendMessage({ type: "GET_SETTINGS" });179      const settings = (response as { ok: boolean; data?: { pinEnabled?: boolean; pinPreferred?: boolean } }).data;180      const enabled = settings?.pinEnabled === true;181      setPinAvailable(enabled);182      if (enabled && settings?.pinPreferred === true) setUsingPin(true);183    } catch { /* settings are optional at the lock screen */ }184  }185186  async function checkBiometricAvailable(): Promise<void> {187    if (!props.hasVault || !isNativePlatform()) return;188    const keystore = nativePlugin<{ hasMasterKey: () => Promise<{ exists: boolean }> }>("KeystorePlugin");189    const biometric = nativePlugin<{ isAvailable: () => Promise<{ available: boolean }> }>("BiometricPlugin");190    if (!keystore || !biometric) return;191    try {192      const stored = await keystore.hasMasterKey();193      if (!stored.exists) return;194      const avail = await biometric.isAvailable();195      if (!avail.available) return;196      setBiometricAvailable(true);197      window.setTimeout(() => { void handleBiometricUnlock(); }, 400);198    } catch { /* missing plugins or runtime error — silently skip */ }199  }200201  async function handleBiometricUnlock(): Promise<void> {202    if (biometricBusy()) return;203    const biometric = nativePlugin<{ authenticate: (opts: Record<string, string>) => Promise<void> }>("BiometricPlugin");204    const keystore = nativePlugin<{ retrieveMasterKey: () => Promise<{ masterKeyHex: string }> }>("KeystorePlugin");205    if (!biometric || !keystore) return;206    setBiometricBusy(true);207    setError("");208    try {209      await biometric.authenticate({210        title: "Unlock Peach",211        subtitle: "Use biometrics to access your vault",212        negativeButtonText: "Use Password",213      });214      const { masterKeyHex } = await keystore.retrieveMasterKey();215      const res = (await sendMessage({216        type: "UNLOCK_WITH_KEY",217        payload: { masterKeyHex },218      })) as { ok: boolean; error?: string };219      if (res.ok) {220        await props.onUnlock();221        return;222      }223      if (res.error === "biometric_key_invalidated") {224        await sendMessage({225          type: "UPDATE_SETTINGS",226          payload: { biometricsEnabled: false },227        });228        setBiometricAvailable(false);229        setError("biometric key expired — re-enable in settings");230      } else {231        setError("biometric unlock failed");232      }233    } catch (e) {234      const reason = e instanceof Error ? e.message : String(e);235      if (reason.includes("user_cancelled")) return;236      if (reason.includes("biometric_key_invalidated")) {237        await sendMessage({238          type: "UPDATE_SETTINGS",239          payload: { biometricsEnabled: false },240        });241        setBiometricAvailable(false);242        setError("biometric key expired — re-enable in settings");243        return;244      }245      if (reason.includes("biometric_lockout")) {246        setError("biometric locked out — use your password");247      }248    } finally {249      setBiometricBusy(false);250    }251  }252253  onMount(() => {254    void checkBiometricAvailable();255    void checkPinAvailable();256  });257258  async function handleCreate() {259    if (!password().trim()) return;260    if (password().length < MIN_LENGTH) {261      setError(`password must be at least ${MIN_LENGTH} characters`);262      return;263    }264    if (password() !== confirmPassword()) {265      setError("passwords do not match");266      return;267    }268    const score = strengthScore();269    if (score === null || score < MIN_ZXCVBN_SCORE) {270      setError("password is too weak — use a longer passphrase");271      return;272    }273    setLoading(true);274    setError("");275    const response = await sendMessage({276      type: "CREATE_VAULT",277      payload: { password: password() },278    });279    const result = response as { ok: boolean; error?: string };280    if (result.ok) {281      // Don't unlock yet — show the recovery words screen first. Mark the282      // confirmation as pending in chrome.storage.local so it survives both283      // popup close (lock-on-close skips while set) and full browser restart284      // (next unlock re-routes to the recovery surface). Cleared when the285      // user types the 3 confirmation words successfully.286      try {287        await chrome.storage.local?.set({ peach_recovery_pending: "1" });288      } catch { /* best-effort */ }289      setShowRecoveryWords(true);290      setLoading(false);291      return;292    }293    setError(getDisplayError(result.error, "failed to create vault"));294    setLoading(false);295  }296297  // ── All surfaces routed reactively via Switch/Match ───────────────────298  return (299    <Switch>300      {/* ── Restore tab view ──────────────────────────────────────── */}301      <Match when={restoreSurface() === "restore"}>302        <RestoreTabView303          hasVault={props.hasVault}304          onOpenCodexRestore={props.onOpenCodexRestore}305          onBack={() => {306            // The restore tab is only reached from the onboarding carousel,307            // so back returns there — not to the create-vault form.308            if (props.onBackToOnboarding) props.onBackToOnboarding();309            else setRestoreSurface(null);310          }}311          onUnlock={async () => {312            setRestoreSurface(null);313            await props.onUnlock();314          }}315        />316      </Match>317318      {/* ── Recovery words display after fresh vault creation ────────── */}319      <Match when={showRecoveryWords() && (!props.hasVault || props.forceRecoveryWords)}>320        <RecoveryWordDisplayView321          onDone={props.onUnlock}322        />323      </Match>324325      {/* ── Recovery word entry ─────────────────────────────────────── */}326      <Match when={recoverSurface() === "words"}>327        <RecoveryWordEntryView328          onCancel={() => setRecoverSurface(null)}329          onRecoveryComplete={props.onUnlock}330        />331      </Match>332333      {/* ── Unlock (hasVault = true) ───────────────────────────────── */}334      <Match when={props.hasVault}>335        <section class="peach-screen peach-theme lock-screen lock-screen--vault-stage" data-motion-phase="enter">336          <RuneBackground opacity={0.07} />337338          <header class="peach-screen-header lock-screen-header">339            <div class="peach-wordmark-stack">340              <PeachWordmark class="peach-wordmark-wrap" />341              <Show when={props.isPro}>342                <span class="peach-pro-mini-badge">pro</span>343              </Show>344            </div>345          </header>346347          <div class="peach-lock-hero peach-lock-hero--unlock">348            <PeachMark class="peach-lock-mark" />349            <span class="peach-lock-eyebrow">vault locked</span>350            <h1 class="peach-onboarding-headline peach-lock-headline--unlock">351              unlock352              <br />353              your vault.354            </h1>355          </div>356357          <section class="peach-lock-panel peach-lock-panel--unlock peach-glass">358            <Show when={usingPin()} fallback={359              <>360                <label class="peach-label" for="unlock-password">361                  master password362                </label>363                <input364                  id="unlock-password"365                  class="peach-underline-input peach-unlock-input lock-password-input"366                  type="password"367                  placeholder="••••••••••••"368                  autocomplete="current-password"369                  value={password()}370                  disabled={!props.ready}371                  ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}372                  onInput={(event) => setPassword((event.target as HTMLInputElement).value)}373                  onKeyDown={(event) => {374                    if (event.key !== "Enter" || !props.ready) return;375                    void handleUnlock();376                  }}377                />378              </>379            }>380              <label class="peach-label" for="unlock-pin">381                PIN382              </label>383              <input384                id="unlock-pin"385                class="peach-underline-input peach-unlock-input lock-pin-input"386                type="password"387                inputmode="numeric"388                maxlength="12"389                placeholder="••••••••••••"390                autocomplete="off"391                value={pin()}392                disabled={!props.ready}393                ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}394                onInput={(event) => setPin((event.target as HTMLInputElement).value.replace(/\D/g, "").slice(0, 12))}395                onKeyDown={(event) => {396                  if (event.key !== "Enter" || !props.ready) return;397                  void handlePinUnlock();398                }}399              />400              <button401                class="peach-lock-recover-link"402                type="button"403                onClick={() => { setUsingPin(false); setError(""); }}404              >405                use master password406              </button>407            </Show>408409            <Show when={error()}>410              <p class="peach-hint peach-hint-error">{error()}</p>411            </Show>412413            <button414              class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit"415              onClick={() => void (usingPin() ? handlePinUnlock() : handleUnlock())}416              disabled={!props.ready || loading()}417            >418              {loading() ? "unlocking..." : usingPin() ? "unlock with PIN" : "unlock"}419            </button>420421            <Show when={!usingPin() && pinAvailable()}>422              <button423                class="peach-lock-recover-link"424                type="button"425                onClick={() => { setUsingPin(true); setError(""); }}426              >427                use PIN428              </button>429            </Show>430431            <Show when={biometricAvailable()}>432              <button433                class="peach-biometric-btn"434                type="button"435                onClick={() => void handleBiometricUnlock()}436                disabled={biometricBusy() || loading()}437                aria-label="Unlock with biometrics"438              >439                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">440                  <path d="M12 11c-1.7 0-3 1.3-3 3v3"/>441                  <path d="M15 17v-3"/>442                  <path d="M9 4.5C9.7 4.2 10.8 4 12 4s2.3.2 3 .5"/>443                  <path d="M5 9c.7-1.6 2-2.9 3.6-3.6"/>444                  <path d="M19 9c-.7-1.6-2-2.9-3.6-3.6"/>445                  <path d="M5 15c0-1.7.3-3.3.8-4.7"/>446                  <path d="M19 15c0-1.7-.3-3.3-.8-4.7"/>447                </svg>448                {biometricBusy() ? "verifying…" : "use biometrics"}449              </button>450            </Show>451452            <button453              class="peach-lock-recover-link"454              type="button"455              onClick={() => setRecoverSurface("words")}456            >457              forgot your password?458            </button>459          </section>460        </section>461      </Match>462463      {/* ── Onboarding (hasVault = false) ─────────────────────────── */}464      <Match when={true}>465        <section466          class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault"467          data-motion-phase="enter"468        >469          <header class="peach-screen-header peach-newvault-header">470            <div class="peach-wordmark-stack">471              <PeachWordmark class="peach-wordmark-wrap" />472              <Show when={props.isPro}>473                <span class="peach-pro-mini-badge">pro</span>474              </Show>475            </div>476            <Show when={props.onBackToOnboarding}>477              <button478                class="peach-newvault-back"479                type="button"480                onClick={() => props.onBackToOnboarding?.()}481                aria-label="Back to onboarding"482              >483                <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">484                  <path d="M7 2L3 5.5L7 9" />485                </svg>486                back487              </button>488            </Show>489          </header>490491          <div class="peach-newvault-mark" aria-hidden="true">492            <PeachMark class="peach-newvault-mark-art" />493          </div>494495          <div class="peach-newvault-card">496            <h1 class="peach-newvault-headline">{"keep your\nsecrets."}</h1>497            <hr class="peach-newvault-divider" />498499            <div class="peach-newvault-field">500              <div class="peach-newvault-label-row">501                <label class="peach-label" for="master-password">502                  master password503                </label>504                <button505                  class="peach-lock-reveal-btn"506                  type="button"507                  onClick={() => setShowPassword((value) => !value)}508                  aria-label={showPassword() ? "Hide password" : "Show password"}509                >510                  <Show511                    when={showPassword()}512                    fallback={513                      <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">514                        <path d="M1 5C1 5 2.8 1 7 1C11.2 1 13 5 13 5C13 5 11.2 9 7 9C2.8 9 1 5 1 5Z" />515                        <circle cx="7" cy="5" r="1.75" />516                      </svg>517                    }518                  >519                    <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">520                      <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />521                      <path d="M3.5 5.5L2.5 7.5" />522                      <path d="M7 6.5V8.5" />523                      <path d="M10.5 5.5L11.5 7.5" />524                    </svg>525                  </Show>526                  {showPassword() ? "hide" : "show"}527                </button>528              </div>529              <input530                id="master-password"531                class="peach-underline-input peach-newvault-input lock-password-input"532                type={showPassword() ? "text" : "password"}533                placeholder="••••••••••••"534                autocomplete="new-password"535                value={password()}536                disabled={!props.ready}537                onInput={(event) => setPassword((event.target as HTMLInputElement).value)}538                onKeyDown={(event) => {539                  if (event.key !== "Enter" || !props.ready) return;540                  void handleCreate();541                }}542              />543              <Show544                when={password().length > 0 && passwordStrength() !== null}545                fallback={546                  <p class="peach-newvault-hint">547                    At least 12 characters.548                  </p>549                }550              >551                <div class="peach-password-strength">552                  <div class={`peach-strength-bar peach-strength-bar--${passwordStrength()}`}>553                    <div class="peach-strength-fill"></div>554                  </div>555                  <span class="peach-strength-label">{passwordStrength()}</span>556                </div>557              </Show>558            </div>559560            <div class="peach-newvault-field">561              <label class="peach-label" for="confirm-password">562                confirm password563              </label>564              <input565                id="confirm-password"566                class="peach-underline-input peach-newvault-input"567                type={showPassword() ? "text" : "password"}568                placeholder="••••••••••••"569                autocomplete="new-password"570                value={confirmPassword()}571                disabled={!props.ready}572                onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}573                onKeyDown={(event) => {574                  if (event.key === "Enter" && props.ready) void handleCreate();575                }}576              />577            </div>578579            <Show when={error()}>580              <p class="peach-hint peach-hint-error">{error()}</p>581            </Show>582583            <button584              class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit peach-newvault-submit"585              onClick={() => void handleCreate()}586              disabled={!props.ready || loading() || !canCreate()}587              aria-live="polite"588            >589              <Show590                when={!canCreate() && createBlockerMessage()}591                fallback={loading() ? "creating..." : "create vault"}592              >593                {createBlockerMessage()}594              </Show>595            </button>596597            <p class="peach-newvault-warning">598              <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>599              <span>Save your 12 recovery words after creating — they're the only way back in if you forget your password.</span>600            </p>601          </div>602        </section>603      </Match>604    </Switch>605  );606}607608// ── Restore tab view ───────────────────────────────────────────────────────609610type RestoreTab = "symbols" | "codex" | "csv";611612function tabLabel(tab: RestoreTab): string {613  return (614    { symbols: "PeachScript", codex: "Codex", csv: "CSV" }[tab]615  );616}617618function RestoreTabView(props: {619  hasVault: boolean;620  onOpenCodexRestore?: () => void;621  onBack: () => void;622  onUnlock: () => void | Promise<void>;623}) {624  const [activeTab, setActiveTab] = createSignal<RestoreTab>("symbols");625  const [showIntro, setShowIntro] = createSignal(false);626  const [pendingUnlock] = createSignal(false);627628  async function handleRestoreSuccess() {629    const seen = await storageGet("peach_shown_restore_intro").catch(() => null);630    if (!seen) {631      setShowIntro(true);632    } else {633      await props.onUnlock();634    }635  }636637  async function dismissIntro() {638    await storageSet("peach_shown_restore_intro", "true").catch(() => {});639    setShowIntro(false);640    await props.onUnlock();641  }642643  return (644    <section645      class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-restore-tabview"646      data-motion-phase="enter"647    >648      <RuneBackground opacity={0.05} />649650      <header class="peach-screen-header lock-screen-header">651        <PeachWordmark class="peach-wordmark-wrap" />652        <button class="peach-lock-restore-link" onClick={props.onBack}>653          ‹ back654        </button>655      </header>656657      <div class="peach-newvault-card peach-restore-tabcard">658        <div class="peach-restore-tabs" role="tablist">659          <For each={["symbols", "codex", "csv"] as RestoreTab[]}>660            {(tab) => (661              <button662                class="peach-restore-tab"663                classList={{ "is-active": activeTab() === tab }}664                onClick={() => setActiveTab(tab)}665                role="tab"666                aria-selected={activeTab() === tab}667              >668                {tabLabel(tab)}669              </button>670            )}671          </For>672        </div>673        <div class="peach-restore-content">674          <Show when={activeTab() === "symbols"}>675            <RestoreSymbols hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />676          </Show>677          <Show when={activeTab() === "codex"}>678            <RestoreCodex onOpen={() => props.onOpenCodexRestore?.()} />679          </Show>680          <Show when={activeTab() === "csv"}>681            <RestoreCSV hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />682          </Show>683        </div>684      </div>685686      {/* One-time intro popup after first restore */}687      <Show when={showIntro()}>688        <div class="peach-restore-intro-overlay">689          <div class="peach-restore-intro-card">690            <p class="peach-restore-intro-headline">welcome to peach.</p>691            <div class="peach-restore-intro-body">692              <p>Your vault lives only on this device. No server has a copy.</p>693              <p>The inline bubble fills passwords automatically when you visit sites.</p>694              <p>Export your vault from Settings before switching devices.</p>695            </div>696            <button697              class="peach-btn peach-btn--accent peach-btn--md peach-restore-intro-btn"698              onClick={() => void dismissIntro()}699              disabled={pendingUnlock()}700            >701              got it702            </button>703          </div>704        </div>705      </Show>706    </section>707  );708}709710// ── Peach Codex tab ────────────────────────────────────────────────────────711712function RestoreCodex(props: { onOpen: () => void }) {713  return (714    <div class="peach-restore-codex">715      <p class="peach-restore-codex-title">Restore from Peach Codex</p>716      <p class="peach-restore-codex-copy">717        Scan printed Codex pages or import the Codex PDF. Codex restore is718        always available, even before you create a vault.719      </p>720      <button721        type="button"722        class="peach-btn peach-btn--accent peach-btn--md peach-restore-codex-button"723        onClick={props.onOpen}724      >725        open Codex restore →726      </button>727    </div>728  );729}730731// ── PeachScript tab ────────────────────────────────────────────────────────732733function RestoreSymbols(props: { hasVault: boolean; onSuccess: () => void | Promise<void> }) {734  const [scriptInput, setScriptInput] = createSignal("");735  const [backupPass, setBackupPass] = createSignal("");736  const [working, setWorking] = createSignal(false);737  const [animating, setAnimating] = createSignal<"chaos" | "snap" | "bloom" | null>(null);738  const [error, setError] = createSignal<string | null>(null);739  let canvasRef: HTMLCanvasElement | undefined;740  let animFrameId = 0;741  let runes: { x: number; y: number; vx: number; vy: number; char: string; size: number; angle: number; va: number }[] = [];742743  const scriptValid = createMemo(() => isPeachScript(scriptInput()));744745  function stopAnim() {746    cancelAnimationFrame(animFrameId);747    animFrameId = 0;748  }749750  function startChaos(canvas: HTMLCanvasElement) {751    const ctx = canvas.getContext("2d")!;752    const W = canvas.width;753    const H = canvas.height;754    const RUNE_CHARS = Array.from({ length: 40 }, (_, i) =>755      String.fromCodePoint(0xe000 + i)756    );757    if (runes.length === 0) {758      runes = Array.from({ length: 60 }, () => ({759        x: Math.random() * W,760        y: Math.random() * H,761        vx: (Math.random() - 0.5) * 3,762        vy: (Math.random() - 0.5) * 3,763        char: RUNE_CHARS[Math.floor(Math.random() * RUNE_CHARS.length)]!,764        size: 14 + Math.random() * 20,765        angle: Math.random() * Math.PI * 2,766        va: (Math.random() - 0.5) * 0.1,767      }));768    }769770    function draw() {771      ctx.clearRect(0, 0, W, H);772      for (const r of runes) {773        r.x = (r.x + r.vx + W) % W;774        r.y = (r.y + r.vy + H) % H;775        r.angle += r.va;776        ctx.save();777        ctx.translate(r.x, r.y);778        ctx.rotate(r.angle);779        ctx.font = `${r.size}px PeachScript, monospace`;780        const alpha = 0.5 + 0.5 * Math.sin(Date.now() / 400 + r.x);781        ctx.fillStyle = `rgba(232, 149, 109, ${alpha})`;782        ctx.shadowColor = "rgba(232, 149, 109, 0.7)";783        ctx.shadowBlur = 8;784        ctx.fillText(r.char, 0, 0);785        ctx.restore();786      }787      animFrameId = requestAnimationFrame(draw);788    }789    draw();790  }791792  function snapToGrid(canvas: HTMLCanvasElement, onDone: () => void) {793    stopAnim();794    const ctx = canvas.getContext("2d")!;795    const W = canvas.width;796    const H = canvas.height;797    const cols = 8;798    const rows = 6;799    const cellW = W / cols;800    const cellH = H / rows;801    const targets = runes.slice(0, cols * rows).map((_, i) => ({802      x: (i % cols) * cellW + cellW / 2,803      y: Math.floor(i / cols) * cellH + cellH / 2,804    }));805    const start = performance.now();806    const DURATION = 400;807808    function drawSnap(now: number) {809      const t = Math.min((now - start) / DURATION, 1);810      const ease = t < 1 ? 1 - (1 - t) ** 3 : 1;811      ctx.clearRect(0, 0, W, H);812      runes.slice(0, targets.length).forEach((r, i) => {813        const tx = targets[i]!.x;814        const ty = targets[i]!.y;815        const cx = r.x + (tx - r.x) * ease;816        const cy = r.y + (ty - r.y) * ease;817        ctx.font = `16px PeachScript, monospace`;818        ctx.fillStyle = `rgba(232, 149, 109, ${0.8 * ease})`;819        ctx.shadowColor = "rgba(232, 149, 109, 0.6)";820        ctx.shadowBlur = 6;821        ctx.fillText(r.char, cx - 8, cy + 8);822      });823      if (t < 1) {824        animFrameId = requestAnimationFrame(drawSnap);825      } else {826        onDone();827      }828    }829    animFrameId = requestAnimationFrame(drawSnap);830  }831832  function bloom(canvas: HTMLCanvasElement, onDone: () => void) {833    stopAnim();834    const ctx = canvas.getContext("2d")!;835    const W = canvas.width;836    const H = canvas.height;837    const start = performance.now();838    const DURATION = 900;839840    function drawBloom(now: number) {841      const t = Math.min((now - start) / DURATION, 1);842      ctx.clearRect(0, 0, W, H);843      // Runes dissolve844      const runeAlpha = 1 - Math.min(t / 0.4, 1);845      if (runeAlpha > 0) {846        for (const r of runes.slice(0, 48)) {847          ctx.font = `16px PeachScript, monospace`;848          ctx.fillStyle = `rgba(232, 149, 109, ${runeAlpha * 0.8})`;849          ctx.fillText(r.char, r.x - 8, r.y + 8);850        }851      }852      // Peach mark bloom853      const markT = Math.max(0, (t - 0.2) / 0.5);854      const markScale = Math.min(markT * 1.2, 1);855      const markAlpha = markT < 0.5 ? markT * 2 : 2 - markT * 2;856      if (markAlpha > 0) {857        ctx.save();858        ctx.globalAlpha = markAlpha;859        ctx.shadowColor = `rgba(217, 104, 48, ${markAlpha * 0.8})`;860        ctx.shadowBlur = 30;861        ctx.translate(W / 2, H / 2);862        ctx.scale(markScale, markScale);863        ctx.drawImage(peachMarkImg, -32, -32, 64, 64);864        ctx.restore();865      }866      if (t < 1) {867        animFrameId = requestAnimationFrame(drawBloom);868      } else {869        onDone();870      }871    }872    animFrameId = requestAnimationFrame(drawBloom);873  }874875  onCleanup(() => stopAnim());876877  async function handleRestore() {878    if (!scriptValid() || !backupPass().trim() || working()) return;879    setError(null);880    setWorking(true);881    setAnimating("chaos");882883    const canvas = canvasRef;884    if (canvas) startChaos(canvas);885886    try {887      const bytes = decodePeachScript(normalisePeachScript(scriptInput()));888      const payload = await parsePayload(bytes, backupPass());889890      if (!props.hasVault) {891        const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });892        if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");893      }894895      const rr = await sendMessage({896        type: "RESTORE_ENTRIES",897        payload: { entries: payload.entries, mode: "merge", settings: payload.settings },898      });899      if (!(rr as { ok: boolean }).ok) throw new Error((rr as { error?: string }).error ?? "RESTORE_FAILED");900901      if (payload.license?.key) {902        await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: payload.license.key } }).catch(() => {});903      }904905      setAnimating("snap");906      stopAnim();907      if (canvas) {908        snapToGrid(canvas, () => {909          setAnimating("bloom");910          bloom(canvas, async () => {911            setAnimating(null);912            await props.onSuccess();913          });914        });915      } else {916        await props.onSuccess();917      }918    } catch (err) {919      stopAnim();920      setAnimating(null);921      const code = err instanceof Error ? err.message : String(err);922      setError(923        code === "INVALID_PASSPHRASE" || code === "INVALID_EXPORT_PASSWORD"924          ? "That passphrase didn't work."925          : code === "CREATE_VAULT_FAILED"926            ? "Couldn't create a new local vault."927            : "Could not read this backup.",928      );929    } finally {930      setWorking(false);931    }932  }933934  return (935    <div class="peach-rt-symbols">936      <Show when={animating() !== null}>937        <canvas938          ref={(el) => { canvasRef = el; }}939          class="peach-rt-anim-canvas"940          width={280}941          height={200}942        />943      </Show>944      <Show when={animating() === null}>945        <textarea946          class="peach-restore-symbols-textarea"947          placeholder="paste peachscript…"948          rows={3}949          value={scriptInput()}950          onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}951        />952        <div class="peach-rt-divider">— or —</div>953        <label class="peach-btn peach-btn--ghost peach-btn--sm peach-rt-file-label">954          open .peach file955          <input956            type="file"957            accept=".peach,text/plain"958            style="display:none"959            onChange={async (e) => {960              const file = (e.currentTarget as HTMLInputElement).files?.[0];961              if (!file) return;962              try {963                setScriptInput(await file.text());964              } catch {965                setError("Couldn't read file.");966              } finally {967                (e.currentTarget as HTMLInputElement).value = "";968              }969            }}970          />971        </label>972        <input973          class="peach-restore-symbols-pass"974          type="password"975          placeholder="backup password"976          value={backupPass()}977          onInput={(e) => setBackupPass((e.target as HTMLInputElement).value)}978          onKeyDown={(e) => {979            if (e.key === "Enter" && scriptValid() && backupPass().trim() && !working()) {980              e.preventDefault();981              void handleRestore();982            }983          }}984        />985        <button986          class="peach-btn peach-btn--accent peach-btn--md peach-rt-submit"987          onClick={() => void handleRestore()}988          disabled={!scriptValid() || !backupPass().trim() || working()}989        >990          restore vault →991        </button>992        <Show when={error()}>993          <p class="peach-rt-error">{error()}</p>994        </Show>995      </Show>996    </div>997  );998}9991000// ── CSV tab ────────────────────────────────────────────────────────────────10011002function RestoreCSV(props: { hasVault: boolean; onSuccess: () => void | Promise<void> }) {1003  const [importing, setImporting] = createSignal(false);1004  const [error, setError] = createSignal<string | null>(null);1005  // CSV/JSON imports are plaintext and carry no password, so when there is no1006  // vault yet the user MUST choose a master password here — otherwise the1007  // imported credentials would be encrypted under an empty key and offer zero1008  // at-rest protection (audit HIGH). Mirrors the onboarding MIN_LENGTH policy.1009  const CSV_MIN_PASSWORD_LENGTH = 12;1010  const [newPass, setNewPass] = createSignal("");1011  const [confirmPass, setConfirmPass] = createSignal("");1012  const needsPassword = () => props.hasVault === false;1013  const passwordReady = () =>1014    !needsPassword() ||1015    (newPass().length >= CSV_MIN_PASSWORD_LENGTH && newPass() === confirmPass());10161017  async function handleFile(e: Event) {1018    const input = e.currentTarget as HTMLInputElement;1019    const file = input.files?.[0];1020    input.value = "";1021    if (!file) return;1022    if (needsPassword() && newPass().length < CSV_MIN_PASSWORD_LENGTH) {1023      setError(`Set a master password of at least ${CSV_MIN_PASSWORD_LENGTH} characters first.`);1024      return;1025    }1026    if (needsPassword() && newPass() !== confirmPass()) {1027      setError("Passwords do not match.");1028      return;1029    }1030    setImporting(true);1031    setError(null);1032    try {1033      const text = await file.text();1034      const parsed = await parseImportSource(text);1035      if (parsed.entries.length === 0) throw new Error("NO_ENTRIES");10361037      if (props.hasVault === false) {1038        // Create the vault under the user-chosen master password — never an1039        // empty one (an empty key derives a publicly-known vault key).1040        const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });1041        if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");1042      }10431044      const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });1045      if (!(res as { ok: boolean }).ok) throw new Error("IMPORT_FAILED");1046      if (parsed.licenseKey) {1047        await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: parsed.licenseKey } }).catch(() => {});1048      }1049      await props.onSuccess();1050    } catch (err) {1051      const code = err instanceof Error ? err.message : String(err);1052      setError(1053        code === "NO_ENTRIES" ? "No entries found in this file." :1054        code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :1055        "Import failed. Check the file format and try again."1056      );1057    } finally {1058      setImporting(false);1059    }1060  }10611062  return (1063    <div class="peach-rt-csv">1064      <Show when={needsPassword()}>1065        <input1066          class="peach-restore-symbols-pass"1067          type="password"1068          placeholder="new master password"1069          value={newPass()}1070          onInput={(e) => setNewPass((e.target as HTMLInputElement).value)}1071        />1072        <input1073          class="peach-restore-symbols-pass"1074          type="password"1075          placeholder="confirm master password"1076          value={confirmPass()}1077          onInput={(e) => setConfirmPass((e.target as HTMLInputElement).value)}1078        />1079      </Show>1080      <label1081        class="peach-btn peach-btn--accent peach-btn--md peach-rt-csv-btn"1082        classList={{ "is-busy": importing(), "is-disabled": !passwordReady() }}1083      >1084        {importing() ? "importing…" : "open csv file"}1085        <input1086          type="file"1087          accept=".csv,.json,.peach,application/x-peach"1088          style="display:none"1089          onChange={handleFile}1090          disabled={importing() || !passwordReady()}1091        />1092      </label>1093      <p class="peach-rt-csv-sources">1094        Imports from Bitwarden, 1Password, Proton Pass,<br />1095        Chrome, Safari, and Edge.1096      </p>1097      <p class="peach-rt-csv-warning">PLAIN-TEXT — DELETE THE FILE AFTER IMPORT</p>1098      <Show when={error()}>1099        <p class="peach-rt-error">{error()}</p>1100      </Show>1101    </div>1102  );1103}11041105// ── Helpers ────────────────────────────────────────────────────────────────11061107function getDisplayError(error: string | undefined, fallback: string): string {1108  if (!error) return fallback;1109  if (1110    error === "SERVICE_WORKER_UNAVAILABLE" ||1111    error.includes("Receiving end does not exist") ||1112    error.includes("message port closed")1113  ) {1114    return "background service unavailable";1115  }1116  return error;1117}