App.tsx

48.7 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Capacitor } from "@capacitor/core";3import { storageGet, storageSet } from "../shared/storage";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import { isPasskeyOnly } from "../shared/types";7import { LockView } from "./views/Lock";8import { Onboarding } from "./views/Onboarding";9import { ProCelebration } from "./views/ProCelebration";10import { VaultView, type SortOrder } from "./views/Vault";11import { EntryView } from "./views/Entry";12import { AddView } from "./views/Add";13import { PeachWordmark } from "./components/PeachMark";14import { PasskeyApprovalView } from "./views/PasskeyApproval";15import { extractDomain } from "../shared/domain";16import { popupCopy } from "./copy";17import {18  DEFAULT_BINDINGS,19  formatKeybinding,20  getActiveBindings,21  matchKeybinding,22  SHORTCUT_DESCRIPTORS,23  type Keybinding,24  type ShortcutAction,25} from "../shared/shortcuts";26import { generateTOTP } from "../crypto/totp";2728const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));29const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));30const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));31const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));32const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));33const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));3435type View =36  | "lock"37  | "pro-celebration"38  | "entry"39  | "list"40  | "add"41  | "settings"42  | "import"43  | "export"44  | "health"45  | "trash"46  | "panic";47type BootState = "loading" | "ready";4849const canarySuppressMap = new Map<string, boolean>();50let shellRingAnimation: Animation | null = null;5152export function isCanarySuppressed(entryId: string): boolean {53  return canarySuppressMap.get(entryId) ?? false;54}5556export function setCanarySuppressed(entryId: string, suppressed: boolean): void {57  canarySuppressMap.set(entryId, suppressed);58}5960export function clearCanarySuppressions(): void {61  canarySuppressMap.clear();62}6364export function triggerRing() {65  const shell = document.getElementById("hd-shell");66  if (!shell) return;6768  shellRingAnimation?.cancel();69  shell.dataset.glowing = "true";70  const animation = shell.animate(71    [72      { offset: 0, boxShadow: "var(--copy-shadow)" },73      {74        offset: 0.3,75        boxShadow:76          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",77      },78      { offset: 1, boxShadow: "var(--copy-shadow)" },79    ],80    {81      duration: 720,82      easing: "cubic-bezier(0.4, 0, 0.2, 1)",83      fill: "none",84    }85  );86  shellRingAnimation = animation;87  const clearGlow = () => {88    if (shellRingAnimation !== animation) return;89    shellRingAnimation = null;90    delete shell.dataset.glowing;91  };92  animation.onfinish = clearGlow;93  animation.oncancel = clearGlow;94}959697export function triggerPipPulse() {98  const pip = document.querySelector(".peach-status-pip, .pip");99  if (pip) {100    pip.classList.remove("pulse");101    void (pip as HTMLElement).offsetWidth;102    pip.classList.add("pulse");103  }104}105106function humanizeError(error: string | undefined): string | undefined {107  if (!error) return error;108  if (error === "STORAGE_QUOTA_EXCEEDED") {109    return "Peach has run out of browser storage. Delete some entries or clear browser storage to continue.";110  }111  return error;112}113114async function sendMessage(msg: any): Promise<any> {115  if (Capacitor.isNativePlatform()) {116    return { ok: false, error: "NOT_SUPPORTED_ON_MOBILE" };117  }118119  const MESSAGE_TIMEOUT_MS = 5000;120121  return new Promise((resolve) => {122    let settled = false;123    const timeoutId = window.setTimeout(() => {124      if (settled) return;125      settled = true;126      resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });127    }, MESSAGE_TIMEOUT_MS);128129    try {130      chrome.runtime.sendMessage(msg, (response) => {131        if (settled) return;132        settled = true;133        window.clearTimeout(timeoutId);134135        if (chrome.runtime.lastError) {136          resolve({137            ok: false,138            error:139              chrome.runtime.lastError.message ?? "SERVICE_WORKER_UNAVAILABLE",140          });141          return;142        }143144        if (response === undefined) {145          resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });146          return;147        }148149        if (response && response.ok === false) {150          response.error = humanizeError(response.error);151        }152        resolve(response);153      });154    } catch (error) {155      if (settled) return;156      settled = true;157      window.clearTimeout(timeoutId);158      resolve({159        ok: false,160        error:161          error instanceof Error ? error.message : "SERVICE_WORKER_UNAVAILABLE",162      });163    }164  });165}166167export { sendMessage };168169const ENTRY_TRANSITION_EXIT_MS = 95;170const ENTRY_TRANSITION_SETTLE_MS = 135;171172export default function App() {173  const [bootState, setBootState] = createSignal<BootState>("loading");174  const [view, setView] = createSignal<View>("lock");175  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(176    "enter"177  );178  const [contentTransitioning, setContentTransitioning] = createSignal(false);179  const [hasVault, setHasVault] = createSignal(false);180  const [onboarded, setOnboarded] = createSignal(true);181  const [entries, setEntries] = createSignal<VaultEntry[]>([]);182  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);183  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);184  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");185  const [theme, setTheme] = createSignal<"dark" | "light">("dark");186  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");187  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");188  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);189  const [lockOnClose, setLockOnClose] = createSignal(true);190  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);191  const [breachMonitoring, setBreachMonitoring] = createSignal(true);192  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);193  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);194  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);195  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);196  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);197  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");198  // Cached Pro status — synchronous for render paths. Background's199  // GET_LICENSE is async, but render-time reads of isPro() must not block.200  // Refreshed at boot, after activate/deactivate, and whenever the popup201  // re-opens onto a stored license that has changed via another window.202  const [proStatus, setProStatus] = createSignal(false);203  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);204  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);205  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");206  const [listSearchSeed, setListSearchSeed] = createSignal("");207  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);208  const [pendingCelebration, setPendingCelebration] = createSignal(false);209  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);210  // True while Panic Step 1 has bounced the user out to Export. When Export's211  // onBack fires we return to Panic instead of Settings so the user keeps the212  // destruction context they came from.213  const [returnToPanic, setReturnToPanic] = createSignal(false);214215  let contentPhaseTimer: number | undefined;216217  function applyAccent(name: AccentColorName) {218    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;219    const hex = color.hex;220    document.documentElement.style.setProperty("--peach-accent", hex);221    // Ambient surface variables — derived from the accent so surfaces shift222    // subtly toward the accent hue rather than staying fixed warm-brown.223    document.documentElement.style.setProperty("--peach-glow", hex + "2A");224    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");225    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");226  }227228  createEffect(() => {229    applyAccent(accentColor());230  });231232  createEffect(() => {233    document.documentElement.classList.toggle("light", theme() === "light");234    document.body.classList.toggle("light", theme() === "light");235  });236237  createEffect(() => {238    document.documentElement.setAttribute("data-display-font", displayFont());239  });240241  createEffect(() => {242    document.documentElement.setAttribute("data-text-size", textSize());243  });244245  createEffect(() => {246    if (reduceMotion()) {247      document.documentElement.setAttribute("data-motion", "reduce");248    } else {249      document.documentElement.removeAttribute("data-motion");250    }251  });252253  const selectedIndex = createMemo(() => {254    const currentId = selectedEntry()?.id;255    if (!currentId) return entries().length > 0 ? 0 : -1;256    return entries().findIndex((entry) => entry.id === currentId);257  });258259  async function applyAccentColor(name: AccentColorName) {260    applyAccent(name);261    setAccentColor(name);262    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });263  }264265  async function applyTheme(t: "dark" | "light") {266    setTheme(t);267    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });268  }269270  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {271    setDisplayFont(f);272    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });273  }274275  async function applyTextSize(size: "small" | "medium" | "large") {276    setTextSize(size);277    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });278  }279280  async function applyReduceMotion(enabled: boolean) {281    setReduceMotion(enabled);282    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });283  }284285  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload286  // small and lets future default updates land for actions the user hasn't287  // touched. Settings sends us the full active map; we filter and store.288  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {289    setShortcutBindings(active);290    const overrides: Record<string, Keybinding> = {};291    for (const action of Object.keys(active) as ShortcutAction[]) {292      const a = active[action];293      const d = DEFAULT_BINDINGS[action];294      const same = a.key === d.key295        && Boolean(a.ctrl)  === Boolean(d.ctrl)296        && Boolean(a.meta)  === Boolean(d.meta)297        && Boolean(a.shift) === Boolean(d.shift)298        && Boolean(a.alt)   === Boolean(d.alt);299      if (!same) overrides[action] = a;300    }301    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });302  }303304  async function applyLockOnClose(enabled: boolean) {305    setLockOnClose(enabled);306    await sendMessage({307      type: "UPDATE_SETTINGS",308      payload: { lockOnClose: enabled },309    });310  }311312  async function applyAutoLockMinutes(minutes: number) {313    setAutoLockMinutes(minutes);314    await sendMessage({315      type: "UPDATE_SETTINGS",316      payload: { autoLockMinutes: minutes },317    });318  }319320  async function applyBreachMonitoring(enabled: boolean) {321    setBreachMonitoring(enabled);322    await sendMessage({323      type: "UPDATE_SETTINGS",324      payload: { breachMonitoring: enabled },325    });326  }327328  onMount(async () => {329    // Resolve the active tab in parallel with the unlock/has-vault queries —330    // openVault()'s smart selection picks the entry matching currentTabDomain,331    // so it must be populated before openVault runs. Previously refreshCurrentTab332    // ran after openVault, leaving popups that booted already-unlocked falling333    // back to loadedEntries[0] instead of the domain match.334    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([335      sendMessage({ type: "IS_UNLOCKED" }),336      sendMessage({ type: "HAS_VAULT" }),337      refreshCurrentTab(),338      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),339    ]);340    const unlocked = Boolean(341      (unlockResponse as { ok: boolean; data?: boolean }).data342    );343    const vaultExists = Boolean(344      (vaultResponse as { ok: boolean; data?: boolean }).data345    );346    const shouldCelebrate = Boolean(347      (celebrationResponse as { ok: boolean; data?: boolean }).data348    );349    setHasVault(vaultExists);350    // Onboarding gate — show once on first install, never again. Existing351    // users (vaultExists) are auto-marked onboarded so they skip the flow352    // even on the very first popup open after this feature ships.353    try {354      const onboarded = await storageGet("peach_onboarded");355      const seen = onboarded === "true";356      if (vaultExists && !seen) {357        await storageSet("peach_onboarded", "true");358        setOnboarded(true);359      } else {360        setOnboarded(seen);361      }362    } catch {363      // storage unavailable — default to onboarded so we never block boot364      setOnboarded(true);365    }366    await Promise.all([restoreSettings(), refreshProStatus()]);367368    // Mark played before any animation so a crash mid-sequence never replays it369    if (shouldCelebrate) {370      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });371    }372373    if (unlocked && vaultExists) {374      await openVault(undefined, shouldCelebrate);375      if (shouldCelebrate) {376        setView("pro-celebration");377        window.setTimeout(() => setView("entry"), 2500);378      }379    } else if (shouldCelebrate) {380      setPendingCelebration(true);381    }382383    await refreshPendingPasskey();384385    // Track tab changes so smart sort stays current386    if (!Capacitor.isNativePlatform()) {387      const handleTabActivated = () => { void refreshCurrentTab(); };388      const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {389        if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();390      };391      try {392        chrome.tabs.onActivated.addListener(handleTabActivated);393        chrome.tabs.onUpdated.addListener(handleTabUpdated);394        onCleanup(() => {395          chrome.tabs.onActivated.removeListener(handleTabActivated);396          chrome.tabs.onUpdated.removeListener(handleTabUpdated);397        });398      } catch {399        // tabs permission may not be available in all contexts400      }401    }402403    setBootState("ready");404    document.getElementById("pre-lock")?.setAttribute("hidden", "true");405406    // Check for pending session-storage notices from the background.407    if (!Capacitor.isNativePlatform() && chrome.storage.session) {408      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as409        Record<string, { feature?: string } | undefined>;410      if (session.pendingProGate?.feature) {411        await chrome.storage.session.remove("pendingProGate");412        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);413        setSettingsInitialSection("license");414        setView("settings");415      } else if (session.pendingProNotice?.feature) {416        await chrome.storage.session.remove("pendingProNotice");417        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });418      }419    }420421    // Warm the lazy-module cache so the Suspense fallback never shows for422    // locally-bundled extension views. Without this, the first navigation to423    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which424    // covers the shell and absorbs clicks on the header.425    void Promise.all([426      import("./views/Settings").catch(() => {}),427      import("./views/Import").catch(() => {}),428      import("./views/Export").catch(() => {}),429      import("./views/Health").catch(() => {}),430      import("./views/TrashView").catch(() => {}),431    ]);432433    // Lock-on-close via a persistent port. sendMessage in pagehide is434    // unreliable — the popup context tears down before the message lands.435    // The SW's onConnect listener locks when this port disconnects.436    if (!Capacitor.isNativePlatform()) {437      let popupPort: chrome.runtime.Port | null = null;438      try {439        popupPort = chrome.runtime.connect({ name: "popup" });440      } catch { /* extension context invalidated — ignore */ }441      onCleanup(() => { try { popupPort?.disconnect(); } catch {} });442443      // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale444      // entries instead of waiting for the next GET_ENTRIES round-trip.445      const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {446        if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();447        if (msg?.type === "PRO_GATE_TRIGGERED") {448          setUpgradeHighlight(msg.payload?.feature ?? null);449          setSettingsInitialSection("license");450          setView("settings");451        }452      };453      chrome.runtime.onMessage.addListener(handleRuntimeMessage);454      onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));455    }456457    // Action handlers — keyed by ShortcutAction. The dispatcher below tests458    // each binding against the event and runs the matching handler. New459    // shortcuts only need an entry here; the binding is data, not code.460    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {461      copy_password: () => {462        const entry = selectedEntry();463        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });464      },465      copy_username: () => {466        const entry = selectedEntry();467        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });468      },469      copy_totp: () => {470        const entry = selectedEntry();471        if (!entry?.totp) return;472        try {473          const { code } = generateTOTP(entry.totp);474          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });475        } catch { /* invalid TOTP secret — silent */ }476      },477      new_entry: () => handleAdd(),478      edit_entry: () => {479        const entry = selectedEntry();480        // Passkey-only entries have nothing user-editable in the Add view; the481        // passkey credential itself is opaque. Skip the edit action for them.482        if (!entry || isPasskeyOnly(entry)) return;483        setEditEntry(entry);484        setView("add");485      },486      delete_entry: () => {487        if (selectedEntry()) void handleDelete();488      },489      lock_vault: () => { void handleHeaderLock(); },490      search: () => openList(),491      nav_prev: () => navigate(-1),492      nav_next: () => navigate(1),493      jump_vault: () => setView("entry"),494      jump_settings: () => setView("settings"),495      show_help: () => setShowShortcutsHelp(true),496    };497498    // Actions that are MEANINGFUL only on the entry-detail view. Outside499    // that scope the binding is dormant — pressing C while on Settings500    // does nothing rather than awkwardly copying from a now-stale entry.501    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([502      "copy_password", "copy_username", "copy_totp",503      "edit_entry", "delete_entry", "nav_prev", "nav_next",504    ]);505506    const handleGlobalKeydown = (e: KeyboardEvent) => {507      const v = view();508      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"509        || (e.target as HTMLElement)?.tagName === "TEXTAREA"510        || (e.target as HTMLElement)?.isContentEditable;511      const isPrintableSearchKey =512        e.key.length === 1 &&513        !e.ctrlKey &&514        !e.metaKey &&515        !e.altKey;516517      // No input during the pro celebration sequence518      if (v === "pro-celebration") return;519520      // Help dialog: Escape closes it; eat the keypress so it doesn't521      // also navigate away from the underlying view.522      if (showShortcutsHelp()) {523        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }524        return;525      }526527      // ── Escape — fixed binding (not user-customizable) ───────528      if (e.key === "Escape") {529        if (v === "list") { setView("entry"); return; }530        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }531      }532533      // Bindings-driven dispatch. Single-key letter bindings without534      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is535      // inside an input, so users can type into search/forms normally.536      const bindings = shortcutBindings();537      for (const action of Object.keys(bindings) as ShortcutAction[]) {538        const binding = bindings[action];539        if (!matchKeybinding(e, binding)) continue;540        // Single-key letter bindings need the input-focus guard. Bindings541        // with any modifier are safe — Ctrl+L doesn't conflict with typing.542        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;543        if (!hasMod && binding.key.length === 1 && inInput) return;544        if (ENTRY_SCOPED.has(action) && v !== "entry") return;545        e.preventDefault();546        SHORTCUT_HANDLERS[action]?.();547        return;548      }549550      // Type-to-search: in entry view, any printable key not consumed by a551      // shortcut above primes the list search seed and opens the list.552      // Kept outside the bindings table because it's a behavior, not a553      // discrete action — every printable character can trigger it.554      if (v === "entry" && !inInput && isPrintableSearchKey) {555        e.preventDefault();556        primeListSearch(e.key);557        return;558      }559    };560    window.addEventListener("keydown", handleGlobalKeydown);561    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));562563    if (!Capacitor.isNativePlatform()) {564      const handleStorageChanged = (565        changes: Record<string, chrome.storage.StorageChange>,566        areaName: string567      ) => {568        if (areaName !== "session") return;569        if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {570          return;571        }572        void refreshPendingPasskey();573      };574      chrome.storage.onChanged.addListener(handleStorageChanged);575      onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));576    }577  });578579  async function refreshCurrentTab() {580    if (Capacitor.isNativePlatform()) return;581    try {582      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });583      const url = tab?.url ?? tab?.pendingUrl ?? "";584      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");585    } catch {586      setCurrentTabDomain("");587    }588  }589590  async function refreshPendingPasskey() {591    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });592    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);593  }594595  async function refreshProStatus() {596    const res = await sendMessage({ type: "GET_LICENSE" });597    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;598    setProStatus(Boolean(data?.valid && data?.plan === "pro"));599  }600601  async function restoreSettings() {602    const res = await sendMessage({ type: "GET_SETTINGS" });603    const s = (res as { ok: boolean; data?: any }).data ?? {};604    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {605      setAccentColor(s.accentColor as AccentColorName);606    }607    setTheme(s.theme === "light" ? "light" : "dark");608    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {609      setDisplayFont(s.displayFont);610    } else {611      setDisplayFont("cormorant-italic");612    }613    if (s.textSize === "small" || s.textSize === "large") {614      setTextSize(s.textSize);615    } else {616      setTextSize("medium");617    }618    setReduceMotion(s.reduceMotion === true);619    setLockOnClose(s.lockOnClose !== false);620    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);621    setBreachMonitoring(s.breachMonitoring !== false);622    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);623    setShortcutBindings(getActiveBindings(s.shortcuts));624  }625626  async function applyTrashRetention(days: number) {627    setTrashRetentionDays(days);628    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });629  }630631  function primeListSearch(seed: string) {632    setListSearchSeed(seed);633    setListSearchSeedNonce((value) => value + 1);634    openList();635  }636637  // Returns null when it detected a dead service worker and triggered handleLock().638  // Callers that need to abort (e.g. openVault) check for null rather than relying639  // on view() state, which may already be "lock" during normal startup flows.640  async function loadEntries(): Promise<VaultEntry[] | null> {641    const response = await sendMessage({ type: "GET_ENTRIES" });642    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };643644    // If the service worker was killed and restarted (MV3 workers sleep), the645    // vault will be locked again — or the worker may not respond at all.646    // In either case, send the user to the lock screen rather than silently647    // showing an empty vault (which looks like data loss).648    if (!res.ok) {649      if (650        res.error === "vault locked" ||651        res.error === "SERVICE_WORKER_UNAVAILABLE" ||652        (typeof res.error === "string" && res.error.includes("locked"))653      ) {654        handleLock();655        return null; // signal emergency lock to callers656      }657      return [];658    }659660    const loadedEntries = res.data ?? [];661    setEntries(loadedEntries);662663    const currentId = selectedEntry()?.id;664    if (currentId) {665      setSelectedEntry(666        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null667      );668    }669670    return loadedEntries;671  }672673  async function openVault(preferredEntryId?: string, skipViewSet = false) {674    // Purge expired trash entries on each vault open675    const retDays = trashRetentionDays();676    if (retDays > 0) {677      void sendMessage({678        type: "PURGE_EXPIRED_TRASH",679        payload: { retentionMs: retDays * 86_400_000 },680      });681    }682683    const loadedEntries = await loadEntries();684685    // null means loadEntries() triggered an emergency lock (service worker died).686    // Don't override it by setting view back to "entry" with an empty vault.687    if (loadedEntries === null) return;688689    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry690    let nextSelectedEntry: VaultEntry | null = null;691    if (preferredEntryId) {692      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;693    }694    if (!nextSelectedEntry) {695      const tabDomain = currentTabDomain();696      if (tabDomain) {697        nextSelectedEntry = loadedEntries.find((e) => {698          if (e.type === "login") {699            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;700            for (const extra of e.additionalUrls ?? []) {701              if ((extractDomain(extra) ?? "") === tabDomain) return true;702            }703            return false;704          }705          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;706          return false;707        }) ?? null;708      }709    }710    nextSelectedEntry ??= loadedEntries[0] ?? null;711712    setSelectedEntry(nextSelectedEntry);713    setEditEntry(undefined);714    setContentTransitioning(false);715    setContentPhase("enter");716    queueContentIdle();717    if (!skipViewSet) setView("entry");718  }719720  async function handleUnlock() {721    setHasVault(true);722    triggerPipPulse();723    await restoreSettings();724    const celebrating = pendingCelebration();725    if (celebrating) {726      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });727      setPendingCelebration(false);728    }729    await openVault(undefined, celebrating);730    if (celebrating) {731      setView("pro-celebration");732      window.setTimeout(() => setView("entry"), 2500);733    }734  }735736  function handleSelectEntry(entry: VaultEntry) {737    setSelectedEntry(entry);738    setContentTransitioning(false);739    setContentPhase("enter");740    queueContentIdle();741    setView("entry");742  }743744  function handleAdd() {745    setEditEntry(undefined);746    setView("add");747  }748749  async function handleDelete() {750    const entry = selectedEntry();751    if (!entry) return;752    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });753    const loadedEntries = await loadEntries() ?? [];754    setSelectedEntry(loadedEntries[0] ?? null);755    setView("entry");756  }757758  async function handleDeleteMany(ids: string[]) {759    for (const id of ids) {760      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });761    }762    const loadedEntries = await loadEntries() ?? [];763    // If the currently selected entry was among the deleted, move to first764    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);765    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);766  }767768  async function handleSave(savedEntry?: VaultEntry) {769    await openVault(savedEntry?.id);770  }771772  function handleBack() {773    setEditEntry(undefined);774    setView("entry");775  }776777  function handleLock() {778    clearCanarySuppressions();779    setEntries([]);780    setSelectedEntry(null);781    setEditEntry(undefined);782    setContentPhase("idle");783    setView("lock");784  }785786  function handleHeaderLock() {787    // Lock the UI immediately — do not wait for the service worker. If the SW788    // is dead or slow, the 5s sendMessage timeout would create a dead-click789    // window. The SW will lock on its next wake regardless.790    handleLock();791    void sendMessage({ type: "LOCK" });792  }793794  function navigate(dir: number) {795    const allEntries = entries();796    if (allEntries.length === 0) return;797    const currentIndex = selectedIndex();798    const baseIndex = currentIndex >= 0 ? currentIndex : 0;799    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;800    setSelectedEntry(allEntries[nextIndex]);801    setContentPhase("enter");802    queueContentIdle();803  }804805  function openList() {806    setView("list");807  }808809  function openHealth() {810    setEditEntry(undefined);811    setView("health");812  }813814  function handleOpenFileImport() {815    setRestoreView("file");816  }817818  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;819820  function handleFixEntry(entry: VaultEntry) {821    // Passkey-only entries have no editable surface — drop into view mode822    // instead of opening the Add editor.823    if (isPasskeyOnly(entry)) {824      setSelectedEntry(entry);825      setView("entry");826      return;827    }828    setEditEntry(entry);829    setView("add");830  }831832  const isLockedView = () => view() === "lock";833834  async function handleApprovePendingPasskey() {835    const pending = pendingPasskey();836    if (!pending) return;837    if (pending.browser === "firefox" && pending.type === "create") {838      // Firefox path: popup itself runs navigator.credentials.create. The839      // background never approved/rejected anything — it just stashed840      // intent. After the popup-driven flow resolves (success or cancel),841      // clear the pending key so the popup doesn't re-show this on next open.842      const { createFirefoxPasskey } = await import("./firefox-passkey");843      const result = await createFirefoxPasskey(pending);844      if (!result.ok) {845        console.warn("Peach Firefox passkey create failed:", result.error);846      }847      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });848      setPendingPasskey(null);849      void loadEntries();850      return;851    }852    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });853    setPendingPasskey(null);854  }855856  async function handleDenyPendingPasskey() {857    const pending = pendingPasskey();858    if (!pending) return;859    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });860    setPendingPasskey(null);861  }862863  function queueContentIdle(after?: () => void) {864    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);865    contentPhaseTimer = window.setTimeout(() => {866      setContentPhase("idle");867      after?.();868    }, ENTRY_TRANSITION_SETTLE_MS);869  }870871  return (872    <div class="popup-root peach-theme">873      <Show when={bootState() === "ready"}>874        <Show875          when={!pendingPasskey()}876          fallback={877            <PasskeyApprovalView878              type={pendingPasskey()!.type}879              rpName={pendingPasskey()!.rpName}880              rpId={pendingPasskey()!.rpId}881              userName={pendingPasskey()!.userName}882              userDisplayName={pendingPasskey()!.userDisplayName}883              onApprove={handleApprovePendingPasskey}884              onDeny={handleDenyPendingPasskey}885            />886          }887        >888          <Show889            when={!isLockedView()}890            fallback={891              <Show892                when={onboarded() || hasVault()}893                fallback={894                  <Onboarding895                    onComplete={() => { setOnboarded(true); }}896                  />897                }898              >899                <LockView900                  hasVault={hasVault()}901                  ready={bootState() === "ready"}902                  isPro={proStatus()}903                  onUnlock={handleUnlock}904                  onBackToOnboarding={905                    !hasVault()906                      ? () => setOnboarded(false)907                      : undefined908                  }909                />910              </Show>911            }912          >913            <Show914              when={view() !== "pro-celebration"}915              fallback={<ProCelebration />}916            >917            <section918              id="hd-shell"919              class="peach-shell peach-theme"920              data-surface="extension"921            >922            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>923              <PeachWordmark unlocked />924              <div class="peach-chrome-actions">925                <button926                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"927                  onClick={() => setView("settings")}928                  aria-label="Settings"929                >930                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">931                    <path932                      d="M5.91 1.11C6.38-.02 7.62-.02 8.09 1.11L8.31 1.64C8.48 2.05 8.91 2.27 9.34 2.17L9.9 2.04C11.1 1.76 11.98 2.64 11.7 3.84L11.57 4.4C11.47 4.83 11.69 5.26 12.1 5.43L12.63 5.65C13.76 6.12 13.76 7.36 12.63 7.83L12.1 8.05C11.69 8.22 11.47 8.65 11.57 9.08L11.7 9.64C11.98 10.84 11.1 11.72 9.9 11.44L9.34 11.31C8.91 11.21 8.48 11.43 8.31 11.84L8.09 12.37C7.62 13.5 6.38 13.5 5.91 12.37L5.69 11.84C5.52 11.43 5.09 11.21 4.66 11.31L4.1 11.44C2.9 11.72 2.02 10.84 2.3 9.64L2.43 9.08C2.53 8.65 2.31 8.22 1.9 8.05L1.37 7.83C.24 7.36.24 6.12 1.37 5.65L1.9 5.43C2.31 5.26 2.53 4.83 2.43 4.4L2.3 3.84C2.02 2.64 2.9 1.76 4.1 2.04L4.66 2.17C5.09 2.27 5.52 2.05 5.69 1.64L5.91 1.11Z"933                      stroke="currentColor"934                      stroke-width="0.9"935                    />936                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />937                  </svg>938                </button>939                <button940                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"941                  onClick={handleAdd}942                  aria-label="New entry"943                >944                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">945                    <path d="M5.5 1v9M1 5.5h9" />946                  </svg>947                </button>948                <button949                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"950                  onClick={() => void handleHeaderLock()}951                  aria-label="Lock vault"952                >953                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">954                    <path955                      d="M3.75 6V4.75C3.75 2.96 5.21 1.5 7 1.5C8.79 1.5 10.25 2.96 10.25 4.75V6"956                      stroke="currentColor"957                      stroke-width="1"958                      stroke-linecap="round"959                    />960                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />961                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />962                  </svg>963                </button>964              </div>965            </header>966967            <Show when={pendingProNotice() !== null}>968              <div class="peach-pro-notice-banner">969                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>970                <button971                  class="peach-pro-notice-link"972                  onClick={() => {973                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);974                    setSettingsInitialSection("license");975                    setView("settings");976                    setPendingProNotice(null);977                  }}978                >979                  Learn more →980                </button>981                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>982              </div>983            </Show>984985            <div class="peach-shell-body">986              <div class="peach-shell-veil"></div>987              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>988                <EntryView989                  entry={selectedEntry()}990                  onDelete={handleDelete}991                  onFieldSaved={() => void loadEntries()}992                  onEscape={() => { setView("list"); }}993                />994              </div>995996              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>997                <div class="peach-search-bar">998                  <span class="peach-search-icon">999                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1000                      <circle cx="5.5" cy="5.5" r="3.75" />1001                      <path d="M8.75 8.75L11.5 11.5" />1002                    </svg>1003                  </span>1004                  <input1005                    class="peach-search-input"1006                    placeholder="search vault..."1007                    autocomplete="off"1008                    aria-label="Search vault entries"1009                    onClick={openList}1010                    onFocus={openList}1011                    readOnly1012                  />1013                  <div class="peach-search-meta">1014                    <span class="peach-search-counter">1015                      {entries().length > 01016                        ? `${selectedIndex() + 1} / ${entries().length}`1017                        : "0 entries"}1018                    </span>1019                    <span class="peach-divider"></span>1020                    <button1021                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1022                      onClick={() => navigate(-1)}1023                      aria-label="Previous entry"1024                      disabled={entries().length === 0}1025                    >1026                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1027                        <path d="M5 1L1 5.5L5 10" />1028                      </svg>1029                    </button>1030                    <button1031                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1032                      onClick={() => navigate(1)}1033                      aria-label="Next entry"1034                      disabled={entries().length === 0}1035                    >1036                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1037                        <path d="M1 1L5 5.5L1 10" />1038                      </svg>1039                    </button>1040                  </div>1041                </div>1042              </section>1043            </div>10441045            <Show when={view() === "list"}>1046              <VaultView1047                entries={entries()}1048                selectedEntryId={selectedEntry()?.id}1049                currentTabDomain={currentTabDomain()}1050                sortOrder={sortOrder()}1051                searchSeed={listSearchSeed()}1052                searchSeedNonce={listSearchSeedNonce()}1053                onSelectEntry={handleSelectEntry}1054                onSortOrderChange={setSortOrder}1055                onAdd={handleAdd}1056                onClose={() => setView("entry")}1057                onOpenTrash={() => setView("trash")}1058                onDeleteMany={handleDeleteMany}1059              />1060            </Show>1061            <Show when={view() === "settings"}>1062              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1063                <SettingsView1064                  entriesCount={entries().length}1065                  breachMonitoring={breachMonitoring()}1066                  lockOnClose={lockOnClose()}1067                  autoLockMinutes={autoLockMinutes()}1068                  trashRetentionDays={trashRetentionDays()}1069                  theme={theme()}1070                  accentColor={accentColor()}1071                  displayFont={displayFont()}1072                  textSize={textSize()}1073                  reduceMotion={reduceMotion()}1074                  isPro={proStatus()}1075                  initialSection={settingsInitialSection()}1076                  upgradeHighlight={upgradeHighlight()}1077                  onBreachMonitoringChange={applyBreachMonitoring}1078                  onLockOnCloseChange={applyLockOnClose}1079                  onAutoLockMinutesChange={applyAutoLockMinutes}1080                  onTrashRetentionChange={applyTrashRetention}1081                  onThemeChange={applyTheme}1082                  onAccentChange={applyAccentColor}1083                  onDisplayFontChange={applyDisplayFont}1084                  onTextSizeChange={applyTextSize}1085                  onReduceMotionChange={applyReduceMotion}1086                  shortcuts={shortcutBindings()}1087                  onShortcutsChange={applyShortcuts}1088                  onLicenseChange={async () => {1089                    // After activation/deactivation: refresh Pro status,1090                    // re-load entries (defensive — signal state can drift if1091                    // the SW briefly restarts during the verify+save round-trip),1092                    // and replay the Pro celebration if this is the first time1093                    // a valid Pro license is seen on this device.1094                    await refreshProStatus();1095                    void loadEntries();1096                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1097                    if ((should as { ok: boolean; data?: boolean }).data === true) {1098                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1099                      setView("pro-celebration");1100                      window.setTimeout(() => setView("settings"), 2500);1101                    }1102                  }}1103                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1104                  onImport={() => setView("import")}1105                  onExport={() => setView("export")}1106                  onBreachCheckDone={loadEntries}1107                  onOpenHealth={openHealth}1108                  onOpenFileImport={handleOpenFileImport}1109                  onOpenPanic={() => setView("panic")}1110                />1111              </Suspense>1112            </Show>1113            <Show when={view() === "add"}>1114              <AddView1115                entry={editEntry()}1116                entries={entries()}1117                onBack={handleBack}1118                onSave={handleSave}1119              />1120            </Show>1121            <Show when={view() === "import"}>1122              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1123                <ImportView onBack={handleBack} onImport={handleSave} />1124              </Suspense>1125            </Show>1126            <Show when={view() === "export"}>1127              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1128                <ExportView1129                  onBack={() => {1130                    if (returnToPanic()) {1131                      setReturnToPanic(false);1132                      setView("panic");1133                    } else {1134                      handleBack();1135                    }1136                  }}1137                />1138              </Suspense>1139            </Show>1140            <Show when={view() === "panic"}>1141              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1142                <PanicView1143                  onCancel={() => setView("settings")}1144                  onOpenExport={() => {1145                    setReturnToPanic(true);1146                    setView("export");1147                  }}1148                  onDestroyed={async () => {1149                    clearCanarySuppressions();1150                    setEntries([]);1151                    setSelectedEntry(null);1152                    setEditEntry(undefined);1153                    setHasVault(false);1154                    setOnboarded(false);1155                    setProStatus(false);1156                    setPendingPasskey(null);1157                    setUpgradeHighlight(null);1158                    setSettingsInitialSection(null);1159                    setPendingProNotice(null);1160                    setPendingCelebration(false);1161                    setReturnToPanic(false);1162                    setContentPhase("idle");1163                    setView("lock");1164                  }}1165                />1166              </Suspense>1167            </Show>1168            <Show when={view() === "health"}>1169              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1170                <HealthView1171                  entries={entries()}1172                  isPro={proStatus()}1173                  onFixEntry={handleFixEntry}1174                  onBack={() => setView("settings")}1175                  onRefresh={loadEntries}1176                />1177              </Suspense>1178            </Show>1179            <Show when={view() === "trash"}>1180              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1181                <TrashView1182                  onBack={() => setView("list")}1183                  onRestored={() => void loadEntries()}1184                />1185              </Suspense>1186            </Show>1187            <Show when={restoreView() === "file"}>1188              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1189                <ImportView1190                  mode="onboarding"1191                  replacesExistingVault={true}1192                  onBack={() => setRestoreView(null)}1193                  onImport={async () => {1194                    setRestoreView(null);1195                    await handleUnlock();1196                  }}1197                />1198              </Suspense>1199            </Show>1200            </section>1201            </Show>1202          </Show>1203        </Show>1204      </Show>1205      <Show when={showShortcutsHelp()}>1206        <ShortcutsHelpOverlay1207          bindings={shortcutBindings()}1208          onClose={() => setShowShortcutsHelp(false)}1209        />1210      </Show>1211    </div>1212  );1213}12141215function ShortcutsHelpOverlay(props: {1216  bindings: Record<ShortcutAction, Keybinding>;1217  onClose: () => void;1218}) {1219  return (1220    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1221      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1222        <div class="peach-shortcuts-help-head">1223          <h3>Keyboard shortcuts</h3>1224          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1225        </div>1226        <div class="peach-shortcuts-help-body">1227          <p class="peach-settings-sub-label">ENTRY VIEW</p>1228          <ul>1229            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1230              <li>1231                <span>{d.label}</span>1232                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1233              </li>1234            ))}1235          </ul>1236          <p class="peach-settings-sub-label">ANYWHERE</p>1237          <ul>1238            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1239              <li>1240                <span>{d.label}</span>1241                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1242              </li>1243            ))}1244          </ul>1245        </div>1246      </div>1247    </div>1248  );1249}