App.tsx

48.5 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { ACCENT_COLORS } from "../shared/types";3import type { AccentColorName, PasskeyEntry, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";4import { LockView } from "./views/Lock";5import { Onboarding } from "./views/Onboarding";6import { ProCelebration } from "./views/ProCelebration";7import { VaultView, type SortOrder } from "./views/Vault";8import { EntryView } from "./views/Entry";9import { AddView } from "./views/Add";10import { PeachWordmark } from "./components/PeachMark";11import { PasskeyApprovalView } from "./views/PasskeyApproval";12import { PasskeyEntryView } from "./views/PasskeyEntry";13import { extractDomain } from "../shared/domain";14import { popupCopy } from "./copy";15import {16  DEFAULT_BINDINGS,17  formatKeybinding,18  getActiveBindings,19  matchKeybinding,20  SHORTCUT_DESCRIPTORS,21  type Keybinding,22  type ShortcutAction,23} from "../shared/shortcuts";24import { generateTOTP } from "../crypto/totp";2526const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));27const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));28const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));29const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));30const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));31const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));3233type View =34  | "lock"35  | "pro-celebration"36  | "entry"37  | "list"38  | "add"39  | "settings"40  | "import"41  | "export"42  | "health"43  | "trash"44  | "panic";45type BootState = "loading" | "ready";4647const canarySuppressMap = new Map<string, boolean>();48let shellRingAnimation: Animation | null = null;4950export function isCanarySuppressed(entryId: string): boolean {51  return canarySuppressMap.get(entryId) ?? false;52}5354export function setCanarySuppressed(entryId: string, suppressed: boolean): void {55  canarySuppressMap.set(entryId, suppressed);56}5758export function clearCanarySuppressions(): void {59  canarySuppressMap.clear();60}6162export function triggerRing() {63  const shell = document.getElementById("hd-shell");64  if (!shell) return;6566  shellRingAnimation?.cancel();67  shell.dataset.glowing = "true";68  const animation = shell.animate(69    [70      { offset: 0, boxShadow: "var(--copy-shadow)" },71      {72        offset: 0.3,73        boxShadow:74          "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)",75      },76      { offset: 1, boxShadow: "var(--copy-shadow)" },77    ],78    {79      duration: 720,80      easing: "cubic-bezier(0.4, 0, 0.2, 1)",81      fill: "none",82    }83  );84  shellRingAnimation = animation;85  const clearGlow = () => {86    if (shellRingAnimation !== animation) return;87    shellRingAnimation = null;88    delete shell.dataset.glowing;89  };90  animation.onfinish = clearGlow;91  animation.oncancel = clearGlow;92}939495export function triggerPipPulse() {96  const pip = document.querySelector(".peach-status-pip, .pip");97  if (pip) {98    pip.classList.remove("pulse");99    void (pip as HTMLElement).offsetWidth;100    pip.classList.add("pulse");101  }102}103104function humanizeError(error: string | undefined): string | undefined {105  if (!error) return error;106  if (error === "STORAGE_QUOTA_EXCEEDED") {107    return "Peach has run out of browser storage. Delete some entries or clear browser storage to continue.";108  }109  return error;110}111112async function sendMessage(msg: any): Promise<any> {113  const MESSAGE_TIMEOUT_MS = 5000;114115  return new Promise((resolve) => {116    let settled = false;117    const timeoutId = window.setTimeout(() => {118      if (settled) return;119      settled = true;120      resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });121    }, MESSAGE_TIMEOUT_MS);122123    try {124      chrome.runtime.sendMessage(msg, (response) => {125        if (settled) return;126        settled = true;127        window.clearTimeout(timeoutId);128129        if (chrome.runtime.lastError) {130          resolve({131            ok: false,132            error:133              chrome.runtime.lastError.message ?? "SERVICE_WORKER_UNAVAILABLE",134          });135          return;136        }137138        if (response === undefined) {139          resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });140          return;141        }142143        if (response && response.ok === false) {144          response.error = humanizeError(response.error);145        }146        resolve(response);147      });148    } catch (error) {149      if (settled) return;150      settled = true;151      window.clearTimeout(timeoutId);152      resolve({153        ok: false,154        error:155          error instanceof Error ? error.message : "SERVICE_WORKER_UNAVAILABLE",156      });157    }158  });159}160161export { sendMessage };162163const ENTRY_TRANSITION_EXIT_MS = 95;164const ENTRY_TRANSITION_SETTLE_MS = 135;165166export default function App() {167  const [bootState, setBootState] = createSignal<BootState>("loading");168  const [view, setView] = createSignal<View>("lock");169  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(170    "enter"171  );172  const [contentTransitioning, setContentTransitioning] = createSignal(false);173  const [hasVault, setHasVault] = createSignal(false);174  const [onboarded, setOnboarded] = createSignal(true);175  const [entries, setEntries] = createSignal<VaultEntry[]>([]);176  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);177  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);178  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");179  const [theme, setTheme] = createSignal<"dark" | "light">("dark");180  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");181  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");182  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);183  const [lockOnClose, setLockOnClose] = createSignal(true);184  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);185  const [breachMonitoring, setBreachMonitoring] = createSignal(true);186  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);187  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);188  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);189  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);190  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);191  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");192  // Cached Pro status — synchronous for render paths. Background's193  // GET_LICENSE is async, but render-time reads of isPro() must not block.194  // Refreshed at boot, after activate/deactivate, and whenever the popup195  // re-opens onto a stored license that has changed via another window.196  const [proStatus, setProStatus] = createSignal(false);197  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);198  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);199  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");200  const [listSearchSeed, setListSearchSeed] = createSignal("");201  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);202  const [pendingCelebration, setPendingCelebration] = createSignal(false);203  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);204  // True while Panic Step 1 has bounced the user out to Export. When Export's205  // onBack fires we return to Panic instead of Settings so the user keeps the206  // destruction context they came from.207  const [returnToPanic, setReturnToPanic] = createSignal(false);208209  let contentPhaseTimer: number | undefined;210211  function applyAccent(name: AccentColorName) {212    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;213    const hex = color.hex;214    document.documentElement.style.setProperty("--peach-accent", hex);215    // Ambient surface variables — derived from the accent so surfaces shift216    // subtly toward the accent hue rather than staying fixed warm-brown.217    document.documentElement.style.setProperty("--peach-glow", hex + "2A");218    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");219    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");220  }221222  createEffect(() => {223    applyAccent(accentColor());224  });225226  createEffect(() => {227    document.documentElement.classList.toggle("light", theme() === "light");228    document.body.classList.toggle("light", theme() === "light");229  });230231  createEffect(() => {232    document.documentElement.setAttribute("data-display-font", displayFont());233  });234235  createEffect(() => {236    document.documentElement.setAttribute("data-text-size", textSize());237  });238239  createEffect(() => {240    if (reduceMotion()) {241      document.documentElement.setAttribute("data-motion", "reduce");242    } else {243      document.documentElement.removeAttribute("data-motion");244    }245  });246247  const selectedIndex = createMemo(() => {248    const currentId = selectedEntry()?.id;249    if (!currentId) return entries().length > 0 ? 0 : -1;250    return entries().findIndex((entry) => entry.id === currentId);251  });252253  async function applyAccentColor(name: AccentColorName) {254    applyAccent(name);255    setAccentColor(name);256    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });257  }258259  async function applyTheme(t: "dark" | "light") {260    setTheme(t);261    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });262  }263264  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {265    setDisplayFont(f);266    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });267  }268269  async function applyTextSize(size: "small" | "medium" | "large") {270    setTextSize(size);271    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });272  }273274  async function applyReduceMotion(enabled: boolean) {275    setReduceMotion(enabled);276    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });277  }278279  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload280  // small and lets future default updates land for actions the user hasn't281  // touched. Settings sends us the full active map; we filter and store.282  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {283    setShortcutBindings(active);284    const overrides: Record<string, Keybinding> = {};285    for (const action of Object.keys(active) as ShortcutAction[]) {286      const a = active[action];287      const d = DEFAULT_BINDINGS[action];288      const same = a.key === d.key289        && Boolean(a.ctrl)  === Boolean(d.ctrl)290        && Boolean(a.meta)  === Boolean(d.meta)291        && Boolean(a.shift) === Boolean(d.shift)292        && Boolean(a.alt)   === Boolean(d.alt);293      if (!same) overrides[action] = a;294    }295    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });296  }297298  async function applyLockOnClose(enabled: boolean) {299    setLockOnClose(enabled);300    await sendMessage({301      type: "UPDATE_SETTINGS",302      payload: { lockOnClose: enabled },303    });304  }305306  async function applyAutoLockMinutes(minutes: number) {307    setAutoLockMinutes(minutes);308    await sendMessage({309      type: "UPDATE_SETTINGS",310      payload: { autoLockMinutes: minutes },311    });312  }313314  async function applyBreachMonitoring(enabled: boolean) {315    setBreachMonitoring(enabled);316    await sendMessage({317      type: "UPDATE_SETTINGS",318      payload: { breachMonitoring: enabled },319    });320  }321322  onMount(async () => {323    // Resolve the active tab in parallel with the unlock/has-vault queries —324    // openVault()'s smart selection picks the entry matching currentTabDomain,325    // so it must be populated before openVault runs. Previously refreshCurrentTab326    // ran after openVault, leaving popups that booted already-unlocked falling327    // back to loadedEntries[0] instead of the domain match.328    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([329      sendMessage({ type: "IS_UNLOCKED" }),330      sendMessage({ type: "HAS_VAULT" }),331      refreshCurrentTab(),332      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),333    ]);334    const unlocked = Boolean(335      (unlockResponse as { ok: boolean; data?: boolean }).data336    );337    const vaultExists = Boolean(338      (vaultResponse as { ok: boolean; data?: boolean }).data339    );340    const shouldCelebrate = Boolean(341      (celebrationResponse as { ok: boolean; data?: boolean }).data342    );343    setHasVault(vaultExists);344    // Onboarding gate — show once on first install, never again. Existing345    // users (vaultExists) are auto-marked onboarded so they skip the flow346    // even on the very first popup open after this feature ships.347    try {348      const onboardingState = await chrome.storage.local.get("peach_onboarded");349      const seen = onboardingState.peach_onboarded === true;350      if (vaultExists && !seen) {351        await chrome.storage.local.set({ peach_onboarded: true });352        setOnboarded(true);353      } else {354        setOnboarded(seen);355      }356    } catch {357      // storage unavailable — default to onboarded so we never block boot358      setOnboarded(true);359    }360    await Promise.all([restoreSettings(), refreshProStatus()]);361362    // Mark played before any animation so a crash mid-sequence never replays it363    if (shouldCelebrate) {364      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });365    }366367    if (unlocked && vaultExists) {368      await openVault(undefined, shouldCelebrate);369      if (shouldCelebrate) {370        setView("pro-celebration");371        window.setTimeout(() => setView("entry"), 2500);372      }373    } else if (shouldCelebrate) {374      setPendingCelebration(true);375    }376377    await refreshPendingPasskey();378379    // Track tab changes so smart sort stays current380    const handleTabActivated = () => { void refreshCurrentTab(); };381    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {382      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();383    };384    try {385      chrome.tabs.onActivated.addListener(handleTabActivated);386      chrome.tabs.onUpdated.addListener(handleTabUpdated);387      onCleanup(() => {388        chrome.tabs.onActivated.removeListener(handleTabActivated);389        chrome.tabs.onUpdated.removeListener(handleTabUpdated);390      });391    } catch {392      // tabs permission may not be available in all contexts393    }394395    setBootState("ready");396    document.getElementById("pre-lock")?.setAttribute("hidden", "true");397398    // Check for pending session-storage notices from the background.399    if (chrome.storage.session) {400      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as401        Record<string, { feature?: string } | undefined>;402      if (session.pendingProGate?.feature) {403        await chrome.storage.session.remove("pendingProGate");404        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);405        setSettingsInitialSection("license");406        setView("settings");407      } else if (session.pendingProNotice?.feature) {408        await chrome.storage.session.remove("pendingProNotice");409        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });410      }411    }412413    // Warm the lazy-module cache so the Suspense fallback never shows for414    // locally-bundled extension views. Without this, the first navigation to415    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which416    // covers the shell and absorbs clicks on the header.417    void Promise.all([418      import("./views/Settings").catch(() => {}),419      import("./views/Import").catch(() => {}),420      import("./views/Export").catch(() => {}),421      import("./views/Health").catch(() => {}),422      import("./views/TrashView").catch(() => {}),423    ]);424425    // Lock-on-close via a persistent port. sendMessage in pagehide is426    // unreliable — the popup context tears down before the message lands.427    // The SW's onConnect listener locks when this port disconnects.428    let popupPort: chrome.runtime.Port | null = null;429    try {430      popupPort = chrome.runtime.connect({ name: "popup" });431    } catch { /* extension context invalidated — ignore */ }432    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });433434    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale435    // entries instead of waiting for the next GET_ENTRIES round-trip.436    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {437      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();438      if (msg?.type === "PRO_GATE_TRIGGERED") {439        // Background never navigates UI directly — it asks; the popup decides.440        // Land on Settings → License with the triggering feature highlighted.441        setUpgradeHighlight(msg.payload?.feature ?? null);442        setSettingsInitialSection("license");443        setView("settings");444      }445    };446    chrome.runtime.onMessage.addListener(handleRuntimeMessage);447    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));448449    // Action handlers — keyed by ShortcutAction. The dispatcher below tests450    // each binding against the event and runs the matching handler. New451    // shortcuts only need an entry here; the binding is data, not code.452    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {453      copy_password: () => {454        const entry = selectedEntry();455        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });456      },457      copy_username: () => {458        const entry = selectedEntry();459        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });460      },461      copy_totp: () => {462        const entry = selectedEntry();463        if (!entry?.totp) return;464        try {465          const { code } = generateTOTP(entry.totp);466          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });467        } catch { /* invalid TOTP secret — silent */ }468      },469      new_entry: () => handleAdd(),470      edit_entry: () => {471        const entry = selectedEntry();472        if (!entry || entry.type === "passkey") return;473        setEditEntry(entry);474        setView("add");475      },476      delete_entry: () => {477        if (selectedEntry()) void handleDelete();478      },479      lock_vault: () => { void handleHeaderLock(); },480      search: () => openList(),481      nav_prev: () => navigate(-1),482      nav_next: () => navigate(1),483      jump_vault: () => setView("entry"),484      jump_settings: () => setView("settings"),485      show_help: () => setShowShortcutsHelp(true),486    };487488    // Actions that are MEANINGFUL only on the entry-detail view. Outside489    // that scope the binding is dormant — pressing C while on Settings490    // does nothing rather than awkwardly copying from a now-stale entry.491    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([492      "copy_password", "copy_username", "copy_totp",493      "edit_entry", "delete_entry", "nav_prev", "nav_next",494    ]);495496    const handleGlobalKeydown = (e: KeyboardEvent) => {497      const v = view();498      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"499        || (e.target as HTMLElement)?.tagName === "TEXTAREA"500        || (e.target as HTMLElement)?.isContentEditable;501      const isPrintableSearchKey =502        e.key.length === 1 &&503        !e.ctrlKey &&504        !e.metaKey &&505        !e.altKey;506507      // No input during the pro celebration sequence508      if (v === "pro-celebration") return;509510      // Help dialog: Escape closes it; eat the keypress so it doesn't511      // also navigate away from the underlying view.512      if (showShortcutsHelp()) {513        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }514        return;515      }516517      // ── Escape — fixed binding (not user-customizable) ───────518      if (e.key === "Escape") {519        if (v === "list") { setView("entry"); return; }520        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }521      }522523      // Bindings-driven dispatch. Single-key letter bindings without524      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is525      // inside an input, so users can type into search/forms normally.526      const bindings = shortcutBindings();527      for (const action of Object.keys(bindings) as ShortcutAction[]) {528        const binding = bindings[action];529        if (!matchKeybinding(e, binding)) continue;530        // Single-key letter bindings need the input-focus guard. Bindings531        // with any modifier are safe — Ctrl+L doesn't conflict with typing.532        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;533        if (!hasMod && binding.key.length === 1 && inInput) return;534        if (ENTRY_SCOPED.has(action) && v !== "entry") return;535        e.preventDefault();536        SHORTCUT_HANDLERS[action]?.();537        return;538      }539540      // Type-to-search: in entry view, any printable key not consumed by a541      // shortcut above primes the list search seed and opens the list.542      // Kept outside the bindings table because it's a behavior, not a543      // discrete action — every printable character can trigger it.544      if (v === "entry" && !inInput && isPrintableSearchKey) {545        e.preventDefault();546        primeListSearch(e.key);547        return;548      }549    };550    window.addEventListener("keydown", handleGlobalKeydown);551    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));552553    const handleStorageChanged = (554      changes: Record<string, chrome.storage.StorageChange>,555      areaName: string556    ) => {557      if (areaName !== "session") return;558      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {559        return;560      }561      void refreshPendingPasskey();562    };563564    chrome.storage.onChanged.addListener(handleStorageChanged);565    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));566  });567568  async function refreshCurrentTab() {569    try {570      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });571      const url = tab?.url ?? tab?.pendingUrl ?? "";572      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");573    } catch {574      setCurrentTabDomain("");575    }576  }577578  async function refreshPendingPasskey() {579    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });580    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);581  }582583  async function refreshProStatus() {584    const res = await sendMessage({ type: "GET_LICENSE" });585    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;586    setProStatus(Boolean(data?.valid && data?.plan === "pro"));587  }588589  async function restoreSettings() {590    const res = await sendMessage({ type: "GET_SETTINGS" });591    const s = (res as { ok: boolean; data?: any }).data ?? {};592    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {593      setAccentColor(s.accentColor as AccentColorName);594    }595    setTheme(s.theme === "light" ? "light" : "dark");596    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {597      setDisplayFont(s.displayFont);598    } else {599      setDisplayFont("cormorant-italic");600    }601    if (s.textSize === "small" || s.textSize === "large") {602      setTextSize(s.textSize);603    } else {604      setTextSize("medium");605    }606    setReduceMotion(s.reduceMotion === true);607    setLockOnClose(s.lockOnClose !== false);608    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);609    setBreachMonitoring(s.breachMonitoring !== false);610    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);611    setShortcutBindings(getActiveBindings(s.shortcuts));612  }613614  async function applyTrashRetention(days: number) {615    setTrashRetentionDays(days);616    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });617  }618619  function primeListSearch(seed: string) {620    setListSearchSeed(seed);621    setListSearchSeedNonce((value) => value + 1);622    openList();623  }624625  // Returns null when it detected a dead service worker and triggered handleLock().626  // Callers that need to abort (e.g. openVault) check for null rather than relying627  // on view() state, which may already be "lock" during normal startup flows.628  async function loadEntries(): Promise<VaultEntry[] | null> {629    const response = await sendMessage({ type: "GET_ENTRIES" });630    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };631632    // If the service worker was killed and restarted (MV3 workers sleep), the633    // vault will be locked again — or the worker may not respond at all.634    // In either case, send the user to the lock screen rather than silently635    // showing an empty vault (which looks like data loss).636    if (!res.ok) {637      if (638        res.error === "vault locked" ||639        res.error === "SERVICE_WORKER_UNAVAILABLE" ||640        (typeof res.error === "string" && res.error.includes("locked"))641      ) {642        handleLock();643        return null; // signal emergency lock to callers644      }645      return [];646    }647648    const loadedEntries = res.data ?? [];649    setEntries(loadedEntries);650651    const currentId = selectedEntry()?.id;652    if (currentId) {653      setSelectedEntry(654        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null655      );656    }657658    return loadedEntries;659  }660661  async function openVault(preferredEntryId?: string, skipViewSet = false) {662    // Purge expired trash entries on each vault open663    const retDays = trashRetentionDays();664    if (retDays > 0) {665      void sendMessage({666        type: "PURGE_EXPIRED_TRASH",667        payload: { retentionMs: retDays * 86_400_000 },668      });669    }670671    const loadedEntries = await loadEntries();672673    // null means loadEntries() triggered an emergency lock (service worker died).674    // Don't override it by setting view back to "entry" with an empty vault.675    if (loadedEntries === null) return;676677    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry678    let nextSelectedEntry: VaultEntry | null = null;679    if (preferredEntryId) {680      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;681    }682    if (!nextSelectedEntry) {683      const tabDomain = currentTabDomain();684      if (tabDomain) {685        nextSelectedEntry = loadedEntries.find((e) => {686          if (e.type === "login") {687            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;688            for (const extra of e.additionalUrls ?? []) {689              if ((extractDomain(extra) ?? "") === tabDomain) return true;690            }691            return false;692          }693          if (e.type === "passkey" && e.rpId) return e.rpId === tabDomain;694          return false;695        }) ?? null;696      }697    }698    nextSelectedEntry ??= loadedEntries[0] ?? null;699700    setSelectedEntry(nextSelectedEntry);701    setEditEntry(undefined);702    setContentTransitioning(false);703    setContentPhase("enter");704    queueContentIdle();705    if (!skipViewSet) setView("entry");706  }707708  async function handleUnlock() {709    setHasVault(true);710    triggerPipPulse();711    await restoreSettings();712    const celebrating = pendingCelebration();713    if (celebrating) {714      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });715      setPendingCelebration(false);716    }717    await openVault(undefined, celebrating);718    if (celebrating) {719      setView("pro-celebration");720      window.setTimeout(() => setView("entry"), 2500);721    }722  }723724  function handleSelectEntry(entry: VaultEntry) {725    setSelectedEntry(entry);726    setContentTransitioning(false);727    setContentPhase("enter");728    queueContentIdle();729    setView("entry");730  }731732  function handleAdd() {733    setEditEntry(undefined);734    setView("add");735  }736737  async function handleDelete() {738    const entry = selectedEntry();739    if (!entry) return;740    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });741    const loadedEntries = await loadEntries() ?? [];742    setSelectedEntry(loadedEntries[0] ?? null);743    setView("entry");744  }745746  async function handleDeleteMany(ids: string[]) {747    for (const id of ids) {748      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });749    }750    const loadedEntries = await loadEntries() ?? [];751    // If the currently selected entry was among the deleted, move to first752    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);753    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);754  }755756  async function handleSave(savedEntry?: VaultEntry) {757    await openVault(savedEntry?.id);758  }759760  function handleBack() {761    setEditEntry(undefined);762    setView("entry");763  }764765  function handleLock() {766    clearCanarySuppressions();767    setEntries([]);768    setSelectedEntry(null);769    setEditEntry(undefined);770    setContentPhase("idle");771    setView("lock");772  }773774  function handleHeaderLock() {775    // Lock the UI immediately — do not wait for the service worker. If the SW776    // is dead or slow, the 5s sendMessage timeout would create a dead-click777    // window. The SW will lock on its next wake regardless.778    handleLock();779    void sendMessage({ type: "LOCK" });780  }781782  function navigate(dir: number) {783    const allEntries = entries();784    if (allEntries.length === 0) return;785    const currentIndex = selectedIndex();786    const baseIndex = currentIndex >= 0 ? currentIndex : 0;787    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;788    setSelectedEntry(allEntries[nextIndex]);789    setContentPhase("enter");790    queueContentIdle();791  }792793  function openList() {794    setView("list");795  }796797  function openHealth() {798    setEditEntry(undefined);799    setView("health");800  }801802  function handleOpenFileImport() {803    setRestoreView("file");804  }805806  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;807808  function handleFixEntry(entry: VaultEntry) {809    if (entry.type === "passkey") {810      setSelectedEntry(entry);811      setView("entry");812      return;813    }814    setEditEntry(entry);815    setView("add");816  }817818  const isLockedView = () => view() === "lock";819  const selectedPasskeyEntry = createMemo(() =>820    selectedEntry()?.type === "passkey" ? (selectedEntry() as PasskeyEntry) : null821  );822823  async function handleApprovePendingPasskey() {824    const pending = pendingPasskey();825    if (!pending) return;826    if (pending.browser === "firefox" && pending.type === "create") {827      // Firefox path: popup itself runs navigator.credentials.create. The828      // background never approved/rejected anything — it just stashed829      // intent. After the popup-driven flow resolves (success or cancel),830      // clear the pending key so the popup doesn't re-show this on next open.831      const { createFirefoxPasskey } = await import("./firefox-passkey");832      const result = await createFirefoxPasskey(pending);833      if (!result.ok) {834        console.warn("Peach Firefox passkey create failed:", result.error);835      }836      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });837      setPendingPasskey(null);838      void loadEntries();839      return;840    }841    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });842    setPendingPasskey(null);843  }844845  async function handleDenyPendingPasskey() {846    const pending = pendingPasskey();847    if (!pending) return;848    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });849    setPendingPasskey(null);850  }851852  function queueContentIdle(after?: () => void) {853    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);854    contentPhaseTimer = window.setTimeout(() => {855      setContentPhase("idle");856      after?.();857    }, ENTRY_TRANSITION_SETTLE_MS);858  }859860  return (861    <div class="popup-root peach-theme">862      <Show when={bootState() === "ready"}>863        <Show864          when={!pendingPasskey()}865          fallback={866            <PasskeyApprovalView867              type={pendingPasskey()!.type}868              rpName={pendingPasskey()!.rpName}869              rpId={pendingPasskey()!.rpId}870              userName={pendingPasskey()!.userName}871              userDisplayName={pendingPasskey()!.userDisplayName}872              onApprove={handleApprovePendingPasskey}873              onDeny={handleDenyPendingPasskey}874            />875          }876        >877          <Show878            when={!isLockedView()}879            fallback={880              <Show881                when={onboarded() || hasVault()}882                fallback={883                  <Onboarding884                    onComplete={() => { setOnboarded(true); }}885                  />886                }887              >888                <LockView889                  hasVault={hasVault()}890                  ready={bootState() === "ready"}891                  isPro={proStatus()}892                  onUnlock={handleUnlock}893                />894              </Show>895            }896          >897            <Show898              when={view() !== "pro-celebration"}899              fallback={<ProCelebration />}900            >901            <section902              id="hd-shell"903              class="peach-shell peach-theme"904              data-surface="extension"905            >906            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>907              <PeachWordmark unlocked />908              <div class="peach-chrome-actions">909                <button910                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"911                  onClick={() => setView("settings")}912                  aria-label="Settings"913                >914                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">915                    <path916                      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"917                      stroke="currentColor"918                      stroke-width="0.9"919                    />920                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />921                  </svg>922                </button>923                <button924                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"925                  onClick={handleAdd}926                  aria-label="New entry"927                >928                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">929                    <path d="M5.5 1v9M1 5.5h9" />930                  </svg>931                </button>932                <button933                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"934                  onClick={() => void handleHeaderLock()}935                  aria-label="Lock vault"936                >937                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">938                    <path939                      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"940                      stroke="currentColor"941                      stroke-width="1"942                      stroke-linecap="round"943                    />944                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />945                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />946                  </svg>947                </button>948              </div>949            </header>950951            <Show when={pendingProNotice() !== null}>952              <div class="peach-pro-notice-banner">953                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>954                <button955                  class="peach-pro-notice-link"956                  onClick={() => {957                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);958                    setSettingsInitialSection("license");959                    setView("settings");960                    setPendingProNotice(null);961                  }}962                >963                  Learn more →964                </button>965                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>966              </div>967            </Show>968969            <div class="peach-shell-body">970              <div class="peach-shell-veil"></div>971              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>972                <Show973                  when={selectedPasskeyEntry()}974                  fallback={975                    <EntryView976                      entry={selectedEntry()}977                      onDelete={handleDelete}978                      onFieldSaved={() => void loadEntries()}979                      onEscape={() => { setView("list"); }}980                    />981                  }982                >983                  <PasskeyEntryView entry={selectedPasskeyEntry()} onDelete={handleDelete} />984                </Show>985              </div>986987              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>988                <div class="peach-search-bar">989                  <span class="peach-search-icon">990                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">991                      <circle cx="5.5" cy="5.5" r="3.75" />992                      <path d="M8.75 8.75L11.5 11.5" />993                    </svg>994                  </span>995                  <input996                    class="peach-search-input"997                    placeholder="search vault..."998                    autocomplete="off"999                    aria-label="Search vault entries"1000                    onClick={openList}1001                    onFocus={openList}1002                    readOnly1003                  />1004                  <div class="peach-search-meta">1005                    <span class="peach-search-counter">1006                      {entries().length > 01007                        ? `${selectedIndex() + 1} / ${entries().length}`1008                        : "0 entries"}1009                    </span>1010                    <span class="peach-divider"></span>1011                    <button1012                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1013                      onClick={() => navigate(-1)}1014                      aria-label="Previous entry"1015                      disabled={entries().length === 0}1016                    >1017                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1018                        <path d="M5 1L1 5.5L5 10" />1019                      </svg>1020                    </button>1021                    <button1022                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1023                      onClick={() => navigate(1)}1024                      aria-label="Next entry"1025                      disabled={entries().length === 0}1026                    >1027                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1028                        <path d="M1 1L5 5.5L1 10" />1029                      </svg>1030                    </button>1031                  </div>1032                </div>1033              </section>1034            </div>10351036            <Show when={view() === "list"}>1037              <VaultView1038                entries={entries()}1039                selectedEntryId={selectedEntry()?.id}1040                currentTabDomain={currentTabDomain()}1041                sortOrder={sortOrder()}1042                searchSeed={listSearchSeed()}1043                searchSeedNonce={listSearchSeedNonce()}1044                onSelectEntry={handleSelectEntry}1045                onSortOrderChange={setSortOrder}1046                onAdd={handleAdd}1047                onClose={() => setView("entry")}1048                onOpenTrash={() => setView("trash")}1049                onDeleteMany={handleDeleteMany}1050              />1051            </Show>1052            <Show when={view() === "settings"}>1053              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1054                <SettingsView1055                  entriesCount={entries().length}1056                  breachMonitoring={breachMonitoring()}1057                  lockOnClose={lockOnClose()}1058                  autoLockMinutes={autoLockMinutes()}1059                  trashRetentionDays={trashRetentionDays()}1060                  theme={theme()}1061                  accentColor={accentColor()}1062                  displayFont={displayFont()}1063                  textSize={textSize()}1064                  reduceMotion={reduceMotion()}1065                  isPro={proStatus()}1066                  initialSection={settingsInitialSection()}1067                  upgradeHighlight={upgradeHighlight()}1068                  onBreachMonitoringChange={applyBreachMonitoring}1069                  onLockOnCloseChange={applyLockOnClose}1070                  onAutoLockMinutesChange={applyAutoLockMinutes}1071                  onTrashRetentionChange={applyTrashRetention}1072                  onThemeChange={applyTheme}1073                  onAccentChange={applyAccentColor}1074                  onDisplayFontChange={applyDisplayFont}1075                  onTextSizeChange={applyTextSize}1076                  onReduceMotionChange={applyReduceMotion}1077                  shortcuts={shortcutBindings()}1078                  onShortcutsChange={applyShortcuts}1079                  onLicenseChange={async () => {1080                    // After activation/deactivation: refresh Pro status,1081                    // re-load entries (defensive — signal state can drift if1082                    // the SW briefly restarts during the verify+save round-trip),1083                    // and replay the Pro celebration if this is the first time1084                    // a valid Pro license is seen on this device.1085                    await refreshProStatus();1086                    void loadEntries();1087                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1088                    if ((should as { ok: boolean; data?: boolean }).data === true) {1089                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1090                      setView("pro-celebration");1091                      window.setTimeout(() => setView("settings"), 2500);1092                    }1093                  }}1094                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1095                  onImport={() => setView("import")}1096                  onExport={() => setView("export")}1097                  onBreachCheckDone={loadEntries}1098                  onOpenHealth={openHealth}1099                  onOpenFileImport={handleOpenFileImport}1100                  onOpenPanic={() => setView("panic")}1101                />1102              </Suspense>1103            </Show>1104            <Show when={view() === "add"}>1105              <AddView1106                entry={editEntry()}1107                entries={entries()}1108                onBack={handleBack}1109                onSave={handleSave}1110              />1111            </Show>1112            <Show when={view() === "import"}>1113              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1114                <ImportView onBack={handleBack} onImport={handleSave} />1115              </Suspense>1116            </Show>1117            <Show when={view() === "export"}>1118              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1119                <ExportView1120                  onBack={() => {1121                    if (returnToPanic()) {1122                      setReturnToPanic(false);1123                      setView("panic");1124                    } else {1125                      handleBack();1126                    }1127                  }}1128                />1129              </Suspense>1130            </Show>1131            <Show when={view() === "panic"}>1132              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1133                <PanicView1134                  onCancel={() => setView("settings")}1135                  onOpenExport={() => {1136                    setReturnToPanic(true);1137                    setView("export");1138                  }}1139                  onDestroyed={async () => {1140                    clearCanarySuppressions();1141                    setEntries([]);1142                    setSelectedEntry(null);1143                    setEditEntry(undefined);1144                    setHasVault(false);1145                    setOnboarded(false);1146                    setProStatus(false);1147                    setPendingPasskey(null);1148                    setUpgradeHighlight(null);1149                    setSettingsInitialSection(null);1150                    setPendingProNotice(null);1151                    setPendingCelebration(false);1152                    setReturnToPanic(false);1153                    setContentPhase("idle");1154                    setView("lock");1155                  }}1156                />1157              </Suspense>1158            </Show>1159            <Show when={view() === "health"}>1160              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1161                <HealthView1162                  entries={entries()}1163                  isPro={proStatus()}1164                  onFixEntry={handleFixEntry}1165                  onBack={() => setView("settings")}1166                  onRefresh={loadEntries}1167                />1168              </Suspense>1169            </Show>1170            <Show when={view() === "trash"}>1171              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1172                <TrashView1173                  onBack={() => setView("list")}1174                  onRestored={() => void loadEntries()}1175                />1176              </Suspense>1177            </Show>1178            <Show when={restoreView() === "file"}>1179              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1180                <ImportView1181                  mode="onboarding"1182                  replacesExistingVault={true}1183                  onBack={() => setRestoreView(null)}1184                  onImport={async () => {1185                    setRestoreView(null);1186                    await handleUnlock();1187                  }}1188                />1189              </Suspense>1190            </Show>1191            </section>1192            </Show>1193          </Show>1194        </Show>1195      </Show>1196      <Show when={showShortcutsHelp()}>1197        <ShortcutsHelpOverlay1198          bindings={shortcutBindings()}1199          onClose={() => setShowShortcutsHelp(false)}1200        />1201      </Show>1202    </div>1203  );1204}12051206function ShortcutsHelpOverlay(props: {1207  bindings: Record<ShortcutAction, Keybinding>;1208  onClose: () => void;1209}) {1210  return (1211    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1212      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1213        <div class="peach-shortcuts-help-head">1214          <h3>Keyboard shortcuts</h3>1215          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1216        </div>1217        <div class="peach-shortcuts-help-body">1218          <p class="peach-settings-sub-label">ENTRY VIEW</p>1219          <ul>1220            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1221              <li>1222                <span>{d.label}</span>1223                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1224              </li>1225            ))}1226          </ul>1227          <p class="peach-settings-sub-label">ANYWHERE</p>1228          <ul>1229            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1230              <li>1231                <span>{d.label}</span>1232                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1233              </li>1234            ))}1235          </ul>1236        </div>1237      </div>1238    </div>1239  );1240}