inject.ts

137.7 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { generatePassword } from "../shared/generate";14import { generateTOTP } from "../crypto/totp";15import { detectPasswordPolicy } from "./policy";1617let accentHex = "#E8956D";18let popupTheme: "dark" | "light" = "dark";19chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {20  const data = resp?.data;21  const name = data?.accentColor ?? "peach";22  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";23  popupTheme = data?.theme === "light" ? "light" : "dark";24});2526// 8-digit hex alpha helpers for the accent-derived shadow tokens.27// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing28// two hex digits as the alpha channel.29function withAlpha(hex: string, alpha: string): string {30  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS31  // always exposes 6-digit hex, so this is a guard against future changes32  // shipping shorthand colors that would silently break the var injection.33  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;34}3536export interface SelectorEntry {37  id: string;38  title: string;39  username?: string;40  email?: string;41  url?: string;42  hasTotp?: boolean;43  /** True when the entry also has a passkey credential attached. */44  hasPasskey?: boolean;45}4647interface SelectorOptions {48  domain?: string;49  searchableEntries?: SelectorEntry[];50  /** True when shown on a signup form — changes header label and entry-click behaviour */51  isSignup?: boolean;52  /**53   * Derived identity list (emails then usernames) for signup mode (State 10).54   * When present, renderIdentityHelper() is used instead of renderList().55   */56  savedIdentities?: SavedIdentity[];57  /**58   * Called after the user picks a saved identity (signup mode only) or59   * after successfully saving a new entry on a signup form.60   * Lets the caller fill the visible username + password fields.61   */62  onFillFields?: (username: string, password: string) => void;63  /**64   * When true, show an inline unlock form instead of the entries list.65   * Used when the vault is locked so the user can unlock without opening66   * the popup.67   */68  locked?: boolean;69  /**70   * Called after a successful inline unlock — the caller should re-query71   * entries and re-open the selector with real data.72   */73  onUnlocked?: () => void;74  /**75   * Called when the user explicitly dismisses the selector (Escape, Tab, or76   * click outside) — NOT when an entry is selected or on auto-close.77   * Used by the caller to suppress spurious reopens on the same field.78   */79  onDismiss?: () => void;80}8182function getDomainFromUrl(url: string): string {83  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }84}8586function keySvgStr(): string {87  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="rgba(240,232,216,0.35)" stroke-width="0.95" stroke-linecap="round"><rect x="2" y="5.5" width="8" height="6" rx="1.5"/><path d="M4 5.5V4.25A2 2 0 0 1 6 2.25A2 2 0 0 1 8 4.25V5.5"/></svg>`;88}8990function plusSvgStr(): string {91  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>`;92}9394function peachIconSvg(): string {95  // Peach body stays brand-peach regardless of `accentHex` — a sage or96  // sky accent must not turn the autofill icon green or blue. Accent97  // color still tints surrounding glow/hover halos below.98  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 240 240" fill="none" aria-hidden="true"><path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/><path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z" fill="#FFB082"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z" fill="#E5805C"/><ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/></svg>`;99}100101function checkSvgStr(): string {102  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="#5E7A42" stroke-width="1.5" stroke-linecap="round"><path d="M4 10.5L8 14.5L16 6.5"/></svg>`;103}104105function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {106  const { hostname, origin } = location;107  const parts = hostname.split(".");108  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",109    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",110    "oidc", "federation", "saml", "cas", "ldap"];111  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());112  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;113  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);114  return { origin, title, loginSubdomain };115}116117/**118 * Shows a bottom-of-page toast after filling credentials when the entry has119 * never matched the current site — offering to add the current origin to the120 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.121 */122export function showRememberSiteToast(123  pageDomain: string,124  entryId: string,125): void {126  const host = document.createElement("div");127  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";128  host.style.setProperty("--peach-accent", accentHex);129  const shadow = host.attachShadow({ mode: "closed" });130131  const style = document.createElement("style");132  style.textContent = `133    .bar {134      display:flex;align-items:center;gap:10px;padding:10px 14px;135      background:#131109;border:1px solid rgba(240,232,216,0.09);136      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);137      font-family:Inter,sans-serif;white-space:nowrap;138      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;139    }140    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }141    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }142    .yes {143      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;144      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;145    }146    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }147    .no {148      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;149      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;150    }151  `;152  shadow.appendChild(style);153154  const bar = document.createElement("div"); bar.className = "bar";155  const txt = document.createElement("span"); txt.className = "txt";156  txt.textContent = `Remember ${pageDomain} for this entry?`;157  const yesBtn = document.createElement("button"); yesBtn.className = "yes";158  yesBtn.textContent = "Remember";159  yesBtn.addEventListener("click", async () => {160    await chrome.runtime.sendMessage({161      type: "ADD_ADDITIONAL_URL",162      payload: { id: entryId, url: location.origin },163    });164    host.remove();165  });166  const noBtn = document.createElement("button"); noBtn.className = "no";167  noBtn.textContent = "Not now";168  noBtn.addEventListener("click", () => host.remove());169  bar.append(txt, yesBtn, noBtn);170  shadow.appendChild(bar);171  document.body.appendChild(host);172  setTimeout(() => host.remove(), 9000);173}174175interface SmartGenerator {176  root: HTMLElement;177  getPassword: () => string;178  /** Copy the current password to the clipboard with the standard pulse UX. */179  copy: () => Promise<void>;180}181182interface SmartGeneratorOptions {183  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */184  policy: PasswordPolicy;185  /**186   * Seed value: used as the displayed password without regenerating, e.g. the187   * password the user already typed into the page. The generator still188   * regenerates the moment any control changes.189   */190  initialPassword?: string;191  /** Fires every time the password regenerates (initial + on changes). */192  onChange?: (pw: string) => void;193}194195/**196 * Build the inline-popup smart-password generator. Mirrors the main popup's197 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset198 * pills + a policy hint that names the constraints Peach detected on the199 * page. Writing this in pure DOM rather than reusing the Solid component200 * keeps the content-script bundle small.201 */202function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {203  const policy = opts.policy ?? {};204205  // Start at site max (strongest password the site accepts), fall back to 64206  let length = policy.maxLength ?? 64;207  if (policy.minLength) length = Math.max(length, policy.minLength);208  if (length < 8) length = 8;209  if (length > 128) length = 128;210211  let upper = true;212  let lower = true;213  let numbers = true;214  let symbols = !policy.forbidsSymbols;215  if (policy.requiresSymbols) symbols = true;216  const forbiddenChars = policy.forbiddenChars ?? "";217218  let password = "";219220  const root = document.createElement("div");221  root.className = "pwgen-block";222223  const displayRow = root.appendChild(document.createElement("div"));224  displayRow.className = "pwgen-display-row";225  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;226  output.type = "text";227  output.className = "pwgen-output";228  output.setAttribute("autocomplete", "off");229  output.setAttribute("spellcheck", "false");230  output.setAttribute("autocorrect", "off");231  output.setAttribute("autocapitalize", "off");232233  const regenBtn = displayRow.appendChild(document.createElement("button"));234  regenBtn.className = "pwgen-icon-btn";235  regenBtn.type = "button";236  regenBtn.setAttribute("aria-label", "Regenerate password");237  regenBtn.title = "Regenerate";238  regenBtn.innerHTML = `<svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round"><path d="M11 2.5A5.5 5.5 0 1 0 12.5 7"/><path d="M9.5 2.5H11V1"/></svg>`;239240  const copyBtn = displayRow.appendChild(document.createElement("button"));241  copyBtn.className = "pwgen-icon-btn";242  copyBtn.type = "button";243  copyBtn.setAttribute("aria-label", "Copy password");244  copyBtn.title = "Copy";245  copyBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="8" height="9" rx="1.5"/><path d="M10 4V2.5A1.5 1.5 0 0 0 8.5 1h-6A1.5 1.5 0 0 0 1 2.5v7A1.5 1.5 0 0 0 2.5 11H4"/></svg>`;246247  const controls = root.appendChild(document.createElement("div"));248  controls.className = "pwgen-controls-row";249  const slider = controls.appendChild(document.createElement("input"));250  slider.type = "range";251  slider.className = "pwgen-slider";252  slider.min = "8";253  slider.max = "128";254  slider.value = String(length);255  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));256  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));257  const lenNum = controls.appendChild(document.createElement("span"));258  lenNum.className = "pwgen-len-num pwgen-len-num--edit";259  lenNum.textContent = String(length);260  lenNum.addEventListener("click", () => {261    const li = document.createElement("input");262    li.type = "text"; li.inputMode = "numeric";263    li.className = "pwgen-len-input"; li.value = String(length);264    lenNum.replaceWith(li);265    requestAnimationFrame(() => li.select());266    function commitLenEdit() {267      const n = parseInt(li.value, 10);268      if (!isNaN(n)) {269        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));270        slider.value = String(length);271        regenerate();272      }273      lenNum.textContent = String(length);274      li.replaceWith(lenNum);275    }276    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });277    li.addEventListener("blur", commitLenEdit);278  });279280  const pills = root.appendChild(document.createElement("div"));281  pills.className = "pwgen-pills";282283  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {284    const b = document.createElement("button");285    b.type = "button";286    b.className = `pwgen-pill ${on ? "is-on" : ""}`;287    b.textContent = label;288    b.addEventListener("click", () => {289      const next = !b.classList.contains("is-on");290      b.classList.toggle("is-on", next);291      onToggle(next);292    });293    return b;294  }295  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));296  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));297  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));298  pills.appendChild(makePill("!@#", symbols, (next) => {299    // The site forbids symbols — UI lets the user override but still warn.300    symbols = next;301    regenerate();302  }));303304  // Policy hint — surfaces what Peach read off the site so the user knows the305  // generator is already tuned to it. Only shows when something interesting306  // was detected.307  const hintParts: string[] = [];308  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);309  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);310  if (policy.requiresSymbols) hintParts.push("requires symbols");311  if (policy.forbidsSymbols) hintParts.push("no symbols");312  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);313  if (hintParts.length > 0) {314    const hint = root.appendChild(document.createElement("div"));315    hint.className = "pwgen-policy-hint";316    const accent = document.createElement("span");317    accent.className = "pwgen-hint-accent";318    accent.textContent = "site rules · ";319    const text = document.createTextNode(hintParts.join(" · "));320    hint.appendChild(accent);321    hint.appendChild(text);322  }323324  function regenerate() {325    // Falls back gracefully when the user toggles every charset off — the326    // shared generator forces lowercase in that case rather than throwing.327    password = generatePassword({328      length,329      includeUppercase: upper,330      includeLowercase: lower,331      includeNumbers: numbers,332      includeSymbols: symbols,333      forbiddenChars,334    });335    output.value = password;336    opts.onChange?.(password);337  }338339  output.addEventListener("input", () => {340    password = output.value;341    length = password.length;342    slider.value = String(Math.max(8, Math.min(128, length)));343    lenNum.textContent = String(length);344    opts.onChange?.(password);345  });346347  slider.addEventListener("input", () => {348    length = parseInt(slider.value, 10);349    lenNum.textContent = String(length);350    regenerate();351  });352  regenBtn.addEventListener("click", regenerate);353354  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;355  async function copy(): Promise<void> {356    try {357      await navigator.clipboard.writeText(password);358      copyBtn.classList.add("is-copied");359      if (copyResetTimer) clearTimeout(copyResetTimer);360      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);361    } catch {362      // Clipboard API may be denied — silently no-op; user still has regen UI.363    }364  }365  copyBtn.addEventListener("click", () => { void copy(); });366367  if (opts.initialPassword) {368    password = opts.initialPassword;369    output.value = password;370    opts.onChange?.(password);371  } else {372    regenerate();373  }374375  return {376    root,377    getPassword: () => password,378    copy,379  };380}381382export function observeAnchorPosition(383  anchorEl: HTMLElement,384  onUpdate: () => void385): () => void {386  let rafId = 0;387  let burstUntil = 0;388389  const runUpdate = () => {390    rafId = 0;391    onUpdate();392    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);393  };394  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };395  const scheduleBurst = (ms = 220) => {396    burstUntil = Math.max(burstUntil, performance.now() + ms);397    scheduleUpdate();398  };399400  const resizeObserver = new ResizeObserver(() => scheduleBurst());401  resizeObserver.observe(anchorEl);402  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);403404  const mutationObserver = new MutationObserver(() => scheduleBurst());405  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });406  if (anchorEl.parentElement) {407    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });408  }409410  const onScroll = () => scheduleUpdate();411  window.addEventListener("scroll", onScroll, true);412  window.addEventListener("resize", onScroll);413  window.visualViewport?.addEventListener("resize", onScroll);414  window.visualViewport?.addEventListener("scroll", onScroll);415  anchorEl.addEventListener("focus", () => scheduleBurst());416  anchorEl.addEventListener("input", () => scheduleBurst());417418  scheduleBurst(260);419420  return () => {421    if (rafId) cancelAnimationFrame(rafId);422    resizeObserver.disconnect();423    mutationObserver.disconnect();424    window.removeEventListener("scroll", onScroll, true);425    window.removeEventListener("resize", onScroll);426    window.visualViewport?.removeEventListener("resize", onScroll);427    window.visualViewport?.removeEventListener("scroll", onScroll);428  };429}430431export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {432  const button = document.createElement("button");433  button.type = "button";434  button.setAttribute("aria-label", "Peach autofill");435  button.title = "Fill with Peach";436  button.innerHTML = peachIconSvg();437  // position: fixed is load-bearing — not absolute. Absolute positioning438  // inherits the nearest positioned ancestor's box, which on sites with439  // overflow:hidden or sticky parents clips or offsets the icon. Fixed440  // anchors to the viewport and escapes all parent layout.441  button.style.cssText = `442    position: fixed; z-index: 2147483646;443    width: 26px; height: 26px; cursor: pointer;444    pointer-events: auto; border: none; padding: 3px;445    display: inline-flex; align-items: center; justify-content: center;446    background: transparent; border-radius: 999px;447    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;448    opacity: 0;449  `;450  button.addEventListener("mouseenter", () => {451    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;452    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;453    button.style.transform = "scale(1.08)";454  });455  button.addEventListener("mouseleave", () => {456    button.style.background = "transparent";457    button.style.boxShadow = "none";458    button.style.transform = "none";459  });460  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });461  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });462463  document.body.appendChild(button);464465  function updatePosition() {466    const rect = field.getBoundingClientRect();467    if (rect.width === 0 || rect.height === 0) {468      button.style.opacity = "0"; button.style.pointerEvents = "none";469      return;470    }471    const sz = 26;472    const inset = Math.max(5, Math.min(10, rect.height * 0.22));473    const top = rect.top + rect.height / 2 - sz / 2;474    // Clamp left so the icon stays fully inside the field's right edge, never475    // spilling onto an adjacent sibling button.476    const minLeft = rect.left + 4;477    const left = Math.max(minLeft, rect.right - sz - inset);478    // Hide if the field is too narrow to fit the icon cleanly (< 40px)479    if (rect.width < 40) {480      button.style.opacity = "0"; button.style.pointerEvents = "none";481      return;482    }483    button.style.top = `${top}px`;484    button.style.left = `${left}px`;485    button.style.opacity = "1"; button.style.pointerEvents = "auto";486  }487  updatePosition();488  requestAnimationFrame(() => { button.style.opacity = "1"; });489  const stopObserving = observeAnchorPosition(field, updatePosition);490  return () => { stopObserving(); button.remove(); };491}492493// All theme-dependent values resolve through tokens scoped to494// .peach-inline-popup[data-theme="dark|light"]. Accent variables495// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)496// are identical in both themes — only surface tokens differ. See497// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the498// theme switch — only literal brand-peach in peachIconSvg may stay raw.499const SELECTOR_STYLES = `500  :host { all: initial; }501  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }502503  .peach-inline-popup[data-theme="dark"] {504    --peach-bg:           #1a1410;505    --peach-bg-card:      #221c16;506    --peach-text:         #f5f0ea;507    --peach-text-dim:     #8a7a6a;508    --peach-text-muted:   #4a3a2a;509    --peach-border:       rgba(255,255,255,0.07);510    --peach-input-bg:     rgba(255,255,255,0.05);511    --peach-input-border: rgba(255,255,255,0.08);512  }513  .peach-inline-popup[data-theme="light"] {514    --peach-bg:           #fdf8f4;515    --peach-bg-card:      #f5ede4;516    --peach-text:         #1c1310;517    --peach-text-dim:     #6b5a4a;518    --peach-text-muted:   #a89080;519    --peach-border:       rgba(0,0,0,0.08);520    --peach-input-bg:     rgba(0,0,0,0.04);521    --peach-input-border: rgba(0,0,0,0.10);522  }523524  .peach-inline-popup {525    background: var(--peach-bg);526    border: 1px solid var(--peach-border-accent, var(--peach-border));527    border-radius: 14px;528    overflow: hidden;529    box-shadow:530      0 8px 40px var(--peach-glow, transparent),531      0 2px 12px rgba(0,0,0,0.5);532    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;533    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;534    transition: height 220ms cubic-bezier(0.16,1,0.3,1);535  }536  /* Light theme: shadow against a light page is too strong otherwise — drop both537     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */538  .peach-inline-popup[data-theme="light"] {539    box-shadow:540      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),541      0 2px 12px rgba(0,0,0,0.12);542  }543  .peach-inline-popup.is-exiting {544    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;545    pointer-events: none;546  }547548  @keyframes peach-enter {549    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }550    65%  { opacity: 1; filter: blur(0); }551    100% { opacity: 1; transform: translateY(0) scale(1); }552  }553  @keyframes peach-exit {554    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }555    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }556  }557  @keyframes peach-slide-in {558    from { opacity: 0; transform: translateX(12px); }559    to   { opacity: 1; transform: translateX(0); }560  }561  @keyframes peach-slide-back {562    from { opacity: 0; transform: translateX(-12px); }563    to   { opacity: 1; transform: translateX(0); }564  }565  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }566  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }567568  /* Domain header */569  .domain-header {570    padding: 9px 13px 7px;571    border-bottom: 1px solid var(--peach-border);572    display: flex; align-items: center; justify-content: space-between;573    gap: 8px;574  }575  .domain-header-text {576    display: flex; flex-direction: column; gap: 2px;577    min-width: 0; flex: 1;578  }579  .domain-eyebrow {580    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;581    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;582  }583  .domain-name {584    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);585    font-family: "IBM Plex Mono", monospace;586    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;587  }588  .domain-add-btn {589    flex-shrink: 0;590    width: 22px; height: 22px;591    display: inline-flex; align-items: center; justify-content: center;592    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);593    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);594    border-radius: 6px;595    color: var(--peach-accent);596    cursor: pointer; padding: 0;597    transition: background 120ms, border-color 120ms, transform 80ms;598    font-family: "IBM Plex Mono", monospace;599    font-size: 14px; line-height: 1;600  }601  .domain-add-btn:hover {602    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);603    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);604    transform: scale(1.06);605  }606  .domain-add-btn:active { transform: scale(0.96); }607608  /* Search */609  .search-wrap {610    padding: 9px 12px 7px;611    border-bottom: 1px solid var(--peach-border);612  }613  .search {614    width: 100%; background: var(--peach-input-bg);615    border: 1px solid var(--peach-input-border);616    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;617    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;618    transition: border-color 120ms, box-shadow 120ms;619  }620  .search:focus {621    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);622    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);623  }624  .search::placeholder { color: var(--peach-text-muted); }625626  /* Results */627  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }628  .results::-webkit-scrollbar { display: none; }629630  /* Entry rows */631  .entry {632    display: flex; align-items: center; padding: 8px 12px;633    cursor: pointer; border-bottom: 1px solid var(--peach-border);634    transition: background 70ms; position: relative; outline: none;635  }636  .entry:last-child { border-bottom: none; }637  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }638  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }639  .entry.focused::before {640    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;641    width: 2px; border-radius: 2px;642    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);643  }644645  .entry-icon {646    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;647    background: var(--peach-input-bg); border: 1px solid var(--peach-border);648    display: flex; align-items: center; justify-content: center;649    overflow: hidden; margin-right: 10px;650  }651  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }652  .entry-icon.is-new {653    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);654    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);655    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);656  }657658  .entry-info { flex: 1; min-width: 0; }659  .entry-title {660    font-size: 12.5px; color: var(--peach-text);661    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;662    line-height: 1.3;663  }664  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }665  .entry-sub {666    font-size: 10px; color: var(--peach-text-dim);667    font-family: "IBM Plex Mono", monospace;668    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;669    margin-top: 1px;670  }671672  .totp-badge {673    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;674    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);675    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);676    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;677  }678  .passkey-badge {679    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;680    border-radius: 4px;681    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);682    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);683    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);684    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;685  }686687  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }688689  .empty-hint {690    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);691    font-family: "IBM Plex Mono", monospace;692  }693694  /* Create form */695  .create-form-wrap {696    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;697  }698  .create-head {699    display: flex; align-items: center; gap: 8px;700    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);701  }702  .back-btn {703    background: transparent; border: none; cursor: pointer;704    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;705    display: flex; align-items: center; line-height: 0;706    transition: color 100ms, background 100ms;707  }708  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }709  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }710  /* minmax(0, 1fr) caps the grid track at the popup width — without it,711     long monospace content (e.g. a 60-char generated password) would712     auto-size the track wider than the popup and overflow the right edge. */713  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }714  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }715  .f-label {716    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;717    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;718  }719  .f-input {720    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);721    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;722    font-size: 11px; font-family: "IBM Plex Mono", monospace;723    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;724  }725  .f-input:focus { border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent); }726  .f-input::placeholder { color: var(--peach-text-muted); }727  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }728  .f-row { display: flex; gap: 6px; }729  .f-row .f-input { flex: 1; min-width: 0; }730  .gen-btn {731    padding: 0 10px; border-radius: 7px; border: none;732    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);733    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);734    font-size: 10px; font-family: "IBM Plex Mono", monospace;735    cursor: pointer; white-space: nowrap; flex-shrink: 0;736    display: flex; align-items: center; gap: 4px;737    transition: background 100ms;738  }739  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }740  .gen-toggle-link {741    background: none; border: none; padding: 2px 0;742    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);743    font-size: 10px; font-family: "IBM Plex Mono", monospace;744    cursor: pointer; text-align: left; transition: color 100ms;745  }746  .gen-toggle-link:hover { color: var(--peach-accent); }747  .save-btn {748    width: 100%; padding: 8px; border-radius: 8px; border: none;749    background: var(--peach-accent); color: #fff; font-size: 12px;750    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;751    transition: background 120ms, box-shadow 120ms, transform 80ms;752    letter-spacing: 0.01em;753  }754  .save-btn:hover {755    background: color-mix(in srgb, var(--peach-accent) 82%, #000);756    box-shadow: 0 4px 20px var(--peach-glow, transparent);757  }758  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }759  .url-hint {760    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);761    font-family: "IBM Plex Mono", monospace; font-style: italic;762  }763764  /* Success */765  .success-wrap {766    display: flex; flex-direction: column; align-items: center;767    padding: 24px 16px 20px; gap: 8px;768    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;769  }770  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }771  .success-ring {772    width: 40px; height: 40px; border-radius: 50%;773    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);774    display: flex; align-items: center; justify-content: center;775  }776  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }777  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }778779  /* Silver platter (State 1 — single match) */780  .silver-platter {781    padding: 14px 14px 12px;782    display: flex; flex-direction: column; gap: 6px;783  }784  .sp-title {785    font-size: 14px; font-weight: 500; color: var(--peach-text);786    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;787    line-height: 1.25;788  }789  .sp-identity-row {790    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;791  }792  .sp-identity-label {793    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;794    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;795  }796  .sp-username {797    font-size: 12px; color: var(--peach-text-dim);798    font-family: "IBM Plex Mono", monospace;799    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;800    margin-bottom: 0;801  }802  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }803  .sp-fill-btn {804    width: 100%; padding: 11px; border-radius: 9px; border: none;805    background: var(--peach-accent); color: #fff;806    font-size: 13px; font-weight: 500; cursor: pointer;807    font-family: Inter, sans-serif; letter-spacing: 0.01em;808    display: flex; align-items: center; justify-content: center; min-height: 38px;809    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;810  }811  .sp-fill-btn:hover {812    filter: brightness(1.1);813    box-shadow: 0 4px 20px var(--peach-glow, transparent);814    transform: translateY(-1px);815  }816  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }817  .sp-fill-btn.filled {818    background: #16a34a; transform: none; filter: none;819    box-shadow: 0 4px 16px rgba(22,163,74,0.35);820    cursor: default;821  }822  .sp-fill-btn:disabled { cursor: default; }823  .sp-actions {824    display: flex; gap: 4px; justify-content: space-between; align-items: center;825    margin-top: 4px;826  }827  .sp-action-btn {828    flex: 1; height: 28px; border: none; border-radius: 6px;829    background: transparent; color: var(--peach-text-dim);830    font-size: 12px; cursor: pointer;831    transition: background 120ms ease, color 120ms ease;832    font-family: Inter, sans-serif; letter-spacing: 0.04em;833    display: inline-flex; align-items: center; justify-content: center; gap: 4px;834    white-space: nowrap; overflow: hidden;835  }836  .sp-action-btn:hover:not(:disabled) {837    background: color-mix(in srgb, var(--peach-text) 5%, transparent);838    color: var(--peach-text);839  }840  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }841  .sp-action-btn.flashed {842    color: var(--peach-accent);843    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);844  }845846  /* TOTP tray — shown below the silver-platter secondary actions */847  .sp-tray {848    margin-top: 8px;849    padding: 10px 12px;850    border-radius: 9px;851    background: var(--peach-input-bg);852    border: 1px solid var(--peach-input-border);853    display: flex; align-items: center; gap: 12px;854    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;855  }856  .sp-tray-label {857    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;858    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;859    flex-shrink: 0;860  }861  .sp-totp-code {862    font-size: 18px; font-weight: 500;863    color: var(--peach-text);864    font-family: "IBM Plex Mono", monospace;865    letter-spacing: 0.12em;866    flex: 1;867    text-align: center;868  }869  .sp-totp-ring {870    width: 22px; height: 22px; flex-shrink: 0;871  }872  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }873  .sp-totp-ring .ring-fill {874    stroke: var(--peach-accent);875    transition: stroke-dashoffset 1s linear;876    transform: rotate(-90deg);877    transform-origin: center;878  }879  .sp-totp-copy {880    background: transparent; border: none; cursor: pointer;881    padding: 4px 8px; border-radius: 5px;882    color: var(--peach-text-dim); font-size: 11px;883    font-family: Inter, sans-serif;884    transition: background 120ms, color 120ms;885  }886  .sp-totp-copy:hover {887    background: color-mix(in srgb, var(--peach-text) 5%, transparent);888    color: var(--peach-text);889  }890891  /* Card silver platter (State 7) — reuses .sp-* primary action classes */892  .card-platter {893    padding: 12px 14px 10px;894    display: flex; flex-direction: column; gap: 4px;895  }896  .cp-network {897    font-size: 10px; font-weight: 600;898    color: var(--peach-accent);899    letter-spacing: 0.08em; text-transform: uppercase;900    font-family: Inter, sans-serif;901  }902  .cp-nickname {903    font-size: 14px; font-weight: 500; color: var(--peach-text);904    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;905    line-height: 1.2;906  }907  .cp-last4 {908    font-size: 12px; color: var(--peach-text-dim);909    font-family: "IBM Plex Mono", monospace;910    letter-spacing: 0.04em;911    margin-top: 2px;912  }913  .cp-meta {914    font-size: 11px; color: var(--peach-text-dim);915    font-family: "IBM Plex Mono", monospace;916    margin-top: 2px;917    display: flex; gap: 10px; align-items: center;918  }919  .cp-meta-sep { opacity: 0.5; }920  .cp-fill-wrap { margin-top: 10px; }921922  /* Locked state */923  .locked-wrap {924    display: flex; flex-direction: column; align-items: stretch;925    padding: 14px 13px 13px; gap: 9px;926  }927  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }928  .locked-icon {929    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;930    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);931    display: flex; align-items: center; justify-content: center;932  }933  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }934  .locked-input {935    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);936    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;937    font-size: 11px; font-family: "IBM Plex Mono", monospace;938    outline: none; transition: border-color 120ms, box-shadow 120ms;939  }940  .locked-input:focus { border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent); }941  .locked-input::placeholder { color: var(--peach-text-muted); }942  .locked-btn {943    width: 100%; padding: 8px; border-radius: 8px; border: none;944    background: var(--peach-accent); color: #fff; font-size: 12px;945    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;946    transition: background 120ms;947    letter-spacing: 0.01em;948    box-shadow: 0 2px 16px var(--peach-glow, transparent);949    animation: peach-pulse-glow 2.4s ease-in-out infinite;950  }951  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }952  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }953  .locked-error {954    font-size: 10px; color: rgba(220,80,60,0.85);955    font-family: "IBM Plex Mono", monospace;956  }957958  @keyframes peach-pulse-glow {959    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }960    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),961                            0 0 48px var(--peach-glow, transparent); }962  }963964  /* ── State 10: identity helper ─────────────────────────────── */965  .identity-list {966    max-height: 192px; overflow-y: auto; padding: 4px 0;967    scrollbar-width: none;968  }969  .identity-list::-webkit-scrollbar { display: none; }970  .peach-identity-row {971    display: flex; align-items: center; gap: 10px;972    padding: 9px 12px; cursor: pointer; border-radius: 8px;973    transition: background 100ms ease;974  }975  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }976  .peach-identity-value {977    font-family: "IBM Plex Mono", monospace; font-size: 13px;978    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;979  }980  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }981  .identity-alt-row {982    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;983    border-radius: 8px; transition: background 100ms ease;984    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;985  }986  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }987  .identity-escape-row {988    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;989    border-radius: 8px; transition: background 100ms ease; outline: none;990    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;991    margin-top: 2px;992  }993  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }994  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }995  .identity-alt-input-wrap.open { display: flex; }996  .identity-alt-input {997    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;998    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);999    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1000    outline: none; transition: border-color 120ms;1001  }1002  .identity-alt-input:focus {1003    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1004    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1005  }1006  .identity-alt-confirm {1007    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1008    background: var(--peach-accent); color: #fff; font-size: 12px;1009    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1010  }1011  /* ── Generator view (after identity picked) ────────────────── */1012  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1013  .gen-confirmed {1014    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1015    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1016    border-radius: 8px;1017  }1018  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1019  .gen-confirmed-val {1020    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1021    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1022  }1023  .gen-label {1024    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1025    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1026  }1027  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1028  .gen-pw-val {1029    flex: 1; padding: 8px 10px; border-radius: 7px;1030    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1031    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1032    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1033  }1034  .gen-regen-btn {1035    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1036    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1037    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1038    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1039  }1040  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1041  .gen-fill-btn {1042    padding: 10px; border-radius: 8px; border: none;1043    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1044    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1045    transition: filter 120ms ease, transform 80ms ease;1046  }1047  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1048  .gen-fill-btn:active { transform: translateY(0); }10491050  /* ── Smart password generator (parity with main UI compact mode) ─── */1051  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1052  .pwgen-display-row {1053    display: flex; align-items: center; gap: 6px;1054    padding: 8px 10px; border-radius: 7px;1055    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1056  }1057  .pwgen-output {1058    flex: 1; min-width: 0; width: 0;1059    font-family: "IBM Plex Mono", monospace; font-size: 12px;1060    color: var(--peach-text);1061    background: transparent; border: none; outline: none; padding: 0;1062  }1063  .pwgen-icon-btn {1064    flex-shrink: 0;1065    width: 26px; height: 26px;1066    display: inline-flex; align-items: center; justify-content: center;1067    background: transparent; border: 1px solid var(--peach-input-border);1068    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1069    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1070  }1071  .pwgen-icon-btn:hover {1072    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1073    color: var(--peach-accent);1074    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1075  }1076  .pwgen-icon-btn.is-copied {1077    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1078    color: var(--peach-accent);1079    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1080  }1081  .pwgen-controls-row {1082    display: flex; align-items: center; gap: 8px;1083    flex-wrap: wrap;1084  }1085  .pwgen-slider {1086    flex: 1; min-width: 110px;1087    accent-color: var(--peach-accent);1088    cursor: pointer; height: 2px; background: transparent;1089  }1090  .pwgen-len-num {1091    font-family: "IBM Plex Mono", monospace; font-size: 11px;1092    color: var(--peach-accent); min-width: 22px; text-align: right;1093  }1094  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1095  .pwgen-len-input {1096    font-family: "IBM Plex Mono", monospace; font-size: 11px;1097    color: var(--peach-accent); width: 28px; text-align: right;1098    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1099    outline: none; padding: 0; min-width: 22px;1100  }1101  @keyframes identity-suggest-in {1102    from { opacity: 0; transform: translateY(-4px); }1103    to   { opacity: 1; transform: none; }1104  }1105  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1106    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1107  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1108  .identity-collapse-btn {1109    margin-left: auto; background: transparent; border: none; cursor: pointer;1110    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1111    line-height: 0; border-radius: 3px;1112    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1113  }1114  .identity-collapse-btn:hover { color: var(--peach-text); }1115  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1116  .identity-rows { display: grid; grid-template-rows: 1fr;1117    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1118  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1119  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1120    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1121    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1122    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1123  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1124  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1125  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1126  .identity-filter-pill {1127    padding: 2px 7px; border-radius: 999px;1128    border: 1px solid var(--peach-input-border);1129    background: transparent; color: var(--peach-text-muted);1130    font-family: "IBM Plex Mono", monospace; font-size: 9px;1131    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1132  }1133  .identity-filter-pill.is-on {1134    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1135    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1136    color: var(--peach-accent);1137  }1138  .identity-suggest-row {1139    display: flex; align-items: center; gap: 5px;1140    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1141    background: transparent; cursor: pointer; text-align: left;1142    transition: background 80ms;1143  }1144  .identity-suggest-row:hover,1145  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1146  .identity-suggest-val {1147    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1148    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1149  }1150  .identity-suggest-type {1151    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1152    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1153  }1154  .identity-suggest-type--email {1155    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1156    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1157  }1158  .identity-suggest-type--username {1159    color: var(--peach-text-muted);1160    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1161  }1162  .identity-suggest-meta {1163    font-family: "IBM Plex Mono", monospace; font-size: 9px;1164    color: var(--peach-text-muted); flex-shrink: 0;1165  }1166  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1167  .pwgen-pill {1168    padding: 3px 8px; border-radius: 999px;1169    border: 1px solid var(--peach-input-border);1170    background: transparent; color: var(--peach-text-muted);1171    font-family: "IBM Plex Mono", monospace; font-size: 9px;1172    letter-spacing: 0.06em; cursor: pointer;1173    transition: all 130ms ease;1174  }1175  .pwgen-pill.is-on {1176    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1177    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1178    color: var(--peach-accent);1179  }1180  .pwgen-pill:not(.is-on):hover {1181    color: var(--peach-text-dim);1182    border-color: var(--peach-text-muted);1183  }1184  .pwgen-policy-hint {1185    font-size: 10px; color: var(--peach-text-muted);1186    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1187    line-height: 1.3;1188  }1189  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11901191  /* ── Save offer (after password filled) ───────────────────── */1192  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1193  .save-offer-title {1194    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1195  }1196  .save-offer-row {1197    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1198    border-radius: 7px; background: var(--peach-input-bg);1199    border: 1px solid var(--peach-input-border);1200  }1201  .save-offer-lbl {1202    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1203    font-family: "IBM Plex Mono", monospace;1204  }1205  .save-offer-val {1206    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1207    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1208  }1209  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1210  .save-offer-save {1211    flex: 1; padding: 9px; border-radius: 8px; border: none;1212    background: var(--peach-accent); color: #fff; font-size: 13px;1213    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1214  }1215  .save-offer-save:hover { filter: brightness(1.08); }1216  .save-offer-skip {1217    flex: 1; padding: 9px; border-radius: 8px; border: none;1218    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1219    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1220    font-family: Inter, sans-serif; transition: background 100ms ease;1221  }1222  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1223`;12241225export function showAutofillSelector(1226  anchorEl: HTMLInputElement,1227  entries: SelectorEntry[],1228  onSelect: (id: string) => void,1229  options: SelectorOptions = {}1230): () => void {1231  const host = document.createElement("div");1232  host.style.cssText = "position: absolute; z-index: 2147483647;";1233  host.style.setProperty("--peach-accent", accentHex);1234  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1235  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1236  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1237  const shadow = host.attachShadow({ mode: "closed" });12381239  const style = shadow.appendChild(document.createElement("style"));1240  style.textContent = SELECTOR_STYLES;12411242  const rect = anchorEl.getBoundingClientRect();1243  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1244  host.style.left = `${rect.left + window.scrollX}px`;1245  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1246  // wide single-input fields (e.g. centered email input on signup pages).1247  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1248  // expand the host after the initial measurement.1249  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1250  host.style.width = `${popupWidth}px`;12511252  const container = shadow.appendChild(document.createElement("div"));1253  container.className = "peach-inline-popup";1254  container.setAttribute("data-theme", popupTheme);12551256  const searchableEntries = options.searchableEntries ?? [];1257  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12581259  let query = "";1260  let focusedIndex = -1;1261  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1262  let searchInput: HTMLInputElement | null = null;1263  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1264  // setInterval. Add to this list — don't fan out the dismiss function.1265  const cleanupHooks: Array<() => void> = [];12661267  // Smooth height transitions whenever content changes height.1268  // ResizeObserver fires on natural height changes; we freeze the old height,1269  // then animate to the new one so the surface never jumps.1270  {1271    let prevH = 0;1272    let blocked = false;1273    const heightRo = new ResizeObserver(([entry]) => {1274      if (blocked) return;1275      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1276      if (prevH > 0 && Math.abs(h - prevH) > 1) {1277        blocked = true;1278        container.style.height = `${prevH}px`;1279        requestAnimationFrame(() => requestAnimationFrame(() => {1280          container.style.height = `${h}px`;1281          prevH = h;1282          const onEnd = (e: TransitionEvent) => {1283            if (e.propertyName !== "height") return;1284            container.style.height = "";1285            blocked = false;1286            container.removeEventListener("transitionend", onEnd);1287          };1288          container.addEventListener("transitionend", onEnd);1289        }));1290      } else {1291        prevH = h;1292      }1293    });1294    heightRo.observe(container);1295    cleanupHooks.push(() => heightRo.disconnect());1296  }12971298  // Pre-capture the anchor field value for username prefill1299  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1300  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1301  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13021303  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1304    const seen = new Set<string>();1305    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1306  }13071308  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1309    const q = value.trim().toLowerCase();1310    const deduped = uniqueEntries(source);1311    if (!q) return deduped.slice(0, 8);1312    return deduped.filter(e =>1313      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1314    ).slice(0, 12);1315  }13161317  function activeEntries(): SelectorEntry[] {1318    // When user is typing a search, filter across all known entries (domain matches + vault)1319    if (query.trim()) {1320      const merged = uniqueEntries([...entries, ...searchableEntries]);1321      return filterEntries(merged, query);1322    }1323    // Default: show domain matches; fall back to vault search when no matches1324    if (entries.length > 0) return entries;1325    return filterEntries(searchableEntries, "").slice(0, 8);1326  }13271328  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1329    const icon = document.createElement("div");1330    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1331    if (isNew) {1332      icon.innerHTML = plusSvgStr();1333    } else {1334      // Use the generic key glyph for all entries in the page-injected selector.1335      // Avoids disclosing vault domains to any third party and avoids needing1336      // to expose the browser favicon API to page context via web_accessible_resources.1337      void url;1338      icon.innerHTML = keySvgStr();1339    }1340    return icon;1341  }13421343  function renderIdentityHelper() {1344    container.innerHTML = "";1345    const identities = options.savedIdentities ?? [];13461347    // Header: "NEW ACCOUNT" + domain name1348    const hdr = container.appendChild(document.createElement("div"));1349    hdr.className = "domain-header";1350    const eyebrow = hdr.appendChild(document.createElement("div"));1351    eyebrow.className = "domain-eyebrow";1352    eyebrow.textContent = "NEW ACCOUNT";1353    const domName = hdr.appendChild(document.createElement("div"));1354    domName.className = "domain-name";1355    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13561357    // Identity rows1358    const list = container.appendChild(document.createElement("div"));1359    list.className = "identity-list";1360    for (const id of identities) {1361      const row = list.appendChild(document.createElement("div"));1362      row.className = "peach-identity-row";1363      row.setAttribute("tabindex", "-1");1364      const val = row.appendChild(document.createElement("div"));1365      val.className = "peach-identity-value";1366      val.textContent = id.value;1367      const meta = row.appendChild(document.createElement("div"));1368      meta.className = "peach-identity-meta";1369      meta.textContent = `used ${id.useCount}×`;1370      row.addEventListener("click", () => {1371        options.onFillFields?.(id.value, "");1372        renderGenerator(id.value);1373      });1374    }13751376    // Divider before "Use a different email…"1377    if (identities.length > 0) {1378      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1379    }13801381    // "Use a different email…" expandable row1382    const altRow = container.appendChild(document.createElement("div"));1383    altRow.className = "identity-alt-row";1384    altRow.textContent = "+ Use a different email…";13851386    const altInputWrap = container.appendChild(document.createElement("div"));1387    altInputWrap.className = "identity-alt-input-wrap";1388    const altInput = altInputWrap.appendChild(document.createElement("input"));1389    altInput.className = "identity-alt-input";1390    altInput.type = "email";1391    altInput.placeholder = "[email protected]";1392    altInput.setAttribute("autocomplete", "off");1393    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1394    altConfirm.className = "identity-alt-confirm";1395    altConfirm.type = "button";1396    altConfirm.textContent = "✓";13971398    function fillCustomEmail() {1399      const v = altInput.value.trim();1400      if (!v) return;1401      options.onFillFields?.(v, "");1402      renderGenerator(v);1403    }14041405    altRow.addEventListener("click", () => {1406      altRow.style.display = "none";1407      altInputWrap.classList.add("open");1408      altInput.focus();1409    });1410    altConfirm.addEventListener("click", fillCustomEmail);1411    altInput.addEventListener("keydown", (e) => {1412      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1413    });14141415    // Escape hatch: user already has a vault entry for this site but it1416    // wasn't detected (different domain, old entry, etc.). Tapping this1417    // switches to the full searchable list so they can find and fill it;1418    // selecting an entry there will trigger the remember-site toast if1419    // the domain isn't already associated.1420    if ((options.searchableEntries?.length ?? 0) > 0) {1421      const escapeRow = container.appendChild(document.createElement("div"));1422      escapeRow.className = "identity-escape-row";1423      escapeRow.textContent = "I already have an account →";1424      escapeRow.setAttribute("tabindex", "0");1425      escapeRow.addEventListener("click", () => renderList());1426      escapeRow.addEventListener("keydown", (e) => {1427        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1428      });1429    }1430  }14311432  function renderGenerator(filledEmail: string) {1433    container.innerHTML = "";1434    const sitePolicy = detectPasswordPolicy();14351436    const wrap = container.appendChild(document.createElement("div"));1437    wrap.className = "gen-view";14381439    // Header: domain + NEW ACCOUNT1440    const hdrRow = wrap.appendChild(document.createElement("div"));1441    hdrRow.className = "domain-header";1442    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1443    eyebrow2.className = "domain-eyebrow";1444    eyebrow2.textContent = "NEW ACCOUNT";1445    const domName2 = hdrRow.appendChild(document.createElement("div"));1446    domName2.className = "domain-name";1447    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14481449    // Confirmed email row1450    const conf = wrap.appendChild(document.createElement("div"));1451    conf.className = "gen-confirmed";1452    const confCheck = conf.appendChild(document.createElement("span"));1453    confCheck.className = "gen-confirmed-check";1454    confCheck.textContent = "✓";1455    const confVal = conf.appendChild(document.createElement("div"));1456    confVal.className = "gen-confirmed-val";1457    confVal.textContent = filledEmail;14581459    const lbl = wrap.appendChild(document.createElement("div"));1460    lbl.className = "gen-label";1461    lbl.textContent = "Generate a password";14621463    let currentPw = "";1464    const smartGen = createSmartGenerator({1465      policy: sitePolicy,1466      onChange: (pw) => { currentPw = pw; },1467    });1468    wrap.appendChild(smartGen.root);14691470    const fillBtn = wrap.appendChild(document.createElement("button"));1471    fillBtn.className = "gen-fill-btn";1472    fillBtn.type = "button";1473    fillBtn.textContent = "Copy & fill";1474    fillBtn.addEventListener("click", () => {1475      if (!currentPw) return;1476      options.onFillFields?.("", currentPw);1477      renderSaveOffer(filledEmail, currentPw);1478    });1479  }14801481  function renderSaveOffer(filledEmail: string, filledPassword: string) {1482    container.innerHTML = "";1483    const domain = options.domain ?? location.hostname.replace(/^www\./, "");14841485    const wrap = container.appendChild(document.createElement("div"));1486    wrap.className = "save-offer";14871488    const title = wrap.appendChild(document.createElement("div"));1489    title.className = "save-offer-title";1490    title.textContent = "Save this login to Peach?";14911492    function detailRow(label: string, value: string) {1493      const row = wrap.appendChild(document.createElement("div"));1494      row.className = "save-offer-row";1495      const lbl = row.appendChild(document.createElement("div"));1496      lbl.className = "save-offer-lbl";1497      lbl.textContent = label;1498      const val = row.appendChild(document.createElement("div"));1499      val.className = "save-offer-val";1500      val.textContent = value;1501    }15021503    detailRow("site", domain);1504    detailRow("email", filledEmail);1505    detailRow("password", "••••••••••••••••");15061507    const btns = wrap.appendChild(document.createElement("div"));1508    btns.className = "save-offer-btns";15091510    const saveBtn = btns.appendChild(document.createElement("button"));1511    saveBtn.className = "save-offer-save";1512    saveBtn.type = "button";1513    saveBtn.textContent = "Save";1514    saveBtn.addEventListener("click", async () => {1515      saveBtn.disabled = true;1516      saveBtn.textContent = "Saving…";1517      try {1518        const res = await chrome.runtime.sendMessage({1519          type: "ADD_ENTRY",1520          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1521        });1522        if ((res as { ok?: boolean }).ok) {1523          showSuccess(sTitle);1524        } else {1525          saveBtn.disabled = false;1526          saveBtn.textContent = "Save";1527        }1528      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1529    });15301531    const skipBtn = btns.appendChild(document.createElement("button"));1532    skipBtn.className = "save-offer-skip";1533    skipBtn.type = "button";1534    skipBtn.textContent = "Not now";1535    skipBtn.addEventListener("click", () => { dismiss(true); });1536  }15371538  function renderList() {1539    container.innerHTML = "";1540    focusedIndex = -1;1541    searchInput = null;15421543    const current = activeEntries();15441545    // Domain header (always show) — eyebrow + domain on the left,1546    // a "+" shortcut to the create form on the right so the user is never1547    // trapped in the search list when they want to make a new entry.1548    const domHdr = document.createElement("div");1549    domHdr.className = "domain-header";1550    const headText = document.createElement("div");1551    headText.className = "domain-header-text";1552    const eyebrow = document.createElement("div");1553    eyebrow.className = "domain-eyebrow";1554    eyebrow.textContent = options.isSignup1555      ? "Sign up as"1556      : entries.length > 0 ? "Saved for this site" : "No saved login";1557    const domName = document.createElement("div");1558    domName.className = "domain-name";1559    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1560    headText.append(eyebrow, domName);1561    domHdr.appendChild(headText);15621563    if (!options.isSignup) {1564      const addBtn = document.createElement("button");1565      addBtn.className = "domain-add-btn";1566      addBtn.type = "button";1567      addBtn.setAttribute("aria-label", "Create new entry");1568      addBtn.title = "Create new entry";1569      addBtn.textContent = "+";1570      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1571      domHdr.appendChild(addBtn);1572    }15731574    container.appendChild(domHdr);15751576    // Search — always show so user can find entries beyond the domain matches1577    const sw = document.createElement("div"); sw.className = "search-wrap";1578    searchInput = document.createElement("input");1579    searchInput.className = "search";1580    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1581    searchInput.value = query;1582    searchInput.addEventListener("input", () => {1583      query = searchInput?.value ?? "";1584      renderList();1585      searchInput?.focus();1586      searchInput?.setSelectionRange(query.length, query.length);1587    });1588    sw.appendChild(searchInput);1589    container.appendChild(sw);15901591    // Results1592    const results = document.createElement("div");1593    results.className = "results";1594    container.appendChild(results);15951596    if (current.length === 0 && entries.length > 0) {1597      // Show a hint but don't render empty entries1598    }15991600    for (let i = 0; i < current.length; i++) {1601      const e = current[i]!;1602      const entryEl = document.createElement("div");1603      entryEl.className = "entry";1604      entryEl.dataset.id = e.id;1605      entryEl.dataset.index = String(i);1606      entryEl.setAttribute("tabindex", "-1");16071608      entryEl.appendChild(makeEntryIcon(e.url));16091610      const info = document.createElement("div"); info.className = "entry-info";1611      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1612      const subEl = document.createElement("div"); subEl.className = "entry-sub";1613      const domain = e.url ? getDomainFromUrl(e.url) : "";1614      subEl.textContent = domain || e.username || "";1615      info.append(titleEl, subEl);1616      entryEl.appendChild(info);16171618      if (e.hasTotp) {1619        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1620        entryEl.appendChild(badge);1621      }1622      if (e.hasPasskey) {1623        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1624        entryEl.appendChild(badge);1625      }16261627      entryEl.addEventListener("click", () => {1628        if (options.isSignup && options.onFillFields) {1629          // Signup mode: clicking a saved identity fills the username field1630          options.onFillFields(e.username ?? "", "");1631          dismiss();1632        } else {1633          onSelect(e.id);1634          dismiss();1635        }1636      });1637      results.appendChild(entryEl);1638    }16391640    // Divider before "New entry"1641    if (current.length > 0) {1642      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1643    }16441645    // "New entry" row — always present1646    const newEl = document.createElement("div");1647    newEl.className = "entry";1648    newEl.setAttribute("tabindex", "-1");1649    newEl.appendChild(makeEntryIcon(undefined, true));16501651    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1652    const newTitle = document.createElement("div");1653    newTitle.className = "entry-title is-new";1654    newTitle.textContent = `New entry for ${sTitle}`;1655    const newSub = document.createElement("div");1656    newSub.className = "entry-sub";1657    newSub.textContent = sOrigin;1658    newInfo.append(newTitle, newSub);1659    newEl.appendChild(newInfo);1660    newEl.addEventListener("click", showCreateForm);1661    results.appendChild(newEl);16621663    // Focus search if present1664    if (searchInput) {1665      requestAnimationFrame(() => searchInput?.focus());1666    }1667  }16681669  function setFocused(idx: number) {1670    const all = container.querySelectorAll<HTMLElement>(".entry");1671    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1672    focusedIndex = idx;1673    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1674  }16751676  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1677    const typed = identities.filter(s => s.type === fieldType);1678    if (!typed.length) return;1679    let collapsed = false;1680    let suppressNextFocus = false;16811682    const list = g.appendChild(document.createElement("div"));1683    list.className = "identity-suggest-list";1684    list.style.display = "none";16851686    // Collapse toggle — sits alone now that filter pills are gone1687    const collapseRow = list.appendChild(document.createElement("div"));1688    collapseRow.className = "identity-filter-row";1689    collapseRow.style.justifyContent = "flex-end";1690    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1691    collapseBtn.type = "button";1692    collapseBtn.className = "identity-collapse-btn";1693    collapseBtn.innerHTML = `<svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 1L5 5L9 1"/></svg>`;1694    collapseBtn.addEventListener("mousedown", (e) => {1695      e.preventDefault();1696      collapsed = !collapsed;1697      collapseBtn.classList.toggle("is-collapsed", collapsed);1698      rowsWrapper.classList.toggle("is-collapsed", collapsed);1699    });17001701    const rowsWrapper = list.appendChild(document.createElement("div"));1702    rowsWrapper.className = "identity-rows";1703    const rows = rowsWrapper.appendChild(document.createElement("div"));1704    rows.className = "identity-rows-inner";17051706    function pick(value: string) {1707      inp.value = value;1708      list.style.display = "none";1709      suppressNextFocus = true;1710      inp.focus();1711    }17121713    function render() {1714      const q = inp.value.toLowerCase();1715      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1716      rows.innerHTML = "";1717      if (!filtered.length) { list.style.display = "none"; return; }1718      for (const s of filtered) {1719        const row = rows.appendChild(document.createElement("button"));1720        row.type = "button"; row.className = "identity-suggest-row";1721        const val = row.appendChild(document.createElement("span"));1722        val.className = "identity-suggest-val"; val.textContent = s.value;1723        const meta = row.appendChild(document.createElement("span"));1724        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1725        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1726        row.addEventListener("keydown", (e) => {1727          if (e.key === "ArrowDown") {1728            e.preventDefault();1729            (row.nextElementSibling as HTMLElement | null)?.focus();1730          } else if (e.key === "ArrowUp") {1731            e.preventDefault();1732            const prev = row.previousElementSibling as HTMLElement | null;1733            if (prev) prev.focus();1734            else inp.focus();1735          } else if (e.key === "Enter" || e.key === " ") {1736            e.preventDefault();1737            pick(s.value);1738          } else if (e.key === "Escape") {1739            e.preventDefault();1740            list.style.display = "none";1741            suppressNextFocus = true;1742            inp.focus();1743          }1744        });1745        row.addEventListener("blur", (e) => {1746          const rt = (e as FocusEvent).relatedTarget as Node | null;1747          if (rt && (rt === inp || list.contains(rt))) return;1748          setTimeout(() => { list.style.display = "none"; }, 150);1749        });1750      }1751      list.style.display = "";1752    }17531754    inp.addEventListener("focus", () => {1755      if (suppressNextFocus) { suppressNextFocus = false; return; }1756      render();1757    });1758    inp.addEventListener("input", render);1759    inp.addEventListener("keydown", (e) => {1760      if (list.style.display === "none") return;1761      if (e.key === "ArrowDown" && !collapsed) {1762        e.preventDefault();1763        (rows.firstElementChild as HTMLElement | null)?.focus();1764      } else if (e.key === "Escape") {1765        e.preventDefault();1766        list.style.display = "none";1767      }1768    });1769    inp.addEventListener("blur", (e) => {1770      const rt = (e as FocusEvent).relatedTarget as Node | null;1771      if (rt && list.contains(rt)) return;1772      setTimeout(() => { list.style.display = "none"; }, 150);1773    });1774  }17751776  async function showCreateForm() {1777    currentMode = "create";1778    container.innerHTML = "";17791780    // Guard: the service worker may lock the vault between when the selector1781    // opens and when the user clicks "New entry". Show the inline unlock form1782    // instead of silently failing on save.1783    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1784    if (!statusRes?.unlocked) {1785      renderLocked();1786      return;1787    }17881789    // Detect page password policy once for this form — reused on every1790    // regenerate click so the user always gets a compliant password.1791    const sitePolicy = detectPasswordPolicy();17921793    // Fetch identities on-demand — they're passed in signup context but not1794    // in login/search context where the user still clicks "New entry".1795    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1796    if (!formIdentities.length) {1797      try {1798        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1799        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1800      } catch { /* silent fallback */ }1801    }18021803    const wrap = document.createElement("div");1804    wrap.className = "create-form-wrap";18051806    // Header1807    const head = document.createElement("div"); head.className = "create-head";1808    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1809    backBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="7" height="12" viewBox="0 0 8 14" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1L1.5 7L6 13"/></svg>`;1810    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1811    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1812    head.append(backBtn, lbl);18131814    // Body1815    const body = document.createElement("div"); body.className = "create-body";18161817    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1818      const g = document.createElement("div"); g.className = "f-group";1819      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1820      const inp = document.createElement("input"); inp.className = "f-input";1821      g.append(l, inp); return { g, inp };1822    }18231824    // Title1825    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1826    body.appendChild(tg.g);18271828    // URL1829    const ug = fGroup("website");1830    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1831    if (loginSubdomain) {1832      const h = document.createElement("div"); h.className = "url-hint";1833      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1834    }1835    body.appendChild(ug.g);18361837    // Username — pre-fill from anchor if it doesn't look like an email1838    const xg = fGroup("username");1839    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1840    xg.inp.placeholder = "johndoe";1841    xg.inp.setAttribute("autocomplete", "off");1842    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1843    body.appendChild(xg.g);18441845    // Email — pre-fill from anchor if it looks like an email1846    const eg = fGroup("email");1847    (eg.inp as HTMLInputElement).type = "email";1848    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1849    eg.inp.placeholder = "[email protected]";1850    eg.inp.setAttribute("autocomplete", "off");1851    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1852    body.appendChild(eg.g);18531854    // Password — full smart generator with charset pills + length slider +1855    // policy hint. Mirrors the main UI's compact generator so users get the1856    // same controls inline as in the popup.1857    const pg = fGroup("password");1858    pg.inp.remove(); // smartGen provides its own display — no separate input needed1859    let currentPassword = prePassword || "";1860    const smartGen = createSmartGenerator({1861      policy: sitePolicy,1862      initialPassword: prePassword || undefined,1863      onChange: (pw) => { currentPassword = pw; },1864    });1865    pg.g.appendChild(smartGen.root);1866    body.appendChild(pg.g);18671868    // Save1869    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1870    saveBtn.textContent = "Save entry";1871    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1872    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1873    saveBtn.addEventListener("click", async () => {1874      const title = tg.inp.value.trim();1875      const pw = currentPassword.trim();1876      const username = xg.inp.value.trim();1877      const email = eg.inp.value.trim();1878      if (!title) {1879        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1880        showFormError("Entry needs a title");1881        return;1882      }1883      if (!pw) {1884        showFormError("Entry needs a password — tap regen to make one");1885        return;1886      }1887      errEl.style.display = "none";1888      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1889      try {1890        const res = await chrome.runtime.sendMessage({1891          type: "ADD_ENTRY",1892          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1893        });1894        if ((res as { ok?: boolean }).ok) {1895          // Fill the detected form. onFillFields uses whichever identity the1896          // page anchored on — the vault captures both username and email.1897          options.onFillFields?.(username || email, pw);1898          showSuccess(title);1899        } else {1900          const errMsg = (res as { error?: string }).error === "vault locked"1901            ? "Vault locked — open Peach to save"1902            : "Could not save entry";1903          showFormError(errMsg);1904          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1905        }1906      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1907    });1908    body.appendChild(saveBtn);1909    body.appendChild(errEl);19101911    wrap.append(head, body);1912    container.appendChild(wrap);1913    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1914  }19151916  function showSuccess(title: string) {1917    currentMode = "success";1918    container.innerHTML = "";1919    const wrap = document.createElement("div"); wrap.className = "success-wrap";1920    const ring = document.createElement("div"); ring.className = "success-ring";1921    ring.innerHTML = checkSvgStr();1922    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1923    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1924    wrap.append(ring, t, s);1925    container.appendChild(wrap);1926    setTimeout(() => dismiss(), 1600);1927  }19281929  function flashActionBtn(btn: HTMLButtonElement) {1930    btn.classList.add("flashed");1931    setTimeout(() => btn.classList.remove("flashed"), 700);1932  }19331934  // M3/QUA-005: when both the direct clipboard write and the background COPY1935  // fallback fail, briefly show the user that the copy did not happen.1936  function flashCopyError(btn: HTMLButtonElement) {1937    const original = btn.textContent ?? "";1938    btn.textContent = "Blocked";1939    btn.classList.add("flashed");1940    setTimeout(() => {1941      btn.classList.remove("flashed");1942      if (btn.isConnected) btn.textContent = original;1943    }, 1200);1944  }19451946  function renderSilverPlatter(entry: SelectorEntry) {1947    container.innerHTML = "";1948    searchInput = null;1949    focusedIndex = -1;1950    currentMode = "silver-platter";19511952    const domHdr = document.createElement("div");1953    domHdr.className = "domain-header";1954    const headText = document.createElement("div");1955    headText.className = "domain-header-text";1956    const eyebrow = document.createElement("div");1957    eyebrow.className = "domain-eyebrow";1958    eyebrow.textContent = "Saved for this site";1959    const domName = document.createElement("div");1960    domName.className = "domain-name";1961    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1962    headText.append(eyebrow, domName);1963    domHdr.appendChild(headText);1964    if (!options.isSignup) {1965      const addBtn = document.createElement("button");1966      addBtn.className = "domain-add-btn";1967      addBtn.type = "button";1968      addBtn.setAttribute("aria-label", "Create new entry");1969      addBtn.title = "Create new entry";1970      addBtn.textContent = "+";1971      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1972      domHdr.appendChild(addBtn);1973    }1974    container.appendChild(domHdr);19751976    const platter = document.createElement("div");1977    platter.className = "silver-platter";19781979    const titleEl = document.createElement("div");1980    titleEl.className = "sp-title";1981    titleEl.textContent = entry.title;1982    platter.appendChild(titleEl);19831984    if (entry.email) {1985      const emailEl = document.createElement("div");1986      emailEl.className = "sp-identity-row";1987      const emailLbl = document.createElement("span");1988      emailLbl.className = "sp-identity-label";1989      emailLbl.textContent = "email";1990      const emailVal = document.createElement("span");1991      emailVal.className = "sp-username";1992      emailVal.textContent = entry.email;1993      emailEl.append(emailLbl, emailVal);1994      platter.appendChild(emailEl);1995    }19961997    if (entry.username) {1998      const userEl = document.createElement("div");1999      userEl.className = "sp-identity-row";2000      const userLbl = document.createElement("span");2001      userLbl.className = "sp-identity-label";2002      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2003      const userVal = document.createElement("span");2004      userVal.className = "sp-username";2005      userVal.textContent = entry.username;2006      userEl.append(userLbl, userVal);2007      platter.appendChild(userEl);2008    }20092010    const fillBtn = document.createElement("button");2011    fillBtn.className = "sp-fill-btn";2012    fillBtn.type = "button";2013    fillBtn.textContent = "Fill credentials";2014    fillBtn.addEventListener("click", () => {2015      if (fillBtn.disabled) return;2016      fillBtn.disabled = true;2017      fillBtn.classList.add("filled");2018      fillBtn.innerHTML = checkSvgStr();2019      // Fire the fill, then exit via the standard exit animation. The fill2020      // itself is async (handled in index.ts) — by 400ms the form is filled2021      // and the popup begins its exit. Total dwell from click to host2022      // removal: 400ms + 130ms (exit animation) = 530ms.2023      onSelect(entry.id);2024      setTimeout(() => dismiss(), 400);2025    });2026    platter.appendChild(fillBtn);20272028    const actions = document.createElement("div");2029    actions.className = "sp-actions";20302031    if (entry.email) {2032      const copyEmail = document.createElement("button");2033      copyEmail.className = "sp-action-btn";2034      copyEmail.type = "button";2035      copyEmail.title = "Copy email";2036      copyEmail.textContent = "Copy email";2037      copyEmail.addEventListener("click", async (e) => {2038        e.stopPropagation();2039        let alreadyWritten = false;2040        try {2041          await navigator.clipboard.writeText(entry.email!);2042          alreadyWritten = true;2043        } catch (err) {2044          console.warn("[Peach] clipboard write denied:", err);2045        }2046        const resp = await chrome.runtime.sendMessage({2047          type: "COPY",2048          payload: { text: entry.email, label: "Email", alreadyWritten },2049        }).catch(() => null) as { ok?: boolean } | null;2050        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2051        else flashCopyError(copyEmail);2052      });2053      actions.appendChild(copyEmail);2054    }20552056    const copyU = document.createElement("button");2057    copyU.className = "sp-action-btn";2058    copyU.type = "button";2059    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";2060    copyU.title = copyULabel;2061    copyU.textContent = copyULabel;2062    copyU.disabled = !entry.username;2063    copyU.addEventListener("click", async (e) => {2064      e.stopPropagation();2065      if (!entry.username) return;2066      let alreadyWritten = false;2067      try {2068        await navigator.clipboard.writeText(entry.username);2069        alreadyWritten = true;2070      } catch (err) {2071        console.warn("[Peach] clipboard write denied:", err);2072      }2073      const resp = await chrome.runtime.sendMessage({2074        type: "COPY",2075        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2076      }).catch(() => null) as { ok?: boolean } | null;2077      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2078      else flashCopyError(copyU);2079    });2080    actions.appendChild(copyU);20812082    const copyP = document.createElement("button");2083    copyP.className = "sp-action-btn";2084    copyP.type = "button";2085    copyP.title = "Copy password";2086    copyP.textContent = "Copy password";2087    copyP.addEventListener("click", async (e) => {2088      e.stopPropagation();2089      const resp = await chrome.runtime.sendMessage({2090        type: "GET_ENTRY_FOR_FILL",2091        payload: { id: entry.id },2092      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2093      if (!resp?.ok || !resp.data?.password) return;2094      let alreadyWritten = false;2095      try {2096        await navigator.clipboard.writeText(resp.data.password);2097        alreadyWritten = true;2098      } catch (err) {2099        console.warn("[Peach] clipboard write denied:", err);2100      }2101      const copyResp = await chrome.runtime.sendMessage({2102        type: "COPY",2103        payload: { text: resp.data.password, label: "Password", alreadyWritten },2104      }).catch(() => null) as { ok?: boolean } | null;2105      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2106      else flashCopyError(copyP);2107    });2108    actions.appendChild(copyP);21092110    let trayEl: HTMLDivElement | null = null;2111    let trayInterval: ReturnType<typeof setInterval> | null = null;21122113    function closeTray() {2114      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2115      trayEl?.remove();2116      trayEl = null;2117    }2118    // Register so dismiss() will close the tray and clear the interval2119    // even if the user dismisses without explicitly closing the tray.2120    cleanupHooks.push(closeTray);21212122    async function openTOTPTray() {2123      // Fetch the entry to get the TOTP secret. The selector summary doesn't2124      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2125      // the message-passing surface minimal per Projects.md §5.2).2126      const resp = await chrome.runtime.sendMessage({2127        type: "GET_ENTRY_FOR_FILL",2128        payload: { id: entry.id },2129      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2130      const secret = resp?.ok ? resp.data?.totp : undefined;2131      if (!secret) return;21322133      trayEl = document.createElement("div");2134      trayEl.className = "sp-tray";21352136      const label = document.createElement("span");2137      label.className = "sp-tray-label";2138      label.textContent = "2FA";2139      trayEl.appendChild(label);21402141      const codeEl = document.createElement("div");2142      codeEl.className = "sp-totp-code";2143      trayEl.appendChild(codeEl);21442145      const ringNs = "http://www.w3.org/2000/svg";2146      const ring = document.createElementNS(ringNs, "svg");2147      ring.setAttribute("class", "sp-totp-ring");2148      ring.setAttribute("viewBox", "0 0 24 24");2149      const trackC = document.createElementNS(ringNs, "circle");2150      trackC.setAttribute("class", "ring-track");2151      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2152      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2153      const fillC = document.createElementNS(ringNs, "circle");2154      fillC.setAttribute("class", "ring-fill");2155      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2156      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2157      fillC.setAttribute("stroke-linecap", "round");2158      fillC.setAttribute("stroke-dasharray", "62.83");2159      ring.append(trackC, fillC);2160      trayEl.appendChild(ring);21612162      const copyBtn = document.createElement("button");2163      copyBtn.className = "sp-totp-copy";2164      copyBtn.type = "button";2165      copyBtn.textContent = "Copy";2166      trayEl.appendChild(copyBtn);21672168      function refresh() {2169        const { code, remaining } = generateTOTP(secret!);2170        // Group as "847 291" — easier to read than "847291"2171        codeEl.textContent = code.length === 62172          ? `${code.slice(0, 3)} ${code.slice(3)}`2173          : code;2174        // Ring fills counter-clockwise as time elapses: dashoffset goes from2175        // 0 (full ring) to 62.83 (empty) over the 30s window.2176        const fraction = (30 - remaining) / 30;2177        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2178      }2179      refresh();2180      trayInterval = setInterval(refresh, 1000);21812182      copyBtn.addEventListener("click", async (e) => {2183        e.stopPropagation();2184        const { code } = generateTOTP(secret!);2185        let alreadyWritten = false;2186        try {2187          await navigator.clipboard.writeText(code);2188          alreadyWritten = true;2189        } catch (err) {2190          console.warn("[Peach] clipboard write denied:", err);2191        }2192        const resp = await chrome.runtime.sendMessage({2193          type: "COPY",2194          payload: { text: code, label: "TOTP", alreadyWritten },2195        }).catch(() => null) as { ok?: boolean } | null;2196        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2197        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2198      });21992200      platter.appendChild(trayEl);2201    }22022203    const editBtn = document.createElement("button");2204    editBtn.className = "sp-action-btn sp-action-edit";2205    editBtn.type = "button";2206    editBtn.title = "Edit entry";2207    editBtn.textContent = "Edit";2208    editBtn.addEventListener("click", (e) => {2209      e.stopPropagation();2210      closeTray();2211      void renderInlineEdit(entry);2212    });2213    actions.appendChild(editBtn);22142215    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2216    // "···" toggle was zero-savings (the toggle button took the same space2217    // the "2FA" label needed) and made the code one extra click away.2218    if (entry.hasTotp) void openTOTPTray();22192220    platter.appendChild(actions);2221    container.appendChild(platter);2222  }22232224  /**2225   * Inline-popup edit mode. Swaps the silver platter for an editable form2226   * over the same shadow-DOM surface so the user never leaves the page.2227   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2228   * with the new fields. Cancel returns without writing.2229   */2230  async function renderInlineEdit(summary: SelectorEntry) {2231    container.innerHTML = "";2232    const wrap = document.createElement("div");2233    wrap.className = "create-form-wrap";22342235    const head = document.createElement("div");2236    head.className = "create-head";2237    const back = document.createElement("button");2238    back.className = "back-btn";2239    back.type = "button";2240    back.title = "Cancel";2241    back.innerHTML = `<svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M7 2L3 5.5L7 9"/></svg>`;2242    back.addEventListener("click", () => renderSilverPlatter(summary));2243    head.appendChild(back);2244    const headLbl = document.createElement("div");2245    headLbl.className = "create-label";2246    headLbl.textContent = "Edit entry";2247    head.appendChild(headLbl);2248    wrap.appendChild(head);22492250    const body = document.createElement("div");2251    body.className = "create-body";22522253    // Loading shimmer while we fetch the full entry2254    const loading = document.createElement("div");2255    loading.className = "empty-hint";2256    loading.textContent = "loading…";2257    body.appendChild(loading);2258    wrap.appendChild(body);2259    container.appendChild(wrap);22602261    const [res, idRes] = await Promise.all([2262      chrome.runtime.sendMessage({2263        type: "GET_ENTRY_FOR_FILL",2264        payload: { id: summary.id },2265      }).catch(() => null),2266      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2267    ]);2268    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2269    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];22702271    if (!entryRes || !entryRes.ok || !entryRes.data) {2272      loading.textContent = "couldn't load this entry. try again from the popup.";2273      return;2274    }2275    body.innerHTML = "";22762277    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2278      const group = document.createElement("div");2279      group.className = "f-group";2280      const lbl = document.createElement("div");2281      lbl.className = "f-label";2282      lbl.textContent = label;2283      const input = document.createElement("input");2284      input.className = "f-input";2285      input.type = type;2286      input.value = value;2287      input.autocomplete = "off";2288      group.append(lbl, input);2289      body.appendChild(group);2290      return { g: group, inp: input };2291    }22922293    const titleInput = field("title", entryRes.data.title ?? "").inp;2294    const urlInput = field("url", entryRes.data.url ?? "").inp;2295    urlInput.classList.add("url-f");2296    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2297    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2298    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2299    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2300    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");23012302    // Password row with reveal toggle + generator2303    const pwGroup = document.createElement("div");2304    pwGroup.className = "f-group";2305    const pwLbl = document.createElement("div");2306    pwLbl.className = "f-label";2307    pwLbl.textContent = "password";2308    const pwRow = document.createElement("div");2309    pwRow.className = "f-row";2310    const pwInput = document.createElement("input");2311    pwInput.className = "f-input";2312    pwInput.type = "password";2313    pwInput.value = entryRes.data.password ?? "";2314    pwInput.autocomplete = "new-password";2315    const revealBtn = document.createElement("button");2316    revealBtn.className = "gen-btn";2317    revealBtn.type = "button";2318    revealBtn.textContent = "show";2319    revealBtn.addEventListener("click", () => {2320      const reveal = pwInput.type === "password";2321      pwInput.type = reveal ? "text" : "password";2322      revealBtn.textContent = reveal ? "hide" : "show";2323    });2324    pwRow.append(pwInput, revealBtn);2325    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2326    editSmartGen.root.style.display = "none";2327    let editGenVisible = false;2328    const genToggleBtn = document.createElement("button");2329    genToggleBtn.className = "gen-toggle-link";2330    genToggleBtn.type = "button";2331    genToggleBtn.textContent = "⚙ generate";2332    genToggleBtn.addEventListener("click", () => {2333      editGenVisible = !editGenVisible;2334      pwRow.style.display = editGenVisible ? "none" : "";2335      editSmartGen.root.style.display = editGenVisible ? "" : "none";2336      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2337    });2338    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2339    body.appendChild(pwGroup);23402341    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;23422343    // Notes2344    const notesGroup = document.createElement("div");2345    notesGroup.className = "f-group";2346    const notesLbl = document.createElement("div");2347    notesLbl.className = "f-label";2348    notesLbl.textContent = "notes";2349    const notesInput = document.createElement("textarea");2350    notesInput.className = "f-input";2351    notesInput.rows = 3;2352    notesInput.value = entryRes.data.notes ?? "";2353    notesInput.style.fontFamily = "Inter, sans-serif";2354    notesInput.style.resize = "vertical";2355    notesGroup.append(notesLbl, notesInput);2356    body.appendChild(notesGroup);23572358    // Save / Cancel row2359    const actionsRow = document.createElement("div");2360    actionsRow.className = "f-row";2361    const saveBtn = document.createElement("button");2362    saveBtn.className = "save-btn";2363    saveBtn.type = "button";2364    saveBtn.textContent = "Save changes";2365    saveBtn.style.flex = "1";2366    const cancelBtn = document.createElement("button");2367    cancelBtn.className = "gen-btn";2368    cancelBtn.type = "button";2369    cancelBtn.textContent = "cancel";2370    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2371    actionsRow.append(saveBtn, cancelBtn);2372    body.appendChild(actionsRow);23732374    saveBtn.addEventListener("click", async () => {2375      saveBtn.disabled = true;2376      const originalLabel = saveBtn.textContent;2377      saveBtn.textContent = "Saving…";2378      const patch: Record<string, unknown> = {2379        title: titleInput.value.trim(),2380        url: urlInput.value.trim(),2381        username: usernameInput.value.trim(),2382        email: emailInput.value.trim() || undefined,2383        password: pwInput.value,2384        totp: totpInput.value.trim(),2385        notes: notesInput.value,2386      };2387      const updateRes = (await chrome.runtime.sendMessage({2388        type: "UPDATE_ENTRY",2389        payload: { id: summary.id, patch },2390      }).catch(() => null)) as { ok: boolean; error?: string } | null;2391      if (!updateRes?.ok) {2392        saveBtn.disabled = false;2393        saveBtn.textContent = originalLabel;2394        const err = document.createElement("div");2395        err.className = "empty-hint";2396        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2397        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2398        body.appendChild(err);2399        setTimeout(() => err.remove(), 3000);2400        return;2401      }2402      // Refresh the platter with updated summary fields2403      const refreshed: SelectorEntry = {2404        id: summary.id,2405        title: patch.title as string,2406        username: patch.username as string,2407        email: patch.email as string | undefined,2408        url: patch.url as string,2409        hasTotp: Boolean(patch.totp),2410        hasPasskey: summary.hasPasskey,2411      };2412      renderSilverPlatter(refreshed);2413    });24142415    queueMicrotask(() => titleInput.focus());2416  }24172418  function renderLocked() {2419    container.innerHTML = "";24202421    // Domain header (same as list view)2422    const domHdr = document.createElement("div");2423    domHdr.className = "domain-header";2424    const eyebrow = document.createElement("div");2425    eyebrow.className = "domain-eyebrow";2426    eyebrow.textContent = "vault locked";2427    const domName = document.createElement("div");2428    domName.className = "domain-name";2429    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2430    domHdr.append(eyebrow, domName);2431    container.appendChild(domHdr);24322433    const wrap = document.createElement("div");2434    wrap.className = "locked-wrap";24352436    // Icon + label row2437    const head = document.createElement("div"); head.className = "locked-head";2438    const icon = document.createElement("div"); icon.className = "locked-icon";2439    icon.innerHTML = keySvgStr();2440    const title = document.createElement("div"); title.className = "locked-title";2441    title.textContent = "unlock to autofill";2442    head.append(icon, title);24432444    // Password input2445    const pwInp = document.createElement("input");2446    pwInp.className = "locked-input";2447    pwInp.type = "password";2448    pwInp.placeholder = "master password";2449    pwInp.setAttribute("autocomplete", "current-password");24502451    // Error line (hidden initially)2452    const errEl = document.createElement("div");2453    errEl.className = "locked-error";2454    errEl.style.display = "none";24552456    // Unlock button2457    const unlockBtn = document.createElement("button");2458    unlockBtn.className = "locked-btn";2459    unlockBtn.type = "button";2460    unlockBtn.textContent = "unlock";24612462    async function tryUnlock() {2463      const pw = pwInp.value.trim();2464      if (!pw) { pwInp.focus(); return; }2465      unlockBtn.disabled = true;2466      unlockBtn.textContent = "unlocking…";2467      errEl.style.display = "none";2468      try {2469        const res = await chrome.runtime.sendMessage({2470          type: "UNLOCK",2471          payload: { password: pw },2472        });2473        if ((res as { ok?: boolean }).ok) {2474          dismiss();2475          options.onUnlocked?.();2476        } else {2477          errEl.textContent = "incorrect password";2478          errEl.style.display = "block";2479          pwInp.value = "";2480          pwInp.focus();2481          unlockBtn.disabled = false;2482          unlockBtn.textContent = "unlock";2483        }2484      } catch {2485        errEl.textContent = "could not reach Peach";2486        errEl.style.display = "block";2487        unlockBtn.disabled = false;2488        unlockBtn.textContent = "unlock";2489      }2490    }24912492    pwInp.addEventListener("keydown", (e) => {2493      e.stopPropagation();2494      if (e.key === "Enter") void tryUnlock();2495    });2496    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2497    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2498    unlockBtn.addEventListener("click", () => void tryUnlock());24992500    wrap.append(head, pwInp, errEl, unlockBtn);2501    container.appendChild(wrap);25022503    // Keep the MV3 service worker alive while the locked popup is visible.2504    // Without this, the SW goes idle (~30 s) while the user types their2505    // password, and the UNLOCK message pays a 100-300 ms wakeup penalty2506    // before the crypto even starts — perceptible as a delay vs the always-2507    // live extension popup page.2508    const keepaliveId = setInterval(() => {2509      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});2510    }, 20_000);2511    cleanupHooks.push(() => clearInterval(keepaliveId));25122513    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2514    // the page reclaims focus from our Shadow DOM input before the user can2515    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2516    // Instead: intercept keystrokes at the document capture phase — this runs2517    // before any page handler regardless of which element technically has2518    // OS focus — and route them into our input.2519    const captureKeydown = (e: KeyboardEvent) => {2520      if (!host.isConnected) {2521        document.removeEventListener("keydown", captureKeydown, true);2522        return;2523      }2524      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2525      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2526      // Intercept before page handlers and give our input focus.2527      e.stopImmediatePropagation();2528      if (e.key === "Escape") { dismiss(true); return; }2529      if (e.key === "Enter") { void tryUnlock(); return; }2530      // For all other printable/editing keys, ensure our input has focus so2531      // the browser delivers the keystroke there naturally.2532      if (document.activeElement !== host) {2533        pwInp.focus({ preventScroll: true });2534      }2535    };2536    captureKeydownRef = captureKeydown;2537    document.addEventListener("keydown", captureKeydown, true);25382539    // Best-effort focus on open — may be overridden by page focus trap,2540    // but the capture listener above handles typing regardless.2541    pwInp.focus({ preventScroll: true });2542    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2543  }25442545  function handleKeyDown(e: KeyboardEvent) {2546    if (options.locked) {2547      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2548      return;2549    }2550    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2551      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2552      return;2553    }2554    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2555    const count = allEntryEls.length;2556    if (document.activeElement === searchInput) {2557      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2558      if (count === 0) return;2559      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2560    }2561    if (count === 0) return;2562    switch (e.key) {2563      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2564      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2565      case "Enter": {2566        if (focusedIndex >= 0) {2567          const el = allEntryEls[focusedIndex] as HTMLElement;2568          const id = el.dataset.id;2569          if (id) { onSelect(id); dismiss(); }2570          else if (el.classList.contains("is-new") || !id) {2571            // "New entry" row (last item, no data-id)2572            showCreateForm();2573          }2574        }2575        break;2576      }2577      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2578    }2579  }25802581  document.addEventListener("keydown", handleKeyDown);25822583  document.body.appendChild(host);25842585  function updatePosition() {2586    const r = anchorEl.getBoundingClientRect();2587    host.style.top = `${r.bottom + window.scrollY + 5}px`;2588    host.style.left = `${r.left + window.scrollX}px`;2589    host.style.width = `${popupWidth}px`;2590  }2591  // These bindings are referenced from renderLocked()/dismiss() — they MUST2592  // be initialized before renderLocked() runs, or the synchronous assignment2593  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2594  // and throws ReferenceError. The throw lands after the popup is rendered2595  // but before showAutofillSelector returns its dismiss handle, leaving an2596  // orphan host in the DOM (which is what caused the locked-popup stacking2597  // and missing autofocus on every click).2598  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2599  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26002601  if (options.locked) {2602    renderLocked();2603  } else if (options.isSignup && options.savedIdentities) {2604    // State 10: identity helper — signup form detected, show derived2605    // identity list (emails then usernames) instead of vault entry list.2606    renderIdentityHelper();2607  } else if (entries.length === 1 && !options.isSignup) {2608    // Silver platter (State 1): single domain match → focused fill view.2609    // Multi-match goes through renderList instead.2610    renderSilverPlatter(entries[0]!);2611  } else {2612    renderList();2613  }26142615  let exitScheduled = false;2616  function dismiss(userAction = false) {2617    // Idempotent: dismiss() can be called from multiple paths (Escape,2618    // outside click, entry select, fill success, host page nav). The exit2619    // animation must only play once and host.remove() must run exactly once.2620    if (exitScheduled) return;2621    exitScheduled = true;2622    // Detach listeners synchronously so nothing can re-trigger during the2623    // 130ms exit window (a focusin firing here would race against the2624    // dismiss-lock work in Pass 2).2625    stopObserving();2626    document.removeEventListener("click", outsideClick, { capture: true });2627    document.removeEventListener("keydown", handleKeyDown);2628    if (captureKeydownRef) {2629      document.removeEventListener("keydown", captureKeydownRef, true);2630      captureKeydownRef = null;2631    }2632    for (const cleanup of cleanupHooks) {2633      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2634    }2635    if (userAction) options.onDismiss?.();2636    container.classList.add("is-exiting");2637    setTimeout(() => host.remove(), 130);2638  }26392640  function outsideClick(ev: MouseEvent) {2641    const path = ev.composedPath();2642    // Never dismiss when clicking the anchor field itself — that click is2643    // what triggered the selector to open, and the user may click the field2644    // again to re-focus it without intending to close the selector.2645    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2646  }2647  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2648  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);26492650  return dismiss;2651}26522653export interface CardSelectorEntry {2654  id: string;2655  title: string;2656  cardholderName?: string;2657  last4?: string;2658  expMonth?: string;2659  expYear?: string;2660  network?: import("../shared/types").CardNetwork;2661}26622663interface CardSelectorOptions {2664  domain?: string;2665  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2666  onFill: (entry: import("../shared/types").VaultEntry) => void;2667  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2668  onDismiss?: () => void;2669}26702671/**2672 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2673 * passkey create or get. Renders as a fixed-position floating popup (no2674 * field anchor needed — passkeys don't require a focused input). Uses the2675 * same theme tokens and entrance animation as all other inline popup states.2676 */2677export function showPasskeyProGate(): void {2678  const domain = location.hostname.replace(/^www\./, "");26792680  const host = document.createElement("div");2681  host.setAttribute("data-peach-passkey-gate", "1");2682  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2683  const shadow = host.attachShadow({ mode: "closed" });26842685  const style = document.createElement("style");2686  style.textContent = `2687    :host { all: initial; }2688    .gate-wrap {2689      position: fixed;2690      top: 50%;2691      left: 50%;2692      transform: translate(-50%, -50%);2693      width: 280px;2694      pointer-events: auto;2695      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2696    }2697    @keyframes g-in {2698      from { opacity:0; transform: translate(-50%,-52%); }2699      to   { opacity:1; transform: translate(-50%,-50%); }2700    }2701    .gate-wrap.is-exiting {2702      animation: g-out 130ms ease-in forwards;2703    }2704    @keyframes g-out {2705      to { opacity:0; transform: translate(-50%,-52%); }2706    }2707    .gate {2708      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2709      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2710      border-radius: 12px;2711      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2712      padding: 16px;2713      font-family: Inter, sans-serif;2714    }2715    .gate-header {2716      display: flex;2717      align-items: center;2718      gap: 7px;2719      margin-bottom: 12px;2720      padding-bottom: 10px;2721      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2722    }2723    .gate-domain {2724      font-size: 12px;2725      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2726      font-family: "IBM Plex Mono", monospace;2727      overflow: hidden;2728      text-overflow: ellipsis;2729      white-space: nowrap;2730    }2731    .gate-title {2732      font-size: 14px;2733      font-weight: 500;2734      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2735      margin-bottom: 6px;2736    }2737    .gate-subtitle {2738      font-size: 12px;2739      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2740      line-height: 1.5;2741      margin-bottom: 14px;2742    }2743    .gate-btn {2744      display: block;2745      width: 100%;2746      padding: 9px 0;2747      border-radius: 8px;2748      border: none;2749      cursor: pointer;2750      font-size: 13px;2751      font-family: Inter, sans-serif;2752      font-weight: 500;2753      transition: opacity 100ms;2754      margin-bottom: 7px;2755      text-align: center;2756    }2757    .gate-btn:last-child { margin-bottom: 0; }2758    .gate-btn--accent {2759      background: ${accentHex};2760      color: #fff;2761    }2762    .gate-btn--accent:hover { opacity: 0.88; }2763    .gate-btn--ghost {2764      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2765      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2766    }2767    .gate-btn--ghost:hover { opacity: 0.75; }2768    .backdrop {2769      position: fixed;2770      inset: 0;2771      pointer-events: auto;2772    }2773  `;2774  shadow.appendChild(style);27752776  const backdrop = document.createElement("div");2777  backdrop.className = "backdrop";2778  shadow.appendChild(backdrop);27792780  const wrap = document.createElement("div");2781  wrap.className = "gate-wrap";2782  shadow.appendChild(wrap);27832784  const gate = document.createElement("div");2785  gate.className = "gate";2786  wrap.appendChild(gate);27872788  // Header: peach icon + domain2789  const header = document.createElement("div");2790  header.className = "gate-header";2791  const icon = document.createElement("span");2792  icon.innerHTML = peachIconSvg();2793  const domainEl = document.createElement("span");2794  domainEl.className = "gate-domain";2795  domainEl.textContent = domain;2796  header.append(icon, domainEl);2797  gate.appendChild(header);27982799  const title = document.createElement("div");2800  title.className = "gate-title";2801  title.textContent = "Passkeys are part of Peach Pro.";2802  gate.appendChild(title);28032804  const subtitle = document.createElement("div");2805  subtitle.className = "gate-subtitle";2806  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2807  gate.appendChild(subtitle);28082809  const upgradeBtn = document.createElement("button");2810  upgradeBtn.className = "gate-btn gate-btn--accent";2811  upgradeBtn.type = "button";2812  upgradeBtn.textContent = "Upgrade to Pro";2813  gate.appendChild(upgradeBtn);28142815  const laterBtn = document.createElement("button");2816  laterBtn.className = "gate-btn gate-btn--ghost";2817  laterBtn.type = "button";2818  laterBtn.textContent = "Not right now";2819  gate.appendChild(laterBtn);28202821  function dismiss() {2822    wrap.classList.add("is-exiting");2823    setTimeout(() => host.remove(), 130);2824  }28252826  upgradeBtn.addEventListener("click", () => {2827    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2828    dismiss();2829  });2830  laterBtn.addEventListener("click", dismiss);2831  backdrop.addEventListener("click", dismiss);28322833  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2834    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2835  });28362837  document.body.appendChild(host);2838}28392840/**2841 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2842 * detector sees the page invoke navigator.credentials.create(); content/index.ts2843 * checks vault + decline state then calls this. "Save passkey to Peach"2844 * initiates the popup-context credential flow; "Not now" records a 30-day2845 * decline for the domain so we don't re-show on every page reload.2846 */2847export function showPasskeyRegistrationOffer(args: {2848  rpId: string;2849  rpName?: string;2850  userName?: string;2851  userDisplayName?: string;2852}): void {2853  const domain = location.hostname.replace(/^www\./, "");2854  const displayName = args.rpName || domain;28552856  const host = document.createElement("div");2857  host.setAttribute("data-peach-passkey-offer", "1");2858  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2859  const shadow = host.attachShadow({ mode: "closed" });28602861  const style = document.createElement("style");2862  style.textContent = `2863    :host { all: initial; }2864    .offer-wrap {2865      position: fixed;2866      top: 16px;2867      right: 16px;2868      width: 320px;2869      pointer-events: auto;2870      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2871    }2872    @keyframes o-in {2873      from { opacity: 0; transform: translateY(-6px); }2874      to   { opacity: 1; transform: translateY(0); }2875    }2876    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2877    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2878    .offer {2879      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2880      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2881      border-radius: 12px;2882      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2883      padding: 14px 14px 12px;2884      font-family: Inter, sans-serif;2885      position: relative;2886    }2887    .offer-close {2888      position: absolute;2889      top: 8px;2890      right: 8px;2891      width: 18px;2892      height: 18px;2893      border: none;2894      background: transparent;2895      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2896      cursor: pointer;2897      font-size: 14px;2898      line-height: 1;2899      padding: 0;2900    }2901    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2902    .offer-header {2903      display: flex;2904      align-items: center;2905      gap: 7px;2906      margin-bottom: 8px;2907      padding-bottom: 8px;2908      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2909    }2910    .offer-domain {2911      font-size: 12px;2912      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2913      font-family: "IBM Plex Mono", monospace;2914      overflow: hidden;2915      text-overflow: ellipsis;2916      white-space: nowrap;2917    }2918    .offer-title {2919      font-size: 13px;2920      font-weight: 500;2921      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2922      margin-bottom: 4px;2923    }2924    .offer-subtitle {2925      font-size: 11px;2926      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2927      line-height: 1.45;2928      margin-bottom: 12px;2929    }2930    .offer-btn {2931      display: block;2932      width: 100%;2933      padding: 8px 0;2934      border-radius: 7px;2935      border: none;2936      cursor: pointer;2937      font-size: 12px;2938      font-family: Inter, sans-serif;2939      font-weight: 500;2940      transition: opacity 100ms;2941      margin-bottom: 6px;2942      text-align: center;2943    }2944    .offer-btn:last-child { margin-bottom: 0; }2945    .offer-btn--accent { background: ${accentHex}; color: #fff; }2946    .offer-btn--accent:hover { opacity: 0.88; }2947    .offer-btn--ghost {2948      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2949      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2950    }2951    .offer-btn--ghost:hover { opacity: 0.75; }2952  `;2953  shadow.appendChild(style);29542955  const wrap = document.createElement("div");2956  wrap.className = "offer-wrap";2957  shadow.appendChild(wrap);29582959  const offer = document.createElement("div");2960  offer.className = "offer";2961  wrap.appendChild(offer);29622963  const closeBtn = document.createElement("button");2964  closeBtn.className = "offer-close";2965  closeBtn.type = "button";2966  closeBtn.setAttribute("aria-label", "Dismiss");2967  closeBtn.textContent = "✕";2968  offer.appendChild(closeBtn);29692970  const header = document.createElement("div");2971  header.className = "offer-header";2972  const icon = document.createElement("span");2973  icon.innerHTML = peachIconSvg();2974  const domainEl = document.createElement("span");2975  domainEl.className = "offer-domain";2976  domainEl.textContent = domain;2977  header.append(icon, domainEl);2978  offer.appendChild(header);29792980  const title = document.createElement("div");2981  title.className = "offer-title";2982  title.textContent = "This site supports passkeys.";2983  offer.appendChild(title);29842985  const subtitle = document.createElement("div");2986  subtitle.className = "offer-subtitle";2987  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2988  offer.appendChild(subtitle);29892990  const saveBtn = document.createElement("button");2991  saveBtn.className = "offer-btn offer-btn--accent";2992  saveBtn.type = "button";2993  saveBtn.textContent = "Save passkey to Peach";2994  offer.appendChild(saveBtn);29952996  const laterBtn = document.createElement("button");2997  laterBtn.className = "offer-btn offer-btn--ghost";2998  laterBtn.type = "button";2999  laterBtn.textContent = "Not now";3000  offer.appendChild(laterBtn);30013002  function dismiss(decline: boolean) {3003    if (decline) {3004      chrome.runtime.sendMessage({3005        type: "PASSKEY_OFFER_DECLINE",3006        payload: { domain },3007      }).catch(() => {});3008    }3009    wrap.classList.add("is-exiting");3010    setTimeout(() => host.remove(), 130);3011  }30123013  saveBtn.addEventListener("click", () => {3014    chrome.runtime.sendMessage({3015      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3016      payload: {3017        rpId: args.rpId,3018        rpName: args.rpName ?? displayName,3019        userName: args.userName ?? "user",3020        userDisplayName: args.userDisplayName,3021      },3022    }).catch(() => {});3023    dismiss(false);3024  });3025  laterBtn.addEventListener("click", () => dismiss(true));3026  closeBtn.addEventListener("click", () => dismiss(true));30273028  document.body.appendChild(host);3029}30303031/**3032 * State 11 — passkey available indicator. Shown when the user lands on a3033 * domain for which they already have a stored passkey. Tells them where to3034 * find it (the entry already shows in the vault list); the "Sign in with3035 * passkey" button opens the popup so they can use the platform authenticator3036 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3037 * the actual sign-in transparently, so this banner is informational only.3038 */3039export function showPasskeyAvailable(args: {3040  rpId: string;3041  userName: string;3042  fromBrowser?: "chrome" | "firefox";3043  currentBrowser?: "chrome" | "firefox" | "unknown";3044}): void {3045  const domain = location.hostname.replace(/^www\./, "");3046  const crossBrowser =3047    args.fromBrowser &&3048    args.currentBrowser &&3049    args.currentBrowser !== "unknown" &&3050    args.fromBrowser !== args.currentBrowser;30513052  const host = document.createElement("div");3053  host.setAttribute("data-peach-passkey-available", "1");3054  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3055  const shadow = host.attachShadow({ mode: "closed" });30563057  const style = document.createElement("style");3058  style.textContent = `3059    :host { all: initial; }3060    .avail-wrap {3061      position: fixed;3062      top: 16px;3063      right: 16px;3064      width: 320px;3065      pointer-events: auto;3066      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3067    }3068    @keyframes a-in {3069      from { opacity: 0; transform: translateY(-6px); }3070      to   { opacity: 1; transform: translateY(0); }3071    }3072    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3073    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3074    .avail {3075      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3076      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3077      border-radius: 12px;3078      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3079      padding: 14px 14px 12px;3080      font-family: Inter, sans-serif;3081      position: relative;3082    }3083    .avail-close {3084      position: absolute;3085      top: 8px;3086      right: 8px;3087      width: 18px;3088      height: 18px;3089      border: none;3090      background: transparent;3091      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3092      cursor: pointer;3093      font-size: 14px;3094      line-height: 1;3095      padding: 0;3096    }3097    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3098    .avail-header {3099      display: flex;3100      align-items: center;3101      gap: 7px;3102      margin-bottom: 8px;3103      padding-bottom: 8px;3104      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3105    }3106    .avail-domain {3107      font-size: 12px;3108      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3109      font-family: "IBM Plex Mono", monospace;3110    }3111    .avail-label {3112      font-size: 9px;3113      letter-spacing: 0.16em;3114      text-transform: uppercase;3115      color: ${accentHex};3116      margin-bottom: 4px;3117    }3118    .avail-user {3119      font-size: 13px;3120      font-weight: 500;3121      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3122      margin-bottom: 12px;3123      overflow: hidden;3124      text-overflow: ellipsis;3125      white-space: nowrap;3126    }3127    .avail-cross {3128      font-size: 11px;3129      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3130      line-height: 1.45;3131      margin-bottom: 12px;3132      padding: 8px;3133      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3134      border-radius: 6px;3135    }3136    .avail-btn {3137      display: block;3138      width: 100%;3139      padding: 8px 0;3140      border-radius: 7px;3141      border: none;3142      cursor: pointer;3143      font-size: 12px;3144      font-family: Inter, sans-serif;3145      font-weight: 500;3146      transition: opacity 100ms;3147      margin-bottom: 6px;3148      text-align: center;3149    }3150    .avail-btn:last-child { margin-bottom: 0; }3151    .avail-btn--accent { background: ${accentHex}; color: #fff; }3152    .avail-btn--accent:hover { opacity: 0.88; }3153    .avail-btn--ghost {3154      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3155      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3156    }3157    .avail-btn--ghost:hover { opacity: 0.75; }3158  `;3159  shadow.appendChild(style);31603161  const wrap = document.createElement("div");3162  wrap.className = "avail-wrap";3163  shadow.appendChild(wrap);31643165  const avail = document.createElement("div");3166  avail.className = "avail";3167  wrap.appendChild(avail);31683169  const closeBtn = document.createElement("button");3170  closeBtn.className = "avail-close";3171  closeBtn.type = "button";3172  closeBtn.setAttribute("aria-label", "Dismiss");3173  closeBtn.textContent = "✕";3174  avail.appendChild(closeBtn);31753176  const header = document.createElement("div");3177  header.className = "avail-header";3178  const icon = document.createElement("span");3179  icon.innerHTML = peachIconSvg();3180  const domainEl = document.createElement("span");3181  domainEl.className = "avail-domain";3182  domainEl.textContent = domain;3183  header.append(icon, domainEl);3184  avail.appendChild(header);31853186  const label = document.createElement("div");3187  label.className = "avail-label";3188  label.textContent = "PASSKEY";3189  avail.appendChild(label);31903191  const user = document.createElement("div");3192  user.className = "avail-user";3193  user.textContent = args.userName;3194  avail.appendChild(user);31953196  if (crossBrowser) {3197    const cross = document.createElement("div");3198    cross.className = "avail-cross";3199    cross.textContent =3200      args.fromBrowser === "chrome"3201        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3202        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3203    avail.appendChild(cross);3204  }32053206  const signInBtn = document.createElement("button");3207  signInBtn.className = "avail-btn avail-btn--accent";3208  signInBtn.type = "button";3209  signInBtn.textContent = "Sign in with passkey";3210  avail.appendChild(signInBtn);32113212  const passwordBtn = document.createElement("button");3213  passwordBtn.className = "avail-btn avail-btn--ghost";3214  passwordBtn.type = "button";3215  passwordBtn.textContent = "Use password instead";3216  avail.appendChild(passwordBtn);32173218  function dismiss() {3219    wrap.classList.add("is-exiting");3220    setTimeout(() => host.remove(), 130);3221  }32223223  signInBtn.addEventListener("click", () => {3224    // On Chrome: the user clicking the page's own Sign-in button is what3225    //   triggers webAuthenticationProxy → existing background flow handles it.3226    //   Our button just dismisses since the page itself drives auth.3227    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3228    //   and surface the entry for manual reference (popup view).3229    dismiss();3230    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3231  });3232  passwordBtn.addEventListener("click", dismiss);3233  closeBtn.addEventListener("click", dismiss);32343235  document.body.appendChild(host);3236}32373238/**3239 * State 7 — card silver platter. Single-card focused fill view rendered3240 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3241 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3242 * so card and login flows render identically. Multi-card list view is a3243 * follow-up; today this picks the first card.3244 */3245export function showCardSelector(3246  anchorEl: HTMLInputElement,3247  cards: CardSelectorEntry[],3248  options: CardSelectorOptions3249): () => void {3250  if (cards.length === 0) return () => {};3251  const card = cards[0]!;32523253  const host = document.createElement("div");3254  host.style.cssText = "position: absolute; z-index: 2147483647;";3255  host.style.setProperty("--peach-accent", accentHex);3256  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3257  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3258  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3259  const shadow = host.attachShadow({ mode: "closed" });32603261  const style = shadow.appendChild(document.createElement("style"));3262  style.textContent = SELECTOR_STYLES;32633264  const rect = anchorEl.getBoundingClientRect();3265  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3266  host.style.left = `${rect.left + window.scrollX}px`;3267  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;32683269  const container = shadow.appendChild(document.createElement("div"));3270  container.className = "peach-inline-popup";3271  container.setAttribute("data-theme", popupTheme);32723273  // Domain header — eyebrow communicates the card context, not the site3274  const domHdr = document.createElement("div");3275  domHdr.className = "domain-header";3276  const eyebrow = document.createElement("div");3277  eyebrow.className = "domain-eyebrow";3278  eyebrow.textContent = "Pay with Peach";3279  const domName = document.createElement("div");3280  domName.className = "domain-name";3281  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3282  domHdr.append(eyebrow, domName);3283  container.appendChild(domHdr);32843285  const platter = document.createElement("div");3286  platter.className = "card-platter";32873288  if (card.network && card.network !== "unknown") {3289    const net = document.createElement("div");3290    net.className = "cp-network";3291    net.textContent = card.network;3292    platter.appendChild(net);3293  }32943295  const nick = document.createElement("div");3296  nick.className = "cp-nickname";3297  nick.textContent = card.title;3298  platter.appendChild(nick);32993300  if (card.last4) {3301    const l4 = document.createElement("div");3302    l4.className = "cp-last4";3303    l4.textContent = `•••• ${card.last4}`;3304    platter.appendChild(l4);3305  }33063307  const meta = document.createElement("div");3308  meta.className = "cp-meta";3309  if (card.cardholderName) {3310    const name = document.createElement("span");3311    name.textContent = card.cardholderName;3312    meta.appendChild(name);3313  }3314  if (card.expMonth && card.expYear) {3315    if (card.cardholderName) {3316      const sep = document.createElement("span");3317      sep.className = "cp-meta-sep";3318      sep.textContent = "·";3319      meta.appendChild(sep);3320    }3321    const exp = document.createElement("span");3322    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3323    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3324    meta.appendChild(exp);3325  }3326  if (meta.childElementCount > 0) platter.appendChild(meta);33273328  const fillWrap = document.createElement("div");3329  fillWrap.className = "cp-fill-wrap";3330  const fillBtn = document.createElement("button");3331  fillBtn.className = "sp-fill-btn";3332  fillBtn.type = "button";3333  fillBtn.textContent = "Fill card details";3334  fillBtn.addEventListener("click", async () => {3335    if (fillBtn.disabled) return;3336    fillBtn.disabled = true;3337    fillBtn.classList.add("filled");3338    fillBtn.innerHTML = checkSvgStr();3339    const resp = await chrome.runtime.sendMessage({3340      type: "GET_ENTRY_FOR_FILL",3341      payload: { id: card.id },3342    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3343    if (resp?.ok && resp.data) options.onFill(resp.data);3344    setTimeout(() => dismiss(), 400);3345  });3346  fillWrap.appendChild(fillBtn);3347  platter.appendChild(fillWrap);33483349  // Secondary actions — copy number, copy CVC, dismiss3350  const actions = document.createElement("div");3351  actions.className = "sp-actions";33523353  function flashBtn(b: HTMLButtonElement) {3354    b.classList.add("flashed");3355    setTimeout(() => b.classList.remove("flashed"), 700);3356  }33573358  // M3/QUA-005: clipboard + background COPY both failed — show user.3359  function flashCopyError(b: HTMLButtonElement) {3360    const original = b.textContent ?? "";3361    b.textContent = "Blocked";3362    b.classList.add("flashed");3363    setTimeout(() => {3364      b.classList.remove("flashed");3365      if (b.isConnected) b.textContent = original;3366    }, 1200);3367  }33683369  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3370    const resp = await chrome.runtime.sendMessage({3371      type: "GET_ENTRY_FOR_FILL",3372      payload: { id: card.id },3373    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3374    return resp?.ok && resp.data ? resp.data : null;3375  }33763377  const copyNum = document.createElement("button");3378  copyNum.className = "sp-action-btn";3379  copyNum.type = "button";3380  copyNum.title = "Copy card number";3381  copyNum.textContent = "Copy number";3382  copyNum.addEventListener("click", async (e) => {3383    e.stopPropagation();3384    const full = await fetchFullCard();3385    if (!full?.cardNumber) return;3386    let alreadyWritten = false;3387    try {3388      await navigator.clipboard.writeText(full.cardNumber);3389      alreadyWritten = true;3390    } catch (err) {3391      console.warn("[Peach] clipboard write denied:", err);3392    }3393    const resp = await chrome.runtime.sendMessage({3394      type: "COPY",3395      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3396    }).catch(() => null) as { ok?: boolean } | null;3397    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3398    else flashCopyError(copyNum);3399  });3400  actions.appendChild(copyNum);34013402  const copyCvc = document.createElement("button");3403  copyCvc.className = "sp-action-btn";3404  copyCvc.type = "button";3405  copyCvc.title = "Copy CVC";3406  copyCvc.textContent = "Copy CVC";3407  copyCvc.addEventListener("click", async (e) => {3408    e.stopPropagation();3409    const full = await fetchFullCard();3410    if (!full?.cvc) return;3411    let alreadyWritten = false;3412    try {3413      await navigator.clipboard.writeText(full.cvc);3414      alreadyWritten = true;3415    } catch (err) {3416      console.warn("[Peach] clipboard write denied:", err);3417    }3418    const resp = await chrome.runtime.sendMessage({3419      type: "COPY",3420      payload: { text: full.cvc, label: "CVC", alreadyWritten },3421    }).catch(() => null) as { ok?: boolean } | null;3422    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3423    else flashCopyError(copyCvc);3424  });3425  actions.appendChild(copyCvc);34263427  const closeBtn = document.createElement("button");3428  closeBtn.className = "sp-action-btn";3429  closeBtn.type = "button";3430  closeBtn.title = "Dismiss";3431  closeBtn.textContent = "✕";3432  closeBtn.addEventListener("click", (e) => {3433    e.stopPropagation();3434    dismiss(true);3435  });3436  actions.appendChild(closeBtn);34373438  platter.appendChild(actions);3439  container.appendChild(platter);34403441  document.body.appendChild(host);3442  function updatePosition() {3443    const r = anchorEl.getBoundingClientRect();3444    host.style.top = `${r.bottom + window.scrollY + 5}px`;3445    host.style.left = `${r.left + window.scrollX}px`;3446  }3447  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);34483449  function onKeyDown(e: KeyboardEvent) {3450    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3451  }3452  document.addEventListener("keydown", onKeyDown);34533454  let exitScheduled = false;3455  function dismiss(userAction = false) {3456    if (exitScheduled) return;3457    exitScheduled = true;3458    stopObserving();3459    document.removeEventListener("click", outsideClick, { capture: true });3460    document.removeEventListener("keydown", onKeyDown);3461    if (userAction) options.onDismiss?.();3462    container.classList.add("is-exiting");3463    setTimeout(() => host.remove(), 130);3464  }34653466  function outsideClick(ev: MouseEvent) {3467    const path = ev.composedPath();3468    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3469  }3470  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);34713472  return dismiss;3473}