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, generateSmartPassword } 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 is always brand-peach (#D96830), not `accentHex` — a sage96  // or 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 64 64" fill="none" aria-hidden="true"><path d="M32 54C16 54 8 44 8 31C8 18 17 10 27 10C28 7 30 5.5 32 5.5C34 5.5 36 7 37 10C47 10 56 18 56 31C56 44 48 54 32 54Z" fill="#D96830"/><path d="M37 8.5C40.5 3.5 48 5 46 10.5C42 11 37 8.5 37 8.5Z" fill="#7B9060"/></svg>`;99}100101function genSvgStr(): string {102  return `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round"><path d="M9.5 2A4.5 4.5 0 1 0 10.5 5.5"/><path d="M8.5 2H9.5V1"/></svg>`;103}104105function checkSvgStr(): string {106  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="#7B9060" stroke-width="1.5" stroke-linecap="round"><path d="M4 10.5L8 14.5L16 6.5"/></svg>`;107}108109function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {110  const { hostname, origin } = location;111  const parts = hostname.split(".");112  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",113    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",114    "oidc", "federation", "saml", "cas", "ldap"];115  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());116  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;117  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);118  return { origin, title, loginSubdomain };119}120121/**122 * Shows a bottom-of-page toast after filling credentials when the entry has123 * never matched the current site — offering to add the current origin to the124 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.125 */126export function showRememberSiteToast(127  pageDomain: string,128  entryId: string,129): void {130  const host = document.createElement("div");131  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";132  host.style.setProperty("--peach-accent", accentHex);133  const shadow = host.attachShadow({ mode: "closed" });134135  const style = document.createElement("style");136  style.textContent = `137    .bar {138      display:flex;align-items:center;gap:10px;padding:10px 14px;139      background:#131109;border:1px solid rgba(240,232,216,0.09);140      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);141      font-family:Inter,sans-serif;white-space:nowrap;142      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;143    }144    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }145    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }146    .yes {147      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;148      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;149    }150    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }151    .no {152      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;153      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;154    }155  `;156  shadow.appendChild(style);157158  const bar = document.createElement("div"); bar.className = "bar";159  const txt = document.createElement("span"); txt.className = "txt";160  txt.textContent = `Remember ${pageDomain} for this entry?`;161  const yesBtn = document.createElement("button"); yesBtn.className = "yes";162  yesBtn.textContent = "Remember";163  yesBtn.addEventListener("click", async () => {164    await chrome.runtime.sendMessage({165      type: "ADD_ADDITIONAL_URL",166      payload: { id: entryId, url: location.origin },167    });168    host.remove();169  });170  const noBtn = document.createElement("button"); noBtn.className = "no";171  noBtn.textContent = "Not now";172  noBtn.addEventListener("click", () => host.remove());173  bar.append(txt, yesBtn, noBtn);174  shadow.appendChild(bar);175  document.body.appendChild(host);176  setTimeout(() => host.remove(), 9000);177}178179function generatePasswordForSite(policy: PasswordPolicy = {}): string {180  return generateSmartPassword(policy);181}182183interface SmartGenerator {184  root: HTMLElement;185  getPassword: () => string;186  /** Copy the current password to the clipboard with the standard pulse UX. */187  copy: () => Promise<void>;188}189190interface SmartGeneratorOptions {191  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */192  policy: PasswordPolicy;193  /**194   * Seed value: used as the displayed password without regenerating, e.g. the195   * password the user already typed into the page. The generator still196   * regenerates the moment any control changes.197   */198  initialPassword?: string;199  /** Fires every time the password regenerates (initial + on changes). */200  onChange?: (pw: string) => void;201}202203/**204 * Build the inline-popup smart-password generator. Mirrors the main popup's205 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset206 * pills + a policy hint that names the constraints Peach detected on the207 * page. Writing this in pure DOM rather than reusing the Solid component208 * keeps the content-script bundle small.209 */210function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {211  const policy = opts.policy ?? {};212213  // Start at site max (strongest password the site accepts), fall back to 64214  let length = policy.maxLength ?? 64;215  if (policy.minLength) length = Math.max(length, policy.minLength);216  if (length < 8) length = 8;217  if (length > 128) length = 128;218219  let upper = true;220  let lower = true;221  let numbers = true;222  let symbols = !policy.forbidsSymbols;223  if (policy.requiresSymbols) symbols = true;224  const forbiddenChars = policy.forbiddenChars ?? "";225226  let password = "";227228  const root = document.createElement("div");229  root.className = "pwgen-block";230231  const displayRow = root.appendChild(document.createElement("div"));232  displayRow.className = "pwgen-display-row";233  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;234  output.type = "text";235  output.className = "pwgen-output";236  output.setAttribute("autocomplete", "off");237  output.setAttribute("spellcheck", "false");238  output.setAttribute("autocorrect", "off");239  output.setAttribute("autocapitalize", "off");240241  const regenBtn = displayRow.appendChild(document.createElement("button"));242  regenBtn.className = "pwgen-icon-btn";243  regenBtn.type = "button";244  regenBtn.setAttribute("aria-label", "Regenerate password");245  regenBtn.title = "Regenerate";246  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>`;247248  const copyBtn = displayRow.appendChild(document.createElement("button"));249  copyBtn.className = "pwgen-icon-btn";250  copyBtn.type = "button";251  copyBtn.setAttribute("aria-label", "Copy password");252  copyBtn.title = "Copy";253  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>`;254255  const controls = root.appendChild(document.createElement("div"));256  controls.className = "pwgen-controls-row";257  const slider = controls.appendChild(document.createElement("input"));258  slider.type = "range";259  slider.className = "pwgen-slider";260  slider.min = "8";261  slider.max = "128";262  slider.value = String(length);263  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));264  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));265  const lenNum = controls.appendChild(document.createElement("span"));266  lenNum.className = "pwgen-len-num pwgen-len-num--edit";267  lenNum.textContent = String(length);268  lenNum.addEventListener("click", () => {269    const li = document.createElement("input");270    li.type = "text"; li.inputMode = "numeric";271    li.className = "pwgen-len-input"; li.value = String(length);272    lenNum.replaceWith(li);273    requestAnimationFrame(() => li.select());274    function commitLenEdit() {275      const n = parseInt(li.value, 10);276      if (!isNaN(n)) {277        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));278        slider.value = String(length);279        regenerate();280      }281      lenNum.textContent = String(length);282      li.replaceWith(lenNum);283    }284    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });285    li.addEventListener("blur", commitLenEdit);286  });287288  const pills = root.appendChild(document.createElement("div"));289  pills.className = "pwgen-pills";290291  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {292    const b = document.createElement("button");293    b.type = "button";294    b.className = `pwgen-pill ${on ? "is-on" : ""}`;295    b.textContent = label;296    b.addEventListener("click", () => {297      const next = !b.classList.contains("is-on");298      b.classList.toggle("is-on", next);299      onToggle(next);300    });301    return b;302  }303  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));304  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));305  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));306  pills.appendChild(makePill("!@#", symbols, (next) => {307    // The site forbids symbols — UI lets the user override but still warn.308    symbols = next;309    regenerate();310  }));311312  // Policy hint — surfaces what Peach read off the site so the user knows the313  // generator is already tuned to it. Only shows when something interesting314  // was detected.315  const hintParts: string[] = [];316  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);317  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);318  if (policy.requiresSymbols) hintParts.push("requires symbols");319  if (policy.forbidsSymbols) hintParts.push("no symbols");320  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);321  if (hintParts.length > 0) {322    const hint = root.appendChild(document.createElement("div"));323    hint.className = "pwgen-policy-hint";324    const accent = document.createElement("span");325    accent.className = "pwgen-hint-accent";326    accent.textContent = "site rules · ";327    const text = document.createTextNode(hintParts.join(" · "));328    hint.appendChild(accent);329    hint.appendChild(text);330  }331332  function regenerate() {333    // Falls back gracefully when the user toggles every charset off — the334    // shared generator forces lowercase in that case rather than throwing.335    password = generatePassword({336      length,337      includeUppercase: upper,338      includeLowercase: lower,339      includeNumbers: numbers,340      includeSymbols: symbols,341      forbiddenChars,342    });343    output.value = password;344    opts.onChange?.(password);345  }346347  output.addEventListener("input", () => {348    password = output.value;349    length = password.length;350    slider.value = String(Math.max(8, Math.min(128, length)));351    lenNum.textContent = String(length);352    opts.onChange?.(password);353  });354355  slider.addEventListener("input", () => {356    length = parseInt(slider.value, 10);357    lenNum.textContent = String(length);358    regenerate();359  });360  regenBtn.addEventListener("click", regenerate);361362  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;363  async function copy(): Promise<void> {364    try {365      await navigator.clipboard.writeText(password);366      copyBtn.classList.add("is-copied");367      if (copyResetTimer) clearTimeout(copyResetTimer);368      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);369    } catch {370      // Clipboard API may be denied — silently no-op; user still has regen UI.371    }372  }373  copyBtn.addEventListener("click", () => { void copy(); });374375  if (opts.initialPassword) {376    password = opts.initialPassword;377    output.value = password;378    opts.onChange?.(password);379  } else {380    regenerate();381  }382383  return {384    root,385    getPassword: () => password,386    copy,387  };388}389390export function observeAnchorPosition(391  anchorEl: HTMLElement,392  onUpdate: () => void393): () => void {394  let rafId = 0;395  let burstUntil = 0;396397  const runUpdate = () => {398    rafId = 0;399    onUpdate();400    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);401  };402  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };403  const scheduleBurst = (ms = 220) => {404    burstUntil = Math.max(burstUntil, performance.now() + ms);405    scheduleUpdate();406  };407408  const resizeObserver = new ResizeObserver(() => scheduleBurst());409  resizeObserver.observe(anchorEl);410  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);411412  const mutationObserver = new MutationObserver(() => scheduleBurst());413  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });414  if (anchorEl.parentElement) {415    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });416  }417418  const onScroll = () => scheduleUpdate();419  window.addEventListener("scroll", onScroll, true);420  window.addEventListener("resize", onScroll);421  window.visualViewport?.addEventListener("resize", onScroll);422  window.visualViewport?.addEventListener("scroll", onScroll);423  anchorEl.addEventListener("focus", () => scheduleBurst());424  anchorEl.addEventListener("input", () => scheduleBurst());425426  scheduleBurst(260);427428  return () => {429    if (rafId) cancelAnimationFrame(rafId);430    resizeObserver.disconnect();431    mutationObserver.disconnect();432    window.removeEventListener("scroll", onScroll, true);433    window.removeEventListener("resize", onScroll);434    window.visualViewport?.removeEventListener("resize", onScroll);435    window.visualViewport?.removeEventListener("scroll", onScroll);436  };437}438439export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {440  const button = document.createElement("button");441  button.type = "button";442  button.setAttribute("aria-label", "Peach autofill");443  button.title = "Fill with Peach";444  button.innerHTML = peachIconSvg();445  // position: fixed is load-bearing — not absolute. Absolute positioning446  // inherits the nearest positioned ancestor's box, which on sites with447  // overflow:hidden or sticky parents clips or offsets the icon. Fixed448  // anchors to the viewport and escapes all parent layout.449  button.style.cssText = `450    position: fixed; z-index: 2147483646;451    width: 26px; height: 26px; cursor: pointer;452    pointer-events: auto; border: none; padding: 3px;453    display: inline-flex; align-items: center; justify-content: center;454    background: transparent; border-radius: 999px;455    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;456    opacity: 0;457  `;458  button.addEventListener("mouseenter", () => {459    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;460    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;461    button.style.transform = "scale(1.08)";462  });463  button.addEventListener("mouseleave", () => {464    button.style.background = "transparent";465    button.style.boxShadow = "none";466    button.style.transform = "none";467  });468  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });469  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });470471  document.body.appendChild(button);472473  function updatePosition() {474    const rect = field.getBoundingClientRect();475    if (rect.width === 0 || rect.height === 0) {476      button.style.opacity = "0"; button.style.pointerEvents = "none";477      return;478    }479    const sz = 26;480    const inset = Math.max(5, Math.min(10, rect.height * 0.22));481    const top = rect.top + rect.height / 2 - sz / 2;482    // Clamp left so the icon stays fully inside the field's right edge, never483    // spilling onto an adjacent sibling button.484    const minLeft = rect.left + 4;485    const left = Math.max(minLeft, rect.right - sz - inset);486    // Hide if the field is too narrow to fit the icon cleanly (< 40px)487    if (rect.width < 40) {488      button.style.opacity = "0"; button.style.pointerEvents = "none";489      return;490    }491    button.style.top = `${top}px`;492    button.style.left = `${left}px`;493    button.style.opacity = "1"; button.style.pointerEvents = "auto";494  }495  updatePosition();496  requestAnimationFrame(() => { button.style.opacity = "1"; });497  const stopObserving = observeAnchorPosition(field, updatePosition);498  return () => { stopObserving(); button.remove(); };499}500501// All theme-dependent values resolve through tokens scoped to502// .peach-inline-popup[data-theme="dark|light"]. Accent variables503// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)504// are identical in both themes — only surface tokens differ. See505// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the506// theme switch — only literal brand-peach in peachIconSvg may stay raw.507const SELECTOR_STYLES = `508  :host { all: initial; }509  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }510511  .peach-inline-popup[data-theme="dark"] {512    --peach-bg:           #1a1410;513    --peach-bg-card:      #221c16;514    --peach-text:         #f5f0ea;515    --peach-text-dim:     #8a7a6a;516    --peach-text-muted:   #4a3a2a;517    --peach-border:       rgba(255,255,255,0.07);518    --peach-input-bg:     rgba(255,255,255,0.05);519    --peach-input-border: rgba(255,255,255,0.08);520  }521  .peach-inline-popup[data-theme="light"] {522    --peach-bg:           #fdf8f4;523    --peach-bg-card:      #f5ede4;524    --peach-text:         #1c1310;525    --peach-text-dim:     #6b5a4a;526    --peach-text-muted:   #a89080;527    --peach-border:       rgba(0,0,0,0.08);528    --peach-input-bg:     rgba(0,0,0,0.04);529    --peach-input-border: rgba(0,0,0,0.10);530  }531532  .peach-inline-popup {533    background: var(--peach-bg);534    border: 1px solid var(--peach-border-accent, var(--peach-border));535    border-radius: 14px;536    overflow: hidden;537    box-shadow:538      0 8px 40px var(--peach-glow, transparent),539      0 2px 12px rgba(0,0,0,0.5);540    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;541    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;542    transition: height 220ms cubic-bezier(0.16,1,0.3,1);543  }544  /* Light theme: shadow against a light page is too strong otherwise — drop both545     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */546  .peach-inline-popup[data-theme="light"] {547    box-shadow:548      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),549      0 2px 12px rgba(0,0,0,0.12);550  }551  .peach-inline-popup.is-exiting {552    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;553    pointer-events: none;554  }555556  @keyframes peach-enter {557    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }558    65%  { opacity: 1; filter: blur(0); }559    100% { opacity: 1; transform: translateY(0) scale(1); }560  }561  @keyframes peach-exit {562    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }563    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }564  }565  @keyframes peach-slide-in {566    from { opacity: 0; transform: translateX(12px); }567    to   { opacity: 1; transform: translateX(0); }568  }569  @keyframes peach-slide-back {570    from { opacity: 0; transform: translateX(-12px); }571    to   { opacity: 1; transform: translateX(0); }572  }573  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }574  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }575576  /* Domain header */577  .domain-header {578    padding: 9px 13px 7px;579    border-bottom: 1px solid var(--peach-border);580    display: flex; align-items: center; justify-content: space-between;581    gap: 8px;582  }583  .domain-header-text {584    display: flex; flex-direction: column; gap: 2px;585    min-width: 0; flex: 1;586  }587  .domain-eyebrow {588    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;589    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;590  }591  .domain-name {592    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);593    font-family: "IBM Plex Mono", monospace;594    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;595  }596  .domain-add-btn {597    flex-shrink: 0;598    width: 22px; height: 22px;599    display: inline-flex; align-items: center; justify-content: center;600    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);601    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);602    border-radius: 6px;603    color: var(--peach-accent);604    cursor: pointer; padding: 0;605    transition: background 120ms, border-color 120ms, transform 80ms;606    font-family: "IBM Plex Mono", monospace;607    font-size: 14px; line-height: 1;608  }609  .domain-add-btn:hover {610    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);611    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);612    transform: scale(1.06);613  }614  .domain-add-btn:active { transform: scale(0.96); }615616  /* Search */617  .search-wrap {618    padding: 9px 12px 7px;619    border-bottom: 1px solid var(--peach-border);620  }621  .search {622    width: 100%; background: var(--peach-input-bg);623    border: 1px solid var(--peach-input-border);624    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;625    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;626    transition: border-color 120ms, box-shadow 120ms;627  }628  .search:focus {629    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);630    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);631  }632  .search::placeholder { color: var(--peach-text-muted); }633634  /* Results */635  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }636  .results::-webkit-scrollbar { display: none; }637638  /* Entry rows */639  .entry {640    display: flex; align-items: center; padding: 8px 12px;641    cursor: pointer; border-bottom: 1px solid var(--peach-border);642    transition: background 70ms; position: relative; outline: none;643  }644  .entry:last-child { border-bottom: none; }645  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }646  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }647  .entry.focused::before {648    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;649    width: 2px; border-radius: 2px;650    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);651  }652653  .entry-icon {654    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;655    background: var(--peach-input-bg); border: 1px solid var(--peach-border);656    display: flex; align-items: center; justify-content: center;657    overflow: hidden; margin-right: 10px;658  }659  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }660  .entry-icon.is-new {661    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);662    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);663    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);664  }665666  .entry-info { flex: 1; min-width: 0; }667  .entry-title {668    font-size: 12.5px; color: var(--peach-text);669    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;670    line-height: 1.3;671  }672  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }673  .entry-sub {674    font-size: 10px; color: var(--peach-text-dim);675    font-family: "IBM Plex Mono", monospace;676    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;677    margin-top: 1px;678  }679680  .totp-badge {681    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;682    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);683    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);684    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;685  }686  .passkey-badge {687    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;688    border-radius: 4px;689    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);690    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);691    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);692    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;693  }694695  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }696697  .empty-hint {698    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);699    font-family: "IBM Plex Mono", monospace;700  }701702  /* Create form */703  .create-form-wrap {704    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;705  }706  .create-head {707    display: flex; align-items: center; gap: 8px;708    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);709  }710  .back-btn {711    background: transparent; border: none; cursor: pointer;712    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;713    display: flex; align-items: center; line-height: 0;714    transition: color 100ms, background 100ms;715  }716  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }717  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }718  /* minmax(0, 1fr) caps the grid track at the popup width — without it,719     long monospace content (e.g. a 60-char generated password) would720     auto-size the track wider than the popup and overflow the right edge. */721  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }722  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }723  .f-label {724    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;725    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;726  }727  .f-input {728    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);729    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;730    font-size: 11px; font-family: "IBM Plex Mono", monospace;731    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;732  }733  .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); }734  .f-input::placeholder { color: var(--peach-text-muted); }735  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }736  .f-row { display: flex; gap: 6px; }737  .f-row .f-input { flex: 1; min-width: 0; }738  .gen-btn {739    padding: 0 10px; border-radius: 7px; border: none;740    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);741    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);742    font-size: 10px; font-family: "IBM Plex Mono", monospace;743    cursor: pointer; white-space: nowrap; flex-shrink: 0;744    display: flex; align-items: center; gap: 4px;745    transition: background 100ms;746  }747  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }748  .gen-toggle-link {749    background: none; border: none; padding: 2px 0;750    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);751    font-size: 10px; font-family: "IBM Plex Mono", monospace;752    cursor: pointer; text-align: left; transition: color 100ms;753  }754  .gen-toggle-link:hover { color: var(--peach-accent); }755  .save-btn {756    width: 100%; padding: 8px; border-radius: 8px; border: none;757    background: var(--peach-accent); color: #fff; font-size: 12px;758    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;759    transition: background 120ms, box-shadow 120ms, transform 80ms;760    letter-spacing: 0.01em;761  }762  .save-btn:hover {763    background: color-mix(in srgb, var(--peach-accent) 82%, #000);764    box-shadow: 0 4px 20px var(--peach-glow, transparent);765  }766  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }767  .url-hint {768    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);769    font-family: "IBM Plex Mono", monospace; font-style: italic;770  }771772  /* Success */773  .success-wrap {774    display: flex; flex-direction: column; align-items: center;775    padding: 24px 16px 20px; gap: 8px;776    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;777  }778  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }779  .success-ring {780    width: 40px; height: 40px; border-radius: 50%;781    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);782    display: flex; align-items: center; justify-content: center;783  }784  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }785  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }786787  /* Silver platter (State 1 — single match) */788  .silver-platter {789    padding: 14px 14px 12px;790    display: flex; flex-direction: column; gap: 6px;791  }792  .sp-title {793    font-size: 14px; font-weight: 500; color: var(--peach-text);794    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;795    line-height: 1.25;796  }797  .sp-identity-row {798    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;799  }800  .sp-identity-label {801    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;802    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;803  }804  .sp-username {805    font-size: 12px; color: var(--peach-text-dim);806    font-family: "IBM Plex Mono", monospace;807    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;808    margin-bottom: 0;809  }810  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }811  .sp-fill-btn {812    width: 100%; padding: 11px; border-radius: 9px; border: none;813    background: var(--peach-accent); color: #fff;814    font-size: 13px; font-weight: 500; cursor: pointer;815    font-family: Inter, sans-serif; letter-spacing: 0.01em;816    display: flex; align-items: center; justify-content: center; min-height: 38px;817    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;818  }819  .sp-fill-btn:hover {820    filter: brightness(1.1);821    box-shadow: 0 4px 20px var(--peach-glow, transparent);822    transform: translateY(-1px);823  }824  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }825  .sp-fill-btn.filled {826    background: #16a34a; transform: none; filter: none;827    box-shadow: 0 4px 16px rgba(22,163,74,0.35);828    cursor: default;829  }830  .sp-fill-btn:disabled { cursor: default; }831  .sp-actions {832    display: flex; gap: 4px; justify-content: space-between; align-items: center;833    margin-top: 4px;834  }835  .sp-action-btn {836    flex: 1; height: 28px; border: none; border-radius: 6px;837    background: transparent; color: var(--peach-text-dim);838    font-size: 12px; cursor: pointer;839    transition: background 120ms ease, color 120ms ease;840    font-family: Inter, sans-serif; letter-spacing: 0.04em;841    display: inline-flex; align-items: center; justify-content: center; gap: 4px;842    white-space: nowrap; overflow: hidden;843  }844  .sp-action-btn:hover:not(:disabled) {845    background: color-mix(in srgb, var(--peach-text) 5%, transparent);846    color: var(--peach-text);847  }848  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }849  .sp-action-btn.flashed {850    color: var(--peach-accent);851    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);852  }853854  /* TOTP tray — shown below the silver-platter secondary actions */855  .sp-tray {856    margin-top: 8px;857    padding: 10px 12px;858    border-radius: 9px;859    background: var(--peach-input-bg);860    border: 1px solid var(--peach-input-border);861    display: flex; align-items: center; gap: 12px;862    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;863  }864  .sp-tray-label {865    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;866    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;867    flex-shrink: 0;868  }869  .sp-totp-code {870    font-size: 18px; font-weight: 500;871    color: var(--peach-text);872    font-family: "IBM Plex Mono", monospace;873    letter-spacing: 0.12em;874    flex: 1;875    text-align: center;876  }877  .sp-totp-ring {878    width: 22px; height: 22px; flex-shrink: 0;879  }880  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }881  .sp-totp-ring .ring-fill {882    stroke: var(--peach-accent);883    transition: stroke-dashoffset 1s linear;884    transform: rotate(-90deg);885    transform-origin: center;886  }887  .sp-totp-copy {888    background: transparent; border: none; cursor: pointer;889    padding: 4px 8px; border-radius: 5px;890    color: var(--peach-text-dim); font-size: 11px;891    font-family: Inter, sans-serif;892    transition: background 120ms, color 120ms;893  }894  .sp-totp-copy:hover {895    background: color-mix(in srgb, var(--peach-text) 5%, transparent);896    color: var(--peach-text);897  }898899  /* Card silver platter (State 7) — reuses .sp-* primary action classes */900  .card-platter {901    padding: 12px 14px 10px;902    display: flex; flex-direction: column; gap: 4px;903  }904  .cp-network {905    font-size: 10px; font-weight: 600;906    color: var(--peach-accent);907    letter-spacing: 0.08em; text-transform: uppercase;908    font-family: Inter, sans-serif;909  }910  .cp-nickname {911    font-size: 14px; font-weight: 500; color: var(--peach-text);912    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;913    line-height: 1.2;914  }915  .cp-last4 {916    font-size: 12px; color: var(--peach-text-dim);917    font-family: "IBM Plex Mono", monospace;918    letter-spacing: 0.04em;919    margin-top: 2px;920  }921  .cp-meta {922    font-size: 11px; color: var(--peach-text-dim);923    font-family: "IBM Plex Mono", monospace;924    margin-top: 2px;925    display: flex; gap: 10px; align-items: center;926  }927  .cp-meta-sep { opacity: 0.5; }928  .cp-fill-wrap { margin-top: 10px; }929930  /* Locked state */931  .locked-wrap {932    display: flex; flex-direction: column; align-items: stretch;933    padding: 14px 13px 13px; gap: 9px;934  }935  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }936  .locked-icon {937    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;938    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);939    display: flex; align-items: center; justify-content: center;940  }941  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }942  .locked-input {943    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);944    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;945    font-size: 11px; font-family: "IBM Plex Mono", monospace;946    outline: none; transition: border-color 120ms, box-shadow 120ms;947  }948  .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); }949  .locked-input::placeholder { color: var(--peach-text-muted); }950  .locked-btn {951    width: 100%; padding: 8px; border-radius: 8px; border: none;952    background: var(--peach-accent); color: #fff; font-size: 12px;953    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;954    transition: background 120ms;955    letter-spacing: 0.01em;956    box-shadow: 0 2px 16px var(--peach-glow, transparent);957    animation: peach-pulse-glow 2.4s ease-in-out infinite;958  }959  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }960  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }961  .locked-error {962    font-size: 10px; color: rgba(220,80,60,0.85);963    font-family: "IBM Plex Mono", monospace;964  }965966  @keyframes peach-pulse-glow {967    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }968    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),969                            0 0 48px var(--peach-glow, transparent); }970  }971972  /* ── State 10: identity helper ─────────────────────────────── */973  .identity-list {974    max-height: 192px; overflow-y: auto; padding: 4px 0;975    scrollbar-width: none;976  }977  .identity-list::-webkit-scrollbar { display: none; }978  .peach-identity-row {979    display: flex; align-items: center; gap: 10px;980    padding: 9px 12px; cursor: pointer; border-radius: 8px;981    transition: background 100ms ease;982  }983  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }984  .peach-identity-value {985    font-family: "IBM Plex Mono", monospace; font-size: 13px;986    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;987  }988  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }989  .identity-alt-row {990    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;991    border-radius: 8px; transition: background 100ms ease;992    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;993  }994  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }995  .identity-escape-row {996    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;997    border-radius: 8px; transition: background 100ms ease; outline: none;998    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;999    margin-top: 2px;1000  }1001  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1002  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1003  .identity-alt-input-wrap.open { display: flex; }1004  .identity-alt-input {1005    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1006    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1007    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1008    outline: none; transition: border-color 120ms;1009  }1010  .identity-alt-input:focus {1011    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1012    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1013  }1014  .identity-alt-confirm {1015    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1016    background: var(--peach-accent); color: #fff; font-size: 12px;1017    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1018  }1019  /* ── Generator view (after identity picked) ────────────────── */1020  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1021  .gen-confirmed {1022    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1023    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1024    border-radius: 8px;1025  }1026  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1027  .gen-confirmed-val {1028    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1029    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1030  }1031  .gen-label {1032    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1033    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1034  }1035  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1036  .gen-pw-val {1037    flex: 1; padding: 8px 10px; border-radius: 7px;1038    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1039    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1040    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1041  }1042  .gen-regen-btn {1043    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1044    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1045    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1046    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1047  }1048  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1049  .gen-fill-btn {1050    padding: 10px; border-radius: 8px; border: none;1051    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1052    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1053    transition: filter 120ms ease, transform 80ms ease;1054  }1055  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1056  .gen-fill-btn:active { transform: translateY(0); }10571058  /* ── Smart password generator (parity with main UI compact mode) ─── */1059  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1060  .pwgen-display-row {1061    display: flex; align-items: center; gap: 6px;1062    padding: 8px 10px; border-radius: 7px;1063    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1064  }1065  .pwgen-output {1066    flex: 1; min-width: 0; width: 0;1067    font-family: "IBM Plex Mono", monospace; font-size: 12px;1068    color: var(--peach-text);1069    background: transparent; border: none; outline: none; padding: 0;1070  }1071  .pwgen-icon-btn {1072    flex-shrink: 0;1073    width: 26px; height: 26px;1074    display: inline-flex; align-items: center; justify-content: center;1075    background: transparent; border: 1px solid var(--peach-input-border);1076    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1077    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1078  }1079  .pwgen-icon-btn:hover {1080    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1081    color: var(--peach-accent);1082    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1083  }1084  .pwgen-icon-btn.is-copied {1085    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1086    color: var(--peach-accent);1087    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1088  }1089  .pwgen-controls-row {1090    display: flex; align-items: center; gap: 8px;1091    flex-wrap: wrap;1092  }1093  .pwgen-slider {1094    flex: 1; min-width: 110px;1095    accent-color: var(--peach-accent);1096    cursor: pointer; height: 2px; background: transparent;1097  }1098  .pwgen-len-num {1099    font-family: "IBM Plex Mono", monospace; font-size: 11px;1100    color: var(--peach-accent); min-width: 22px; text-align: right;1101  }1102  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1103  .pwgen-len-input {1104    font-family: "IBM Plex Mono", monospace; font-size: 11px;1105    color: var(--peach-accent); width: 28px; text-align: right;1106    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1107    outline: none; padding: 0; min-width: 22px;1108  }1109  @keyframes identity-suggest-in {1110    from { opacity: 0; transform: translateY(-4px); }1111    to   { opacity: 1; transform: none; }1112  }1113  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1114    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1115  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1116  .identity-collapse-btn {1117    margin-left: auto; background: transparent; border: none; cursor: pointer;1118    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1119    line-height: 0; border-radius: 3px;1120    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1121  }1122  .identity-collapse-btn:hover { color: var(--peach-text); }1123  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1124  .identity-rows { display: grid; grid-template-rows: 1fr;1125    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1126  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1127  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1128    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1129    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1130    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1131  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1132  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1133  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1134  .identity-filter-pill {1135    padding: 2px 7px; border-radius: 999px;1136    border: 1px solid var(--peach-input-border);1137    background: transparent; color: var(--peach-text-muted);1138    font-family: "IBM Plex Mono", monospace; font-size: 9px;1139    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1140  }1141  .identity-filter-pill.is-on {1142    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1143    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1144    color: var(--peach-accent);1145  }1146  .identity-suggest-row {1147    display: flex; align-items: center; gap: 5px;1148    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1149    background: transparent; cursor: pointer; text-align: left;1150    transition: background 80ms;1151  }1152  .identity-suggest-row:hover,1153  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1154  .identity-suggest-val {1155    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1156    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1157  }1158  .identity-suggest-type {1159    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1160    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1161  }1162  .identity-suggest-type--email {1163    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1164    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1165  }1166  .identity-suggest-type--username {1167    color: var(--peach-text-muted);1168    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1169  }1170  .identity-suggest-meta {1171    font-family: "IBM Plex Mono", monospace; font-size: 9px;1172    color: var(--peach-text-muted); flex-shrink: 0;1173  }1174  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1175  .pwgen-pill {1176    padding: 3px 8px; border-radius: 999px;1177    border: 1px solid var(--peach-input-border);1178    background: transparent; color: var(--peach-text-muted);1179    font-family: "IBM Plex Mono", monospace; font-size: 9px;1180    letter-spacing: 0.06em; cursor: pointer;1181    transition: all 130ms ease;1182  }1183  .pwgen-pill.is-on {1184    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1185    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1186    color: var(--peach-accent);1187  }1188  .pwgen-pill:not(.is-on):hover {1189    color: var(--peach-text-dim);1190    border-color: var(--peach-text-muted);1191  }1192  .pwgen-policy-hint {1193    font-size: 10px; color: var(--peach-text-muted);1194    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1195    line-height: 1.3;1196  }1197  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11981199  /* ── Save offer (after password filled) ───────────────────── */1200  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1201  .save-offer-title {1202    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1203  }1204  .save-offer-row {1205    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1206    border-radius: 7px; background: var(--peach-input-bg);1207    border: 1px solid var(--peach-input-border);1208  }1209  .save-offer-lbl {1210    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1211    font-family: "IBM Plex Mono", monospace;1212  }1213  .save-offer-val {1214    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1215    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1216  }1217  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1218  .save-offer-save {1219    flex: 1; padding: 9px; border-radius: 8px; border: none;1220    background: var(--peach-accent); color: #fff; font-size: 13px;1221    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1222  }1223  .save-offer-save:hover { filter: brightness(1.08); }1224  .save-offer-skip {1225    flex: 1; padding: 9px; border-radius: 8px; border: none;1226    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1227    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1228    font-family: Inter, sans-serif; transition: background 100ms ease;1229  }1230  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1231`;12321233export function showAutofillSelector(1234  anchorEl: HTMLInputElement,1235  entries: SelectorEntry[],1236  onSelect: (id: string) => void,1237  options: SelectorOptions = {}1238): () => void {1239  const host = document.createElement("div");1240  host.style.cssText = "position: absolute; z-index: 2147483647;";1241  host.style.setProperty("--peach-accent", accentHex);1242  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1243  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1244  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1245  const shadow = host.attachShadow({ mode: "closed" });12461247  const style = shadow.appendChild(document.createElement("style"));1248  style.textContent = SELECTOR_STYLES;12491250  const rect = anchorEl.getBoundingClientRect();1251  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1252  host.style.left = `${rect.left + window.scrollX}px`;1253  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1254  // wide single-input fields (e.g. centered email input on signup pages).1255  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1256  // expand the host after the initial measurement.1257  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1258  host.style.width = `${popupWidth}px`;12591260  const container = shadow.appendChild(document.createElement("div"));1261  container.className = "peach-inline-popup";1262  container.setAttribute("data-theme", popupTheme);12631264  const searchableEntries = options.searchableEntries ?? [];1265  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12661267  let query = "";1268  let focusedIndex = -1;1269  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1270  let searchInput: HTMLInputElement | null = null;1271  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1272  // setInterval. Add to this list — don't fan out the dismiss function.1273  const cleanupHooks: Array<() => void> = [];12741275  // Smooth height transitions whenever content changes height.1276  // ResizeObserver fires on natural height changes; we freeze the old height,1277  // then animate to the new one so the surface never jumps.1278  {1279    let prevH = 0;1280    let blocked = false;1281    const heightRo = new ResizeObserver(([entry]) => {1282      if (blocked) return;1283      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1284      if (prevH > 0 && Math.abs(h - prevH) > 1) {1285        blocked = true;1286        container.style.height = `${prevH}px`;1287        requestAnimationFrame(() => requestAnimationFrame(() => {1288          container.style.height = `${h}px`;1289          prevH = h;1290          const onEnd = (e: TransitionEvent) => {1291            if (e.propertyName !== "height") return;1292            container.style.height = "";1293            blocked = false;1294            container.removeEventListener("transitionend", onEnd);1295          };1296          container.addEventListener("transitionend", onEnd);1297        }));1298      } else {1299        prevH = h;1300      }1301    });1302    heightRo.observe(container);1303    cleanupHooks.push(() => heightRo.disconnect());1304  }13051306  // Pre-capture the anchor field value for username prefill1307  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1308  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1309  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13101311  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1312    const seen = new Set<string>();1313    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1314  }13151316  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1317    const q = value.trim().toLowerCase();1318    const deduped = uniqueEntries(source);1319    if (!q) return deduped.slice(0, 8);1320    return deduped.filter(e =>1321      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1322    ).slice(0, 12);1323  }13241325  function activeEntries(): SelectorEntry[] {1326    // When user is typing a search, filter across all known entries (domain matches + vault)1327    if (query.trim()) {1328      const merged = uniqueEntries([...entries, ...searchableEntries]);1329      return filterEntries(merged, query);1330    }1331    // Default: show domain matches; fall back to vault search when no matches1332    if (entries.length > 0) return entries;1333    return filterEntries(searchableEntries, "").slice(0, 8);1334  }13351336  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1337    const icon = document.createElement("div");1338    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1339    if (isNew) {1340      icon.innerHTML = plusSvgStr();1341    } else {1342      // Use the generic key glyph for all entries in the page-injected selector.1343      // Avoids disclosing vault domains to any third party and avoids needing1344      // to expose the browser favicon API to page context via web_accessible_resources.1345      void url;1346      icon.innerHTML = keySvgStr();1347    }1348    return icon;1349  }13501351  function renderIdentityHelper() {1352    container.innerHTML = "";1353    const identities = options.savedIdentities ?? [];13541355    // Header: "NEW ACCOUNT" + domain name1356    const hdr = container.appendChild(document.createElement("div"));1357    hdr.className = "domain-header";1358    const eyebrow = hdr.appendChild(document.createElement("div"));1359    eyebrow.className = "domain-eyebrow";1360    eyebrow.textContent = "NEW ACCOUNT";1361    const domName = hdr.appendChild(document.createElement("div"));1362    domName.className = "domain-name";1363    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13641365    // Identity rows1366    const list = container.appendChild(document.createElement("div"));1367    list.className = "identity-list";1368    for (const id of identities) {1369      const row = list.appendChild(document.createElement("div"));1370      row.className = "peach-identity-row";1371      row.setAttribute("tabindex", "-1");1372      const val = row.appendChild(document.createElement("div"));1373      val.className = "peach-identity-value";1374      val.textContent = id.value;1375      const meta = row.appendChild(document.createElement("div"));1376      meta.className = "peach-identity-meta";1377      meta.textContent = `used ${id.useCount}×`;1378      row.addEventListener("click", () => {1379        options.onFillFields?.(id.value, "");1380        renderGenerator(id.value);1381      });1382    }13831384    // Divider before "Use a different email…"1385    if (identities.length > 0) {1386      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1387    }13881389    // "Use a different email…" expandable row1390    const altRow = container.appendChild(document.createElement("div"));1391    altRow.className = "identity-alt-row";1392    altRow.textContent = "+ Use a different email…";13931394    const altInputWrap = container.appendChild(document.createElement("div"));1395    altInputWrap.className = "identity-alt-input-wrap";1396    const altInput = altInputWrap.appendChild(document.createElement("input"));1397    altInput.className = "identity-alt-input";1398    altInput.type = "email";1399    altInput.placeholder = "[email protected]";1400    altInput.setAttribute("autocomplete", "off");1401    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1402    altConfirm.className = "identity-alt-confirm";1403    altConfirm.type = "button";1404    altConfirm.textContent = "✓";14051406    function fillCustomEmail() {1407      const v = altInput.value.trim();1408      if (!v) return;1409      options.onFillFields?.(v, "");1410      renderGenerator(v);1411    }14121413    altRow.addEventListener("click", () => {1414      altRow.style.display = "none";1415      altInputWrap.classList.add("open");1416      altInput.focus();1417    });1418    altConfirm.addEventListener("click", fillCustomEmail);1419    altInput.addEventListener("keydown", (e) => {1420      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1421    });14221423    // Escape hatch: user already has a vault entry for this site but it1424    // wasn't detected (different domain, old entry, etc.). Tapping this1425    // switches to the full searchable list so they can find and fill it;1426    // selecting an entry there will trigger the remember-site toast if1427    // the domain isn't already associated.1428    if ((options.searchableEntries?.length ?? 0) > 0) {1429      const escapeRow = container.appendChild(document.createElement("div"));1430      escapeRow.className = "identity-escape-row";1431      escapeRow.textContent = "I already have an account →";1432      escapeRow.setAttribute("tabindex", "0");1433      escapeRow.addEventListener("click", () => renderList());1434      escapeRow.addEventListener("keydown", (e) => {1435        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1436      });1437    }1438  }14391440  function renderGenerator(filledEmail: string) {1441    container.innerHTML = "";1442    const sitePolicy = detectPasswordPolicy();14431444    const wrap = container.appendChild(document.createElement("div"));1445    wrap.className = "gen-view";14461447    // Header: domain + NEW ACCOUNT1448    const hdrRow = wrap.appendChild(document.createElement("div"));1449    hdrRow.className = "domain-header";1450    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1451    eyebrow2.className = "domain-eyebrow";1452    eyebrow2.textContent = "NEW ACCOUNT";1453    const domName2 = hdrRow.appendChild(document.createElement("div"));1454    domName2.className = "domain-name";1455    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14561457    // Confirmed email row1458    const conf = wrap.appendChild(document.createElement("div"));1459    conf.className = "gen-confirmed";1460    const confCheck = conf.appendChild(document.createElement("span"));1461    confCheck.className = "gen-confirmed-check";1462    confCheck.textContent = "✓";1463    const confVal = conf.appendChild(document.createElement("div"));1464    confVal.className = "gen-confirmed-val";1465    confVal.textContent = filledEmail;14661467    const lbl = wrap.appendChild(document.createElement("div"));1468    lbl.className = "gen-label";1469    lbl.textContent = "Generate a password";14701471    let currentPw = "";1472    const smartGen = createSmartGenerator({1473      policy: sitePolicy,1474      onChange: (pw) => { currentPw = pw; },1475    });1476    wrap.appendChild(smartGen.root);14771478    const fillBtn = wrap.appendChild(document.createElement("button"));1479    fillBtn.className = "gen-fill-btn";1480    fillBtn.type = "button";1481    fillBtn.textContent = "Copy & fill";1482    fillBtn.addEventListener("click", () => {1483      if (!currentPw) return;1484      options.onFillFields?.("", currentPw);1485      renderSaveOffer(filledEmail, currentPw);1486    });1487  }14881489  function renderSaveOffer(filledEmail: string, filledPassword: string) {1490    container.innerHTML = "";1491    const domain = options.domain ?? location.hostname.replace(/^www\./, "");14921493    const wrap = container.appendChild(document.createElement("div"));1494    wrap.className = "save-offer";14951496    const title = wrap.appendChild(document.createElement("div"));1497    title.className = "save-offer-title";1498    title.textContent = "Save this login to Peach?";14991500    function detailRow(label: string, value: string) {1501      const row = wrap.appendChild(document.createElement("div"));1502      row.className = "save-offer-row";1503      const lbl = row.appendChild(document.createElement("div"));1504      lbl.className = "save-offer-lbl";1505      lbl.textContent = label;1506      const val = row.appendChild(document.createElement("div"));1507      val.className = "save-offer-val";1508      val.textContent = value;1509    }15101511    detailRow("site", domain);1512    detailRow("email", filledEmail);1513    detailRow("password", "••••••••••••••••");15141515    const btns = wrap.appendChild(document.createElement("div"));1516    btns.className = "save-offer-btns";15171518    const saveBtn = btns.appendChild(document.createElement("button"));1519    saveBtn.className = "save-offer-save";1520    saveBtn.type = "button";1521    saveBtn.textContent = "Save";1522    saveBtn.addEventListener("click", async () => {1523      saveBtn.disabled = true;1524      saveBtn.textContent = "Saving…";1525      try {1526        const res = await chrome.runtime.sendMessage({1527          type: "ADD_ENTRY",1528          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1529        });1530        if ((res as { ok?: boolean }).ok) {1531          showSuccess(sTitle);1532        } else {1533          saveBtn.disabled = false;1534          saveBtn.textContent = "Save";1535        }1536      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1537    });15381539    const skipBtn = btns.appendChild(document.createElement("button"));1540    skipBtn.className = "save-offer-skip";1541    skipBtn.type = "button";1542    skipBtn.textContent = "Not now";1543    skipBtn.addEventListener("click", () => { dismiss(true); });1544  }15451546  function renderList() {1547    container.innerHTML = "";1548    focusedIndex = -1;1549    searchInput = null;15501551    const current = activeEntries();15521553    // Domain header (always show) — eyebrow + domain on the left,1554    // a "+" shortcut to the create form on the right so the user is never1555    // trapped in the search list when they want to make a new entry.1556    const domHdr = document.createElement("div");1557    domHdr.className = "domain-header";1558    const headText = document.createElement("div");1559    headText.className = "domain-header-text";1560    const eyebrow = document.createElement("div");1561    eyebrow.className = "domain-eyebrow";1562    eyebrow.textContent = options.isSignup1563      ? "Sign up as"1564      : entries.length > 0 ? "Saved for this site" : "No saved login";1565    const domName = document.createElement("div");1566    domName.className = "domain-name";1567    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1568    headText.append(eyebrow, domName);1569    domHdr.appendChild(headText);15701571    if (!options.isSignup) {1572      const addBtn = document.createElement("button");1573      addBtn.className = "domain-add-btn";1574      addBtn.type = "button";1575      addBtn.setAttribute("aria-label", "Create new entry");1576      addBtn.title = "Create new entry";1577      addBtn.textContent = "+";1578      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1579      domHdr.appendChild(addBtn);1580    }15811582    container.appendChild(domHdr);15831584    // Search — always show so user can find entries beyond the domain matches1585    const sw = document.createElement("div"); sw.className = "search-wrap";1586    searchInput = document.createElement("input");1587    searchInput.className = "search";1588    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1589    searchInput.value = query;1590    searchInput.addEventListener("input", () => {1591      query = searchInput?.value ?? "";1592      renderList();1593      searchInput?.focus();1594      searchInput?.setSelectionRange(query.length, query.length);1595    });1596    sw.appendChild(searchInput);1597    container.appendChild(sw);15981599    // Results1600    const results = document.createElement("div");1601    results.className = "results";1602    container.appendChild(results);16031604    if (current.length === 0 && entries.length > 0) {1605      // Show a hint but don't render empty entries1606    }16071608    for (let i = 0; i < current.length; i++) {1609      const e = current[i]!;1610      const entryEl = document.createElement("div");1611      entryEl.className = "entry";1612      entryEl.dataset.id = e.id;1613      entryEl.dataset.index = String(i);1614      entryEl.setAttribute("tabindex", "-1");16151616      entryEl.appendChild(makeEntryIcon(e.url));16171618      const info = document.createElement("div"); info.className = "entry-info";1619      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1620      const subEl = document.createElement("div"); subEl.className = "entry-sub";1621      const domain = e.url ? getDomainFromUrl(e.url) : "";1622      subEl.textContent = domain || e.username || "";1623      info.append(titleEl, subEl);1624      entryEl.appendChild(info);16251626      if (e.hasTotp) {1627        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1628        entryEl.appendChild(badge);1629      }1630      if (e.hasPasskey) {1631        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1632        entryEl.appendChild(badge);1633      }16341635      entryEl.addEventListener("click", () => {1636        if (options.isSignup && options.onFillFields) {1637          // Signup mode: clicking a saved identity fills the username field1638          options.onFillFields(e.username ?? "", "");1639          dismiss();1640        } else {1641          onSelect(e.id);1642          dismiss();1643        }1644      });1645      results.appendChild(entryEl);1646    }16471648    // Divider before "New entry"1649    if (current.length > 0) {1650      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1651    }16521653    // "New entry" row — always present1654    const newEl = document.createElement("div");1655    newEl.className = "entry";1656    newEl.setAttribute("tabindex", "-1");1657    newEl.appendChild(makeEntryIcon(undefined, true));16581659    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1660    const newTitle = document.createElement("div");1661    newTitle.className = "entry-title is-new";1662    newTitle.textContent = `New entry for ${sTitle}`;1663    const newSub = document.createElement("div");1664    newSub.className = "entry-sub";1665    newSub.textContent = sOrigin;1666    newInfo.append(newTitle, newSub);1667    newEl.appendChild(newInfo);1668    newEl.addEventListener("click", showCreateForm);1669    results.appendChild(newEl);16701671    // Focus search if present1672    if (searchInput) {1673      requestAnimationFrame(() => searchInput?.focus());1674    }1675  }16761677  function setFocused(idx: number) {1678    const all = container.querySelectorAll<HTMLElement>(".entry");1679    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1680    focusedIndex = idx;1681    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1682  }16831684  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1685    const typed = identities.filter(s => s.type === fieldType);1686    if (!typed.length) return;1687    let collapsed = false;1688    let suppressNextFocus = false;16891690    const list = g.appendChild(document.createElement("div"));1691    list.className = "identity-suggest-list";1692    list.style.display = "none";16931694    // Collapse toggle — sits alone now that filter pills are gone1695    const collapseRow = list.appendChild(document.createElement("div"));1696    collapseRow.className = "identity-filter-row";1697    collapseRow.style.justifyContent = "flex-end";1698    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1699    collapseBtn.type = "button";1700    collapseBtn.className = "identity-collapse-btn";1701    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>`;1702    collapseBtn.addEventListener("mousedown", (e) => {1703      e.preventDefault();1704      collapsed = !collapsed;1705      collapseBtn.classList.toggle("is-collapsed", collapsed);1706      rowsWrapper.classList.toggle("is-collapsed", collapsed);1707    });17081709    const rowsWrapper = list.appendChild(document.createElement("div"));1710    rowsWrapper.className = "identity-rows";1711    const rows = rowsWrapper.appendChild(document.createElement("div"));1712    rows.className = "identity-rows-inner";17131714    function pick(value: string) {1715      inp.value = value;1716      list.style.display = "none";1717      suppressNextFocus = true;1718      inp.focus();1719    }17201721    function render() {1722      const q = inp.value.toLowerCase();1723      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1724      rows.innerHTML = "";1725      if (!filtered.length) { list.style.display = "none"; return; }1726      for (const s of filtered) {1727        const row = rows.appendChild(document.createElement("button"));1728        row.type = "button"; row.className = "identity-suggest-row";1729        const val = row.appendChild(document.createElement("span"));1730        val.className = "identity-suggest-val"; val.textContent = s.value;1731        const meta = row.appendChild(document.createElement("span"));1732        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1733        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1734        row.addEventListener("keydown", (e) => {1735          if (e.key === "ArrowDown") {1736            e.preventDefault();1737            (row.nextElementSibling as HTMLElement | null)?.focus();1738          } else if (e.key === "ArrowUp") {1739            e.preventDefault();1740            const prev = row.previousElementSibling as HTMLElement | null;1741            if (prev) prev.focus();1742            else inp.focus();1743          } else if (e.key === "Enter" || e.key === " ") {1744            e.preventDefault();1745            pick(s.value);1746          } else if (e.key === "Escape") {1747            e.preventDefault();1748            list.style.display = "none";1749            suppressNextFocus = true;1750            inp.focus();1751          }1752        });1753        row.addEventListener("blur", (e) => {1754          const rt = (e as FocusEvent).relatedTarget as Node | null;1755          if (rt && (rt === inp || list.contains(rt))) return;1756          setTimeout(() => { list.style.display = "none"; }, 150);1757        });1758      }1759      list.style.display = "";1760    }17611762    inp.addEventListener("focus", () => {1763      if (suppressNextFocus) { suppressNextFocus = false; return; }1764      render();1765    });1766    inp.addEventListener("input", render);1767    inp.addEventListener("keydown", (e) => {1768      if (list.style.display === "none") return;1769      if (e.key === "ArrowDown" && !collapsed) {1770        e.preventDefault();1771        (rows.firstElementChild as HTMLElement | null)?.focus();1772      } else if (e.key === "Escape") {1773        e.preventDefault();1774        list.style.display = "none";1775      }1776    });1777    inp.addEventListener("blur", (e) => {1778      const rt = (e as FocusEvent).relatedTarget as Node | null;1779      if (rt && list.contains(rt)) return;1780      setTimeout(() => { list.style.display = "none"; }, 150);1781    });1782  }17831784  async function showCreateForm() {1785    currentMode = "create";1786    container.innerHTML = "";17871788    // Guard: the service worker may lock the vault between when the selector1789    // opens and when the user clicks "New entry". Show the inline unlock form1790    // instead of silently failing on save.1791    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1792    if (!statusRes?.unlocked) {1793      renderLocked();1794      return;1795    }17961797    // Detect page password policy once for this form — reused on every1798    // regenerate click so the user always gets a compliant password.1799    const sitePolicy = detectPasswordPolicy();18001801    // Fetch identities on-demand — they're passed in signup context but not1802    // in login/search context where the user still clicks "New entry".1803    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1804    if (!formIdentities.length) {1805      try {1806        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1807        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1808      } catch { /* silent fallback */ }1809    }18101811    const wrap = document.createElement("div");1812    wrap.className = "create-form-wrap";18131814    // Header1815    const head = document.createElement("div"); head.className = "create-head";1816    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1817    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>`;1818    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1819    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1820    head.append(backBtn, lbl);18211822    // Body1823    const body = document.createElement("div"); body.className = "create-body";18241825    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1826      const g = document.createElement("div"); g.className = "f-group";1827      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1828      const inp = document.createElement("input"); inp.className = "f-input";1829      g.append(l, inp); return { g, inp };1830    }18311832    // Title1833    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1834    body.appendChild(tg.g);18351836    // URL1837    const ug = fGroup("website");1838    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1839    if (loginSubdomain) {1840      const h = document.createElement("div"); h.className = "url-hint";1841      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1842    }1843    body.appendChild(ug.g);18441845    // Username — pre-fill from anchor if it doesn't look like an email1846    const xg = fGroup("username");1847    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1848    xg.inp.placeholder = "johndoe";1849    xg.inp.setAttribute("autocomplete", "off");1850    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1851    body.appendChild(xg.g);18521853    // Email — pre-fill from anchor if it looks like an email1854    const eg = fGroup("email");1855    (eg.inp as HTMLInputElement).type = "email";1856    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1857    eg.inp.placeholder = "[email protected]";1858    eg.inp.setAttribute("autocomplete", "off");1859    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1860    body.appendChild(eg.g);18611862    // Password — full smart generator with charset pills + length slider +1863    // policy hint. Mirrors the main UI's compact generator so users get the1864    // same controls inline as in the popup.1865    const pg = fGroup("password");1866    pg.inp.remove(); // smartGen provides its own display — no separate input needed1867    let currentPassword = prePassword || "";1868    const smartGen = createSmartGenerator({1869      policy: sitePolicy,1870      initialPassword: prePassword || undefined,1871      onChange: (pw) => { currentPassword = pw; },1872    });1873    pg.g.appendChild(smartGen.root);1874    body.appendChild(pg.g);18751876    // Save1877    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1878    saveBtn.textContent = "Save entry";1879    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1880    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1881    saveBtn.addEventListener("click", async () => {1882      const title = tg.inp.value.trim();1883      const pw = currentPassword.trim();1884      const username = xg.inp.value.trim();1885      const email = eg.inp.value.trim();1886      if (!title) {1887        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1888        showFormError("Entry needs a title");1889        return;1890      }1891      if (!pw) {1892        showFormError("Entry needs a password — tap regen to make one");1893        return;1894      }1895      errEl.style.display = "none";1896      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1897      try {1898        const res = await chrome.runtime.sendMessage({1899          type: "ADD_ENTRY",1900          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1901        });1902        if ((res as { ok?: boolean }).ok) {1903          // Fill the detected form. onFillFields uses whichever identity the1904          // page anchored on — the vault captures both username and email.1905          options.onFillFields?.(username || email, pw);1906          showSuccess(title);1907        } else {1908          const errMsg = (res as { error?: string }).error === "vault locked"1909            ? "Vault locked — open Peach to save"1910            : "Could not save entry";1911          showFormError(errMsg);1912          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1913        }1914      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1915    });1916    body.appendChild(saveBtn);1917    body.appendChild(errEl);19181919    wrap.append(head, body);1920    container.appendChild(wrap);1921    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1922  }19231924  function showSuccess(title: string) {1925    currentMode = "success";1926    container.innerHTML = "";1927    const wrap = document.createElement("div"); wrap.className = "success-wrap";1928    const ring = document.createElement("div"); ring.className = "success-ring";1929    ring.innerHTML = checkSvgStr();1930    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1931    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1932    wrap.append(ring, t, s);1933    container.appendChild(wrap);1934    setTimeout(() => dismiss(), 1600);1935  }19361937  function flashActionBtn(btn: HTMLButtonElement) {1938    btn.classList.add("flashed");1939    setTimeout(() => btn.classList.remove("flashed"), 700);1940  }19411942  // M3/QUA-005: when both the direct clipboard write and the background COPY1943  // fallback fail, briefly show the user that the copy did not happen.1944  function flashCopyError(btn: HTMLButtonElement) {1945    const original = btn.textContent ?? "";1946    btn.textContent = "Blocked";1947    btn.classList.add("flashed");1948    setTimeout(() => {1949      btn.classList.remove("flashed");1950      if (btn.isConnected) btn.textContent = original;1951    }, 1200);1952  }19531954  function renderSilverPlatter(entry: SelectorEntry) {1955    container.innerHTML = "";1956    searchInput = null;1957    focusedIndex = -1;1958    currentMode = "silver-platter";19591960    const domHdr = document.createElement("div");1961    domHdr.className = "domain-header";1962    const headText = document.createElement("div");1963    headText.className = "domain-header-text";1964    const eyebrow = document.createElement("div");1965    eyebrow.className = "domain-eyebrow";1966    eyebrow.textContent = "Saved for this site";1967    const domName = document.createElement("div");1968    domName.className = "domain-name";1969    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1970    headText.append(eyebrow, domName);1971    domHdr.appendChild(headText);1972    if (!options.isSignup) {1973      const addBtn = document.createElement("button");1974      addBtn.className = "domain-add-btn";1975      addBtn.type = "button";1976      addBtn.setAttribute("aria-label", "Create new entry");1977      addBtn.title = "Create new entry";1978      addBtn.textContent = "+";1979      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1980      domHdr.appendChild(addBtn);1981    }1982    container.appendChild(domHdr);19831984    const platter = document.createElement("div");1985    platter.className = "silver-platter";19861987    const titleEl = document.createElement("div");1988    titleEl.className = "sp-title";1989    titleEl.textContent = entry.title;1990    platter.appendChild(titleEl);19911992    if (entry.email) {1993      const emailEl = document.createElement("div");1994      emailEl.className = "sp-identity-row";1995      const emailLbl = document.createElement("span");1996      emailLbl.className = "sp-identity-label";1997      emailLbl.textContent = "email";1998      const emailVal = document.createElement("span");1999      emailVal.className = "sp-username";2000      emailVal.textContent = entry.email;2001      emailEl.append(emailLbl, emailVal);2002      platter.appendChild(emailEl);2003    }20042005    if (entry.username) {2006      const userEl = document.createElement("div");2007      userEl.className = "sp-identity-row";2008      const userLbl = document.createElement("span");2009      userLbl.className = "sp-identity-label";2010      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2011      const userVal = document.createElement("span");2012      userVal.className = "sp-username";2013      userVal.textContent = entry.username;2014      userEl.append(userLbl, userVal);2015      platter.appendChild(userEl);2016    }20172018    const fillBtn = document.createElement("button");2019    fillBtn.className = "sp-fill-btn";2020    fillBtn.type = "button";2021    fillBtn.textContent = "Fill credentials";2022    fillBtn.addEventListener("click", () => {2023      if (fillBtn.disabled) return;2024      fillBtn.disabled = true;2025      fillBtn.classList.add("filled");2026      fillBtn.innerHTML = checkSvgStr();2027      // Fire the fill, then exit via the standard exit animation. The fill2028      // itself is async (handled in index.ts) — by 400ms the form is filled2029      // and the popup begins its exit. Total dwell from click to host2030      // removal: 400ms + 130ms (exit animation) = 530ms.2031      onSelect(entry.id);2032      setTimeout(() => dismiss(), 400);2033    });2034    platter.appendChild(fillBtn);20352036    const actions = document.createElement("div");2037    actions.className = "sp-actions";20382039    if (entry.email) {2040      const copyEmail = document.createElement("button");2041      copyEmail.className = "sp-action-btn";2042      copyEmail.type = "button";2043      copyEmail.title = "Copy email";2044      copyEmail.textContent = "Copy email";2045      copyEmail.addEventListener("click", async (e) => {2046        e.stopPropagation();2047        let alreadyWritten = false;2048        try {2049          await navigator.clipboard.writeText(entry.email!);2050          alreadyWritten = true;2051        } catch (err) {2052          console.warn("[Peach] clipboard write denied:", err);2053        }2054        const resp = await chrome.runtime.sendMessage({2055          type: "COPY",2056          payload: { text: entry.email, label: "Email", alreadyWritten },2057        }).catch(() => null) as { ok?: boolean } | null;2058        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2059        else flashCopyError(copyEmail);2060      });2061      actions.appendChild(copyEmail);2062    }20632064    const copyU = document.createElement("button");2065    copyU.className = "sp-action-btn";2066    copyU.type = "button";2067    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";2068    copyU.title = copyULabel;2069    copyU.textContent = copyULabel;2070    copyU.disabled = !entry.username;2071    copyU.addEventListener("click", async (e) => {2072      e.stopPropagation();2073      if (!entry.username) return;2074      let alreadyWritten = false;2075      try {2076        await navigator.clipboard.writeText(entry.username);2077        alreadyWritten = true;2078      } catch (err) {2079        console.warn("[Peach] clipboard write denied:", err);2080      }2081      const resp = await chrome.runtime.sendMessage({2082        type: "COPY",2083        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2084      }).catch(() => null) as { ok?: boolean } | null;2085      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2086      else flashCopyError(copyU);2087    });2088    actions.appendChild(copyU);20892090    const copyP = document.createElement("button");2091    copyP.className = "sp-action-btn";2092    copyP.type = "button";2093    copyP.title = "Copy password";2094    copyP.textContent = "Copy password";2095    copyP.addEventListener("click", async (e) => {2096      e.stopPropagation();2097      const resp = await chrome.runtime.sendMessage({2098        type: "GET_ENTRY_FOR_FILL",2099        payload: { id: entry.id },2100      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2101      if (!resp?.ok || !resp.data?.password) return;2102      let alreadyWritten = false;2103      try {2104        await navigator.clipboard.writeText(resp.data.password);2105        alreadyWritten = true;2106      } catch (err) {2107        console.warn("[Peach] clipboard write denied:", err);2108      }2109      const copyResp = await chrome.runtime.sendMessage({2110        type: "COPY",2111        payload: { text: resp.data.password, label: "Password", alreadyWritten },2112      }).catch(() => null) as { ok?: boolean } | null;2113      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2114      else flashCopyError(copyP);2115    });2116    actions.appendChild(copyP);21172118    let trayEl: HTMLDivElement | null = null;2119    let trayInterval: ReturnType<typeof setInterval> | null = null;21202121    function closeTray() {2122      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2123      trayEl?.remove();2124      trayEl = null;2125    }2126    // Register so dismiss() will close the tray and clear the interval2127    // even if the user dismisses without explicitly closing the tray.2128    cleanupHooks.push(closeTray);21292130    async function openTOTPTray() {2131      // Fetch the entry to get the TOTP secret. The selector summary doesn't2132      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2133      // the message-passing surface minimal per Projects.md §5.2).2134      const resp = await chrome.runtime.sendMessage({2135        type: "GET_ENTRY_FOR_FILL",2136        payload: { id: entry.id },2137      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2138      const secret = resp?.ok ? resp.data?.totp : undefined;2139      if (!secret) return;21402141      trayEl = document.createElement("div");2142      trayEl.className = "sp-tray";21432144      const label = document.createElement("span");2145      label.className = "sp-tray-label";2146      label.textContent = "2FA";2147      trayEl.appendChild(label);21482149      const codeEl = document.createElement("div");2150      codeEl.className = "sp-totp-code";2151      trayEl.appendChild(codeEl);21522153      const ringNs = "http://www.w3.org/2000/svg";2154      const ring = document.createElementNS(ringNs, "svg");2155      ring.setAttribute("class", "sp-totp-ring");2156      ring.setAttribute("viewBox", "0 0 24 24");2157      const trackC = document.createElementNS(ringNs, "circle");2158      trackC.setAttribute("class", "ring-track");2159      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2160      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2161      const fillC = document.createElementNS(ringNs, "circle");2162      fillC.setAttribute("class", "ring-fill");2163      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2164      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2165      fillC.setAttribute("stroke-linecap", "round");2166      fillC.setAttribute("stroke-dasharray", "62.83");2167      ring.append(trackC, fillC);2168      trayEl.appendChild(ring);21692170      const copyBtn = document.createElement("button");2171      copyBtn.className = "sp-totp-copy";2172      copyBtn.type = "button";2173      copyBtn.textContent = "Copy";2174      trayEl.appendChild(copyBtn);21752176      function refresh() {2177        const { code, remaining } = generateTOTP(secret!);2178        // Group as "847 291" — easier to read than "847291"2179        codeEl.textContent = code.length === 62180          ? `${code.slice(0, 3)} ${code.slice(3)}`2181          : code;2182        // Ring fills counter-clockwise as time elapses: dashoffset goes from2183        // 0 (full ring) to 62.83 (empty) over the 30s window.2184        const fraction = (30 - remaining) / 30;2185        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2186      }2187      refresh();2188      trayInterval = setInterval(refresh, 1000);21892190      copyBtn.addEventListener("click", async (e) => {2191        e.stopPropagation();2192        const { code } = generateTOTP(secret!);2193        let alreadyWritten = false;2194        try {2195          await navigator.clipboard.writeText(code);2196          alreadyWritten = true;2197        } catch (err) {2198          console.warn("[Peach] clipboard write denied:", err);2199        }2200        const resp = await chrome.runtime.sendMessage({2201          type: "COPY",2202          payload: { text: code, label: "TOTP", alreadyWritten },2203        }).catch(() => null) as { ok?: boolean } | null;2204        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2205        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2206      });22072208      platter.appendChild(trayEl);2209    }22102211    const editBtn = document.createElement("button");2212    editBtn.className = "sp-action-btn sp-action-edit";2213    editBtn.type = "button";2214    editBtn.title = "Edit entry";2215    editBtn.textContent = "Edit";2216    editBtn.addEventListener("click", (e) => {2217      e.stopPropagation();2218      closeTray();2219      void renderInlineEdit(entry);2220    });2221    actions.appendChild(editBtn);22222223    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2224    // "···" toggle was zero-savings (the toggle button took the same space2225    // the "2FA" label needed) and made the code one extra click away.2226    if (entry.hasTotp) void openTOTPTray();22272228    platter.appendChild(actions);2229    container.appendChild(platter);2230  }22312232  /**2233   * Inline-popup edit mode. Swaps the silver platter for an editable form2234   * over the same shadow-DOM surface so the user never leaves the page.2235   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2236   * with the new fields. Cancel returns without writing.2237   */2238  async function renderInlineEdit(summary: SelectorEntry) {2239    container.innerHTML = "";2240    const wrap = document.createElement("div");2241    wrap.className = "create-form-wrap";22422243    const head = document.createElement("div");2244    head.className = "create-head";2245    const back = document.createElement("button");2246    back.className = "back-btn";2247    back.type = "button";2248    back.title = "Cancel";2249    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>`;2250    back.addEventListener("click", () => renderSilverPlatter(summary));2251    head.appendChild(back);2252    const headLbl = document.createElement("div");2253    headLbl.className = "create-label";2254    headLbl.textContent = "Edit entry";2255    head.appendChild(headLbl);2256    wrap.appendChild(head);22572258    const body = document.createElement("div");2259    body.className = "create-body";22602261    // Loading shimmer while we fetch the full entry2262    const loading = document.createElement("div");2263    loading.className = "empty-hint";2264    loading.textContent = "loading…";2265    body.appendChild(loading);2266    wrap.appendChild(body);2267    container.appendChild(wrap);22682269    const [res, idRes] = await Promise.all([2270      chrome.runtime.sendMessage({2271        type: "GET_ENTRY_FOR_FILL",2272        payload: { id: summary.id },2273      }).catch(() => null),2274      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2275    ]);2276    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2277    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];22782279    if (!entryRes || !entryRes.ok || !entryRes.data) {2280      loading.textContent = "couldn't load this entry. try again from the popup.";2281      return;2282    }2283    body.innerHTML = "";22842285    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2286      const group = document.createElement("div");2287      group.className = "f-group";2288      const lbl = document.createElement("div");2289      lbl.className = "f-label";2290      lbl.textContent = label;2291      const input = document.createElement("input");2292      input.className = "f-input";2293      input.type = type;2294      input.value = value;2295      input.autocomplete = "off";2296      group.append(lbl, input);2297      body.appendChild(group);2298      return { g: group, inp: input };2299    }23002301    const titleInput = field("title", entryRes.data.title ?? "").inp;2302    const urlInput = field("url", entryRes.data.url ?? "").inp;2303    urlInput.classList.add("url-f");2304    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2305    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2306    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2307    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2308    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");23092310    // Password row with reveal toggle + generator2311    const pwGroup = document.createElement("div");2312    pwGroup.className = "f-group";2313    const pwLbl = document.createElement("div");2314    pwLbl.className = "f-label";2315    pwLbl.textContent = "password";2316    const pwRow = document.createElement("div");2317    pwRow.className = "f-row";2318    const pwInput = document.createElement("input");2319    pwInput.className = "f-input";2320    pwInput.type = "password";2321    pwInput.value = entryRes.data.password ?? "";2322    pwInput.autocomplete = "new-password";2323    const revealBtn = document.createElement("button");2324    revealBtn.className = "gen-btn";2325    revealBtn.type = "button";2326    revealBtn.textContent = "show";2327    revealBtn.addEventListener("click", () => {2328      const reveal = pwInput.type === "password";2329      pwInput.type = reveal ? "text" : "password";2330      revealBtn.textContent = reveal ? "hide" : "show";2331    });2332    pwRow.append(pwInput, revealBtn);2333    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2334    editSmartGen.root.style.display = "none";2335    let editGenVisible = false;2336    const genToggleBtn = document.createElement("button");2337    genToggleBtn.className = "gen-toggle-link";2338    genToggleBtn.type = "button";2339    genToggleBtn.textContent = "⚙ generate";2340    genToggleBtn.addEventListener("click", () => {2341      editGenVisible = !editGenVisible;2342      pwRow.style.display = editGenVisible ? "none" : "";2343      editSmartGen.root.style.display = editGenVisible ? "" : "none";2344      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2345    });2346    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2347    body.appendChild(pwGroup);23482349    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;23502351    // Notes2352    const notesGroup = document.createElement("div");2353    notesGroup.className = "f-group";2354    const notesLbl = document.createElement("div");2355    notesLbl.className = "f-label";2356    notesLbl.textContent = "notes";2357    const notesInput = document.createElement("textarea");2358    notesInput.className = "f-input";2359    notesInput.rows = 3;2360    notesInput.value = entryRes.data.notes ?? "";2361    notesInput.style.fontFamily = "Inter, sans-serif";2362    notesInput.style.resize = "vertical";2363    notesGroup.append(notesLbl, notesInput);2364    body.appendChild(notesGroup);23652366    // Save / Cancel row2367    const actionsRow = document.createElement("div");2368    actionsRow.className = "f-row";2369    const saveBtn = document.createElement("button");2370    saveBtn.className = "save-btn";2371    saveBtn.type = "button";2372    saveBtn.textContent = "Save changes";2373    saveBtn.style.flex = "1";2374    const cancelBtn = document.createElement("button");2375    cancelBtn.className = "gen-btn";2376    cancelBtn.type = "button";2377    cancelBtn.textContent = "cancel";2378    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2379    actionsRow.append(saveBtn, cancelBtn);2380    body.appendChild(actionsRow);23812382    saveBtn.addEventListener("click", async () => {2383      saveBtn.disabled = true;2384      const originalLabel = saveBtn.textContent;2385      saveBtn.textContent = "Saving…";2386      const patch: Record<string, unknown> = {2387        title: titleInput.value.trim(),2388        url: urlInput.value.trim(),2389        username: usernameInput.value.trim(),2390        email: emailInput.value.trim() || undefined,2391        password: pwInput.value,2392        totp: totpInput.value.trim(),2393        notes: notesInput.value,2394      };2395      const updateRes = (await chrome.runtime.sendMessage({2396        type: "UPDATE_ENTRY",2397        payload: { id: summary.id, patch },2398      }).catch(() => null)) as { ok: boolean; error?: string } | null;2399      if (!updateRes?.ok) {2400        saveBtn.disabled = false;2401        saveBtn.textContent = originalLabel;2402        const err = document.createElement("div");2403        err.className = "empty-hint";2404        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2405        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2406        body.appendChild(err);2407        setTimeout(() => err.remove(), 3000);2408        return;2409      }2410      // Refresh the platter with updated summary fields2411      const refreshed: SelectorEntry = {2412        id: summary.id,2413        title: patch.title as string,2414        username: patch.username as string,2415        email: patch.email as string | undefined,2416        url: patch.url as string,2417        hasTotp: Boolean(patch.totp),2418        hasPasskey: summary.hasPasskey,2419      };2420      renderSilverPlatter(refreshed);2421    });24222423    queueMicrotask(() => titleInput.focus());2424  }24252426  function renderLocked() {2427    container.innerHTML = "";24282429    // Domain header (same as list view)2430    const domHdr = document.createElement("div");2431    domHdr.className = "domain-header";2432    const eyebrow = document.createElement("div");2433    eyebrow.className = "domain-eyebrow";2434    eyebrow.textContent = "vault locked";2435    const domName = document.createElement("div");2436    domName.className = "domain-name";2437    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2438    domHdr.append(eyebrow, domName);2439    container.appendChild(domHdr);24402441    const wrap = document.createElement("div");2442    wrap.className = "locked-wrap";24432444    // Icon + label row2445    const head = document.createElement("div"); head.className = "locked-head";2446    const icon = document.createElement("div"); icon.className = "locked-icon";2447    icon.innerHTML = keySvgStr();2448    const title = document.createElement("div"); title.className = "locked-title";2449    title.textContent = "unlock to autofill";2450    head.append(icon, title);24512452    // Password input2453    const pwInp = document.createElement("input");2454    pwInp.className = "locked-input";2455    pwInp.type = "password";2456    pwInp.placeholder = "master password";2457    pwInp.setAttribute("autocomplete", "current-password");24582459    // Error line (hidden initially)2460    const errEl = document.createElement("div");2461    errEl.className = "locked-error";2462    errEl.style.display = "none";24632464    // Unlock button2465    const unlockBtn = document.createElement("button");2466    unlockBtn.className = "locked-btn";2467    unlockBtn.type = "button";2468    unlockBtn.textContent = "unlock";24692470    async function tryUnlock() {2471      const pw = pwInp.value.trim();2472      if (!pw) { pwInp.focus(); return; }2473      unlockBtn.disabled = true;2474      unlockBtn.textContent = "unlocking…";2475      errEl.style.display = "none";2476      try {2477        const res = await chrome.runtime.sendMessage({2478          type: "UNLOCK",2479          payload: { password: pw },2480        });2481        if ((res as { ok?: boolean }).ok) {2482          dismiss();2483          options.onUnlocked?.();2484        } else {2485          errEl.textContent = "incorrect password";2486          errEl.style.display = "block";2487          pwInp.value = "";2488          pwInp.focus();2489          unlockBtn.disabled = false;2490          unlockBtn.textContent = "unlock";2491        }2492      } catch {2493        errEl.textContent = "could not reach Peach";2494        errEl.style.display = "block";2495        unlockBtn.disabled = false;2496        unlockBtn.textContent = "unlock";2497      }2498    }24992500    pwInp.addEventListener("keydown", (e) => {2501      e.stopPropagation();2502      if (e.key === "Enter") void tryUnlock();2503    });2504    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2505    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2506    unlockBtn.addEventListener("click", () => void tryUnlock());25072508    wrap.append(head, pwInp, errEl, unlockBtn);2509    container.appendChild(wrap);25102511    // Keep the MV3 service worker alive while the locked popup is visible.2512    // Without this, the SW goes idle (~30 s) while the user types their2513    // password, and the UNLOCK message pays a 100-300 ms wakeup penalty2514    // before the crypto even starts — perceptible as a delay vs the always-2515    // live extension popup page.2516    const keepaliveId = setInterval(() => {2517      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});2518    }, 20_000);2519    cleanupHooks.push(() => clearInterval(keepaliveId));25202521    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2522    // the page reclaims focus from our Shadow DOM input before the user can2523    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2524    // Instead: intercept keystrokes at the document capture phase — this runs2525    // before any page handler regardless of which element technically has2526    // OS focus — and route them into our input.2527    const captureKeydown = (e: KeyboardEvent) => {2528      if (!host.isConnected) {2529        document.removeEventListener("keydown", captureKeydown, true);2530        return;2531      }2532      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2533      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2534      // Intercept before page handlers and give our input focus.2535      e.stopImmediatePropagation();2536      if (e.key === "Escape") { dismiss(true); return; }2537      if (e.key === "Enter") { void tryUnlock(); return; }2538      // For all other printable/editing keys, ensure our input has focus so2539      // the browser delivers the keystroke there naturally.2540      if (document.activeElement !== host) {2541        pwInp.focus({ preventScroll: true });2542      }2543    };2544    captureKeydownRef = captureKeydown;2545    document.addEventListener("keydown", captureKeydown, true);25462547    // Best-effort focus on open — may be overridden by page focus trap,2548    // but the capture listener above handles typing regardless.2549    pwInp.focus({ preventScroll: true });2550    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2551  }25522553  function handleKeyDown(e: KeyboardEvent) {2554    if (options.locked) {2555      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2556      return;2557    }2558    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2559      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2560      return;2561    }2562    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2563    const count = allEntryEls.length;2564    if (document.activeElement === searchInput) {2565      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2566      if (count === 0) return;2567      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2568    }2569    if (count === 0) return;2570    switch (e.key) {2571      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2572      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2573      case "Enter": {2574        if (focusedIndex >= 0) {2575          const el = allEntryEls[focusedIndex] as HTMLElement;2576          const id = el.dataset.id;2577          if (id) { onSelect(id); dismiss(); }2578          else if (el.classList.contains("is-new") || !id) {2579            // "New entry" row (last item, no data-id)2580            showCreateForm();2581          }2582        }2583        break;2584      }2585      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2586    }2587  }25882589  document.addEventListener("keydown", handleKeyDown);25902591  document.body.appendChild(host);25922593  function updatePosition() {2594    const r = anchorEl.getBoundingClientRect();2595    host.style.top = `${r.bottom + window.scrollY + 5}px`;2596    host.style.left = `${r.left + window.scrollX}px`;2597    host.style.width = `${popupWidth}px`;2598  }2599  // These bindings are referenced from renderLocked()/dismiss() — they MUST2600  // be initialized before renderLocked() runs, or the synchronous assignment2601  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2602  // and throws ReferenceError. The throw lands after the popup is rendered2603  // but before showAutofillSelector returns its dismiss handle, leaving an2604  // orphan host in the DOM (which is what caused the locked-popup stacking2605  // and missing autofocus on every click).2606  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2607  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26082609  if (options.locked) {2610    renderLocked();2611  } else if (options.isSignup && options.savedIdentities) {2612    // State 10: identity helper — signup form detected, show derived2613    // identity list (emails then usernames) instead of vault entry list.2614    renderIdentityHelper();2615  } else if (entries.length === 1 && !options.isSignup) {2616    // Silver platter (State 1): single domain match → focused fill view.2617    // Multi-match goes through renderList instead.2618    renderSilverPlatter(entries[0]!);2619  } else {2620    renderList();2621  }26222623  let exitScheduled = false;2624  function dismiss(userAction = false) {2625    // Idempotent: dismiss() can be called from multiple paths (Escape,2626    // outside click, entry select, fill success, host page nav). The exit2627    // animation must only play once and host.remove() must run exactly once.2628    if (exitScheduled) return;2629    exitScheduled = true;2630    // Detach listeners synchronously so nothing can re-trigger during the2631    // 130ms exit window (a focusin firing here would race against the2632    // dismiss-lock work in Pass 2).2633    stopObserving();2634    document.removeEventListener("click", outsideClick, { capture: true });2635    document.removeEventListener("keydown", handleKeyDown);2636    if (captureKeydownRef) {2637      document.removeEventListener("keydown", captureKeydownRef, true);2638      captureKeydownRef = null;2639    }2640    for (const cleanup of cleanupHooks) {2641      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2642    }2643    if (userAction) options.onDismiss?.();2644    container.classList.add("is-exiting");2645    setTimeout(() => host.remove(), 130);2646  }26472648  function outsideClick(ev: MouseEvent) {2649    const path = ev.composedPath();2650    // Never dismiss when clicking the anchor field itself — that click is2651    // what triggered the selector to open, and the user may click the field2652    // again to re-focus it without intending to close the selector.2653    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2654  }2655  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2656  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);26572658  return dismiss;2659}26602661export interface CardSelectorEntry {2662  id: string;2663  title: string;2664  cardholderName?: string;2665  last4?: string;2666  expMonth?: string;2667  expYear?: string;2668  network?: import("../shared/types").CardNetwork;2669}26702671interface CardSelectorOptions {2672  domain?: string;2673  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2674  onFill: (entry: import("../shared/types").VaultEntry) => void;2675  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2676  onDismiss?: () => void;2677}26782679/**2680 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2681 * passkey create or get. Renders as a fixed-position floating popup (no2682 * field anchor needed — passkeys don't require a focused input). Uses the2683 * same theme tokens and entrance animation as all other inline popup states.2684 */2685export function showPasskeyProGate(): void {2686  const domain = location.hostname.replace(/^www\./, "");26872688  const host = document.createElement("div");2689  host.setAttribute("data-peach-passkey-gate", "1");2690  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2691  const shadow = host.attachShadow({ mode: "closed" });26922693  const style = document.createElement("style");2694  style.textContent = `2695    :host { all: initial; }2696    .gate-wrap {2697      position: fixed;2698      top: 50%;2699      left: 50%;2700      transform: translate(-50%, -50%);2701      width: 280px;2702      pointer-events: auto;2703      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2704    }2705    @keyframes g-in {2706      from { opacity:0; transform: translate(-50%,-52%); }2707      to   { opacity:1; transform: translate(-50%,-50%); }2708    }2709    .gate-wrap.is-exiting {2710      animation: g-out 130ms ease-in forwards;2711    }2712    @keyframes g-out {2713      to { opacity:0; transform: translate(-50%,-52%); }2714    }2715    .gate {2716      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2717      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2718      border-radius: 12px;2719      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2720      padding: 16px;2721      font-family: Inter, sans-serif;2722    }2723    .gate-header {2724      display: flex;2725      align-items: center;2726      gap: 7px;2727      margin-bottom: 12px;2728      padding-bottom: 10px;2729      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2730    }2731    .gate-domain {2732      font-size: 12px;2733      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2734      font-family: "IBM Plex Mono", monospace;2735      overflow: hidden;2736      text-overflow: ellipsis;2737      white-space: nowrap;2738    }2739    .gate-title {2740      font-size: 14px;2741      font-weight: 500;2742      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2743      margin-bottom: 6px;2744    }2745    .gate-subtitle {2746      font-size: 12px;2747      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2748      line-height: 1.5;2749      margin-bottom: 14px;2750    }2751    .gate-btn {2752      display: block;2753      width: 100%;2754      padding: 9px 0;2755      border-radius: 8px;2756      border: none;2757      cursor: pointer;2758      font-size: 13px;2759      font-family: Inter, sans-serif;2760      font-weight: 500;2761      transition: opacity 100ms;2762      margin-bottom: 7px;2763      text-align: center;2764    }2765    .gate-btn:last-child { margin-bottom: 0; }2766    .gate-btn--accent {2767      background: ${accentHex};2768      color: #fff;2769    }2770    .gate-btn--accent:hover { opacity: 0.88; }2771    .gate-btn--ghost {2772      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2773      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2774    }2775    .gate-btn--ghost:hover { opacity: 0.75; }2776    .backdrop {2777      position: fixed;2778      inset: 0;2779      pointer-events: auto;2780    }2781  `;2782  shadow.appendChild(style);27832784  const backdrop = document.createElement("div");2785  backdrop.className = "backdrop";2786  shadow.appendChild(backdrop);27872788  const wrap = document.createElement("div");2789  wrap.className = "gate-wrap";2790  shadow.appendChild(wrap);27912792  const gate = document.createElement("div");2793  gate.className = "gate";2794  wrap.appendChild(gate);27952796  // Header: peach icon + domain2797  const header = document.createElement("div");2798  header.className = "gate-header";2799  const icon = document.createElement("span");2800  icon.innerHTML = peachIconSvg();2801  const domainEl = document.createElement("span");2802  domainEl.className = "gate-domain";2803  domainEl.textContent = domain;2804  header.append(icon, domainEl);2805  gate.appendChild(header);28062807  const title = document.createElement("div");2808  title.className = "gate-title";2809  title.textContent = "Passkeys are part of Peach Pro.";2810  gate.appendChild(title);28112812  const subtitle = document.createElement("div");2813  subtitle.className = "gate-subtitle";2814  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2815  gate.appendChild(subtitle);28162817  const upgradeBtn = document.createElement("button");2818  upgradeBtn.className = "gate-btn gate-btn--accent";2819  upgradeBtn.type = "button";2820  upgradeBtn.textContent = "Upgrade to Pro";2821  gate.appendChild(upgradeBtn);28222823  const laterBtn = document.createElement("button");2824  laterBtn.className = "gate-btn gate-btn--ghost";2825  laterBtn.type = "button";2826  laterBtn.textContent = "Not right now";2827  gate.appendChild(laterBtn);28282829  function dismiss() {2830    wrap.classList.add("is-exiting");2831    setTimeout(() => host.remove(), 130);2832  }28332834  upgradeBtn.addEventListener("click", () => {2835    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2836    dismiss();2837  });2838  laterBtn.addEventListener("click", dismiss);2839  backdrop.addEventListener("click", dismiss);28402841  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2842    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2843  });28442845  document.body.appendChild(host);2846}28472848/**2849 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2850 * detector sees the page invoke navigator.credentials.create(); content/index.ts2851 * checks vault + decline state then calls this. "Save passkey to Peach"2852 * initiates the popup-context credential flow; "Not now" records a 30-day2853 * decline for the domain so we don't re-show on every page reload.2854 */2855export function showPasskeyRegistrationOffer(args: {2856  rpId: string;2857  rpName?: string;2858  userName?: string;2859  userDisplayName?: string;2860}): void {2861  const domain = location.hostname.replace(/^www\./, "");2862  const displayName = args.rpName || domain;28632864  const host = document.createElement("div");2865  host.setAttribute("data-peach-passkey-offer", "1");2866  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2867  const shadow = host.attachShadow({ mode: "closed" });28682869  const style = document.createElement("style");2870  style.textContent = `2871    :host { all: initial; }2872    .offer-wrap {2873      position: fixed;2874      top: 16px;2875      right: 16px;2876      width: 320px;2877      pointer-events: auto;2878      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2879    }2880    @keyframes o-in {2881      from { opacity: 0; transform: translateY(-6px); }2882      to   { opacity: 1; transform: translateY(0); }2883    }2884    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2885    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2886    .offer {2887      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2888      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2889      border-radius: 12px;2890      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2891      padding: 14px 14px 12px;2892      font-family: Inter, sans-serif;2893      position: relative;2894    }2895    .offer-close {2896      position: absolute;2897      top: 8px;2898      right: 8px;2899      width: 18px;2900      height: 18px;2901      border: none;2902      background: transparent;2903      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2904      cursor: pointer;2905      font-size: 14px;2906      line-height: 1;2907      padding: 0;2908    }2909    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2910    .offer-header {2911      display: flex;2912      align-items: center;2913      gap: 7px;2914      margin-bottom: 8px;2915      padding-bottom: 8px;2916      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2917    }2918    .offer-domain {2919      font-size: 12px;2920      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2921      font-family: "IBM Plex Mono", monospace;2922      overflow: hidden;2923      text-overflow: ellipsis;2924      white-space: nowrap;2925    }2926    .offer-title {2927      font-size: 13px;2928      font-weight: 500;2929      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2930      margin-bottom: 4px;2931    }2932    .offer-subtitle {2933      font-size: 11px;2934      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2935      line-height: 1.45;2936      margin-bottom: 12px;2937    }2938    .offer-btn {2939      display: block;2940      width: 100%;2941      padding: 8px 0;2942      border-radius: 7px;2943      border: none;2944      cursor: pointer;2945      font-size: 12px;2946      font-family: Inter, sans-serif;2947      font-weight: 500;2948      transition: opacity 100ms;2949      margin-bottom: 6px;2950      text-align: center;2951    }2952    .offer-btn:last-child { margin-bottom: 0; }2953    .offer-btn--accent { background: ${accentHex}; color: #fff; }2954    .offer-btn--accent:hover { opacity: 0.88; }2955    .offer-btn--ghost {2956      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2957      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2958    }2959    .offer-btn--ghost:hover { opacity: 0.75; }2960  `;2961  shadow.appendChild(style);29622963  const wrap = document.createElement("div");2964  wrap.className = "offer-wrap";2965  shadow.appendChild(wrap);29662967  const offer = document.createElement("div");2968  offer.className = "offer";2969  wrap.appendChild(offer);29702971  const closeBtn = document.createElement("button");2972  closeBtn.className = "offer-close";2973  closeBtn.type = "button";2974  closeBtn.setAttribute("aria-label", "Dismiss");2975  closeBtn.textContent = "✕";2976  offer.appendChild(closeBtn);29772978  const header = document.createElement("div");2979  header.className = "offer-header";2980  const icon = document.createElement("span");2981  icon.innerHTML = peachIconSvg();2982  const domainEl = document.createElement("span");2983  domainEl.className = "offer-domain";2984  domainEl.textContent = domain;2985  header.append(icon, domainEl);2986  offer.appendChild(header);29872988  const title = document.createElement("div");2989  title.className = "offer-title";2990  title.textContent = "This site supports passkeys.";2991  offer.appendChild(title);29922993  const subtitle = document.createElement("div");2994  subtitle.className = "offer-subtitle";2995  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2996  offer.appendChild(subtitle);29972998  const saveBtn = document.createElement("button");2999  saveBtn.className = "offer-btn offer-btn--accent";3000  saveBtn.type = "button";3001  saveBtn.textContent = "Save passkey to Peach";3002  offer.appendChild(saveBtn);30033004  const laterBtn = document.createElement("button");3005  laterBtn.className = "offer-btn offer-btn--ghost";3006  laterBtn.type = "button";3007  laterBtn.textContent = "Not now";3008  offer.appendChild(laterBtn);30093010  function dismiss(decline: boolean) {3011    if (decline) {3012      chrome.runtime.sendMessage({3013        type: "PASSKEY_OFFER_DECLINE",3014        payload: { domain },3015      }).catch(() => {});3016    }3017    wrap.classList.add("is-exiting");3018    setTimeout(() => host.remove(), 130);3019  }30203021  saveBtn.addEventListener("click", () => {3022    chrome.runtime.sendMessage({3023      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3024      payload: {3025        rpId: args.rpId,3026        rpName: args.rpName ?? displayName,3027        userName: args.userName ?? "user",3028        userDisplayName: args.userDisplayName,3029      },3030    }).catch(() => {});3031    dismiss(false);3032  });3033  laterBtn.addEventListener("click", () => dismiss(true));3034  closeBtn.addEventListener("click", () => dismiss(true));30353036  document.body.appendChild(host);3037}30383039/**3040 * State 11 — passkey available indicator. Shown when the user lands on a3041 * domain for which they already have a stored passkey. Tells them where to3042 * find it (the entry already shows in the vault list); the "Sign in with3043 * passkey" button opens the popup so they can use the platform authenticator3044 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3045 * the actual sign-in transparently, so this banner is informational only.3046 */3047export function showPasskeyAvailable(args: {3048  rpId: string;3049  userName: string;3050  fromBrowser?: "chrome" | "firefox";3051  currentBrowser?: "chrome" | "firefox" | "unknown";3052}): void {3053  const domain = location.hostname.replace(/^www\./, "");3054  const crossBrowser =3055    args.fromBrowser &&3056    args.currentBrowser &&3057    args.currentBrowser !== "unknown" &&3058    args.fromBrowser !== args.currentBrowser;30593060  const host = document.createElement("div");3061  host.setAttribute("data-peach-passkey-available", "1");3062  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3063  const shadow = host.attachShadow({ mode: "closed" });30643065  const style = document.createElement("style");3066  style.textContent = `3067    :host { all: initial; }3068    .avail-wrap {3069      position: fixed;3070      top: 16px;3071      right: 16px;3072      width: 320px;3073      pointer-events: auto;3074      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3075    }3076    @keyframes a-in {3077      from { opacity: 0; transform: translateY(-6px); }3078      to   { opacity: 1; transform: translateY(0); }3079    }3080    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3081    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3082    .avail {3083      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3084      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3085      border-radius: 12px;3086      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3087      padding: 14px 14px 12px;3088      font-family: Inter, sans-serif;3089      position: relative;3090    }3091    .avail-close {3092      position: absolute;3093      top: 8px;3094      right: 8px;3095      width: 18px;3096      height: 18px;3097      border: none;3098      background: transparent;3099      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3100      cursor: pointer;3101      font-size: 14px;3102      line-height: 1;3103      padding: 0;3104    }3105    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3106    .avail-header {3107      display: flex;3108      align-items: center;3109      gap: 7px;3110      margin-bottom: 8px;3111      padding-bottom: 8px;3112      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3113    }3114    .avail-domain {3115      font-size: 12px;3116      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3117      font-family: "IBM Plex Mono", monospace;3118    }3119    .avail-label {3120      font-size: 9px;3121      letter-spacing: 0.16em;3122      text-transform: uppercase;3123      color: ${accentHex};3124      margin-bottom: 4px;3125    }3126    .avail-user {3127      font-size: 13px;3128      font-weight: 500;3129      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3130      margin-bottom: 12px;3131      overflow: hidden;3132      text-overflow: ellipsis;3133      white-space: nowrap;3134    }3135    .avail-cross {3136      font-size: 11px;3137      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3138      line-height: 1.45;3139      margin-bottom: 12px;3140      padding: 8px;3141      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3142      border-radius: 6px;3143    }3144    .avail-btn {3145      display: block;3146      width: 100%;3147      padding: 8px 0;3148      border-radius: 7px;3149      border: none;3150      cursor: pointer;3151      font-size: 12px;3152      font-family: Inter, sans-serif;3153      font-weight: 500;3154      transition: opacity 100ms;3155      margin-bottom: 6px;3156      text-align: center;3157    }3158    .avail-btn:last-child { margin-bottom: 0; }3159    .avail-btn--accent { background: ${accentHex}; color: #fff; }3160    .avail-btn--accent:hover { opacity: 0.88; }3161    .avail-btn--ghost {3162      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3163      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3164    }3165    .avail-btn--ghost:hover { opacity: 0.75; }3166  `;3167  shadow.appendChild(style);31683169  const wrap = document.createElement("div");3170  wrap.className = "avail-wrap";3171  shadow.appendChild(wrap);31723173  const avail = document.createElement("div");3174  avail.className = "avail";3175  wrap.appendChild(avail);31763177  const closeBtn = document.createElement("button");3178  closeBtn.className = "avail-close";3179  closeBtn.type = "button";3180  closeBtn.setAttribute("aria-label", "Dismiss");3181  closeBtn.textContent = "✕";3182  avail.appendChild(closeBtn);31833184  const header = document.createElement("div");3185  header.className = "avail-header";3186  const icon = document.createElement("span");3187  icon.innerHTML = peachIconSvg();3188  const domainEl = document.createElement("span");3189  domainEl.className = "avail-domain";3190  domainEl.textContent = domain;3191  header.append(icon, domainEl);3192  avail.appendChild(header);31933194  const label = document.createElement("div");3195  label.className = "avail-label";3196  label.textContent = "PASSKEY";3197  avail.appendChild(label);31983199  const user = document.createElement("div");3200  user.className = "avail-user";3201  user.textContent = args.userName;3202  avail.appendChild(user);32033204  if (crossBrowser) {3205    const cross = document.createElement("div");3206    cross.className = "avail-cross";3207    cross.textContent =3208      args.fromBrowser === "chrome"3209        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3210        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3211    avail.appendChild(cross);3212  }32133214  const signInBtn = document.createElement("button");3215  signInBtn.className = "avail-btn avail-btn--accent";3216  signInBtn.type = "button";3217  signInBtn.textContent = "Sign in with passkey";3218  avail.appendChild(signInBtn);32193220  const passwordBtn = document.createElement("button");3221  passwordBtn.className = "avail-btn avail-btn--ghost";3222  passwordBtn.type = "button";3223  passwordBtn.textContent = "Use password instead";3224  avail.appendChild(passwordBtn);32253226  function dismiss() {3227    wrap.classList.add("is-exiting");3228    setTimeout(() => host.remove(), 130);3229  }32303231  signInBtn.addEventListener("click", () => {3232    // On Chrome: the user clicking the page's own Sign-in button is what3233    //   triggers webAuthenticationProxy → existing background flow handles it.3234    //   Our button just dismisses since the page itself drives auth.3235    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3236    //   and surface the entry for manual reference (popup view).3237    dismiss();3238    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3239  });3240  passwordBtn.addEventListener("click", dismiss);3241  closeBtn.addEventListener("click", dismiss);32423243  document.body.appendChild(host);3244}32453246/**3247 * State 7 — card silver platter. Single-card focused fill view rendered3248 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3249 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3250 * so card and login flows render identically. Multi-card list view is a3251 * follow-up; today this picks the first card.3252 */3253export function showCardSelector(3254  anchorEl: HTMLInputElement,3255  cards: CardSelectorEntry[],3256  options: CardSelectorOptions3257): () => void {3258  if (cards.length === 0) return () => {};3259  const card = cards[0]!;32603261  const host = document.createElement("div");3262  host.style.cssText = "position: absolute; z-index: 2147483647;";3263  host.style.setProperty("--peach-accent", accentHex);3264  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3265  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3266  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3267  const shadow = host.attachShadow({ mode: "closed" });32683269  const style = shadow.appendChild(document.createElement("style"));3270  style.textContent = SELECTOR_STYLES;32713272  const rect = anchorEl.getBoundingClientRect();3273  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3274  host.style.left = `${rect.left + window.scrollX}px`;3275  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;32763277  const container = shadow.appendChild(document.createElement("div"));3278  container.className = "peach-inline-popup";3279  container.setAttribute("data-theme", popupTheme);32803281  // Domain header — eyebrow communicates the card context, not the site3282  const domHdr = document.createElement("div");3283  domHdr.className = "domain-header";3284  const eyebrow = document.createElement("div");3285  eyebrow.className = "domain-eyebrow";3286  eyebrow.textContent = "Pay with Peach";3287  const domName = document.createElement("div");3288  domName.className = "domain-name";3289  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3290  domHdr.append(eyebrow, domName);3291  container.appendChild(domHdr);32923293  const platter = document.createElement("div");3294  platter.className = "card-platter";32953296  if (card.network && card.network !== "unknown") {3297    const net = document.createElement("div");3298    net.className = "cp-network";3299    net.textContent = card.network;3300    platter.appendChild(net);3301  }33023303  const nick = document.createElement("div");3304  nick.className = "cp-nickname";3305  nick.textContent = card.title;3306  platter.appendChild(nick);33073308  if (card.last4) {3309    const l4 = document.createElement("div");3310    l4.className = "cp-last4";3311    l4.textContent = `•••• ${card.last4}`;3312    platter.appendChild(l4);3313  }33143315  const meta = document.createElement("div");3316  meta.className = "cp-meta";3317  if (card.cardholderName) {3318    const name = document.createElement("span");3319    name.textContent = card.cardholderName;3320    meta.appendChild(name);3321  }3322  if (card.expMonth && card.expYear) {3323    if (card.cardholderName) {3324      const sep = document.createElement("span");3325      sep.className = "cp-meta-sep";3326      sep.textContent = "·";3327      meta.appendChild(sep);3328    }3329    const exp = document.createElement("span");3330    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3331    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3332    meta.appendChild(exp);3333  }3334  if (meta.childElementCount > 0) platter.appendChild(meta);33353336  const fillWrap = document.createElement("div");3337  fillWrap.className = "cp-fill-wrap";3338  const fillBtn = document.createElement("button");3339  fillBtn.className = "sp-fill-btn";3340  fillBtn.type = "button";3341  fillBtn.textContent = "Fill card details";3342  fillBtn.addEventListener("click", async () => {3343    if (fillBtn.disabled) return;3344    fillBtn.disabled = true;3345    fillBtn.classList.add("filled");3346    fillBtn.innerHTML = checkSvgStr();3347    const resp = await chrome.runtime.sendMessage({3348      type: "GET_ENTRY_FOR_FILL",3349      payload: { id: card.id },3350    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3351    if (resp?.ok && resp.data) options.onFill(resp.data);3352    setTimeout(() => dismiss(), 400);3353  });3354  fillWrap.appendChild(fillBtn);3355  platter.appendChild(fillWrap);33563357  // Secondary actions — copy number, copy CVC, dismiss3358  const actions = document.createElement("div");3359  actions.className = "sp-actions";33603361  function flashBtn(b: HTMLButtonElement) {3362    b.classList.add("flashed");3363    setTimeout(() => b.classList.remove("flashed"), 700);3364  }33653366  // M3/QUA-005: clipboard + background COPY both failed — show user.3367  function flashCopyError(b: HTMLButtonElement) {3368    const original = b.textContent ?? "";3369    b.textContent = "Blocked";3370    b.classList.add("flashed");3371    setTimeout(() => {3372      b.classList.remove("flashed");3373      if (b.isConnected) b.textContent = original;3374    }, 1200);3375  }33763377  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3378    const resp = await chrome.runtime.sendMessage({3379      type: "GET_ENTRY_FOR_FILL",3380      payload: { id: card.id },3381    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3382    return resp?.ok && resp.data ? resp.data : null;3383  }33843385  const copyNum = document.createElement("button");3386  copyNum.className = "sp-action-btn";3387  copyNum.type = "button";3388  copyNum.title = "Copy card number";3389  copyNum.textContent = "Copy number";3390  copyNum.addEventListener("click", async (e) => {3391    e.stopPropagation();3392    const full = await fetchFullCard();3393    if (!full?.cardNumber) return;3394    let alreadyWritten = false;3395    try {3396      await navigator.clipboard.writeText(full.cardNumber);3397      alreadyWritten = true;3398    } catch (err) {3399      console.warn("[Peach] clipboard write denied:", err);3400    }3401    const resp = await chrome.runtime.sendMessage({3402      type: "COPY",3403      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3404    }).catch(() => null) as { ok?: boolean } | null;3405    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3406    else flashCopyError(copyNum);3407  });3408  actions.appendChild(copyNum);34093410  const copyCvc = document.createElement("button");3411  copyCvc.className = "sp-action-btn";3412  copyCvc.type = "button";3413  copyCvc.title = "Copy CVC";3414  copyCvc.textContent = "Copy CVC";3415  copyCvc.addEventListener("click", async (e) => {3416    e.stopPropagation();3417    const full = await fetchFullCard();3418    if (!full?.cvc) return;3419    let alreadyWritten = false;3420    try {3421      await navigator.clipboard.writeText(full.cvc);3422      alreadyWritten = true;3423    } catch (err) {3424      console.warn("[Peach] clipboard write denied:", err);3425    }3426    const resp = await chrome.runtime.sendMessage({3427      type: "COPY",3428      payload: { text: full.cvc, label: "CVC", alreadyWritten },3429    }).catch(() => null) as { ok?: boolean } | null;3430    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3431    else flashCopyError(copyCvc);3432  });3433  actions.appendChild(copyCvc);34343435  const closeBtn = document.createElement("button");3436  closeBtn.className = "sp-action-btn";3437  closeBtn.type = "button";3438  closeBtn.title = "Dismiss";3439  closeBtn.textContent = "✕";3440  closeBtn.addEventListener("click", (e) => {3441    e.stopPropagation();3442    dismiss(true);3443  });3444  actions.appendChild(closeBtn);34453446  platter.appendChild(actions);3447  container.appendChild(platter);34483449  document.body.appendChild(host);3450  function updatePosition() {3451    const r = anchorEl.getBoundingClientRect();3452    host.style.top = `${r.bottom + window.scrollY + 5}px`;3453    host.style.left = `${r.left + window.scrollX}px`;3454  }3455  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);34563457  function onKeyDown(e: KeyboardEvent) {3458    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3459  }3460  document.addEventListener("keydown", onKeyDown);34613462  let exitScheduled = false;3463  function dismiss(userAction = false) {3464    if (exitScheduled) return;3465    exitScheduled = true;3466    stopObserving();3467    document.removeEventListener("click", outsideClick, { capture: true });3468    document.removeEventListener("keydown", onKeyDown);3469    if (userAction) options.onDismiss?.();3470    container.classList.add("is-exiting");3471    setTimeout(() => host.remove(), 130);3472  }34733474  function outsideClick(ev: MouseEvent) {3475    const path = ev.composedPath();3476    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3477  }3478  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);34793480  return dismiss;3481}