inject.ts

120.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  let length = 20;214  if (policy.minLength) length = Math.max(length, policy.minLength);215  if (policy.maxLength) length = Math.min(length, policy.maxLength);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("div"));234  output.className = "pwgen-output";235236  const regenBtn = displayRow.appendChild(document.createElement("button"));237  regenBtn.className = "pwgen-icon-btn";238  regenBtn.type = "button";239  regenBtn.setAttribute("aria-label", "Regenerate password");240  regenBtn.title = "Regenerate";241  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>`;242243  const copyBtn = displayRow.appendChild(document.createElement("button"));244  copyBtn.className = "pwgen-icon-btn";245  copyBtn.type = "button";246  copyBtn.setAttribute("aria-label", "Copy password");247  copyBtn.title = "Copy";248  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>`;249250  const controls = root.appendChild(document.createElement("div"));251  controls.className = "pwgen-controls-row";252  const slider = controls.appendChild(document.createElement("input"));253  slider.type = "range";254  slider.className = "pwgen-slider";255  slider.min = "8";256  slider.max = "128";257  slider.value = String(length);258  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));259  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));260  const lenNum = controls.appendChild(document.createElement("span"));261  lenNum.className = "pwgen-len-num";262  lenNum.textContent = String(length);263264  const pills = root.appendChild(document.createElement("div"));265  pills.className = "pwgen-pills";266267  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {268    const b = document.createElement("button");269    b.type = "button";270    b.className = `pwgen-pill ${on ? "is-on" : ""}`;271    b.textContent = label;272    b.addEventListener("click", () => {273      const next = !b.classList.contains("is-on");274      b.classList.toggle("is-on", next);275      onToggle(next);276    });277    return b;278  }279  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));280  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));281  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));282  pills.appendChild(makePill("!@#", symbols, (next) => {283    // The site forbids symbols — UI lets the user override but still warn.284    symbols = next;285    regenerate();286  }));287288  // Policy hint — surfaces what Peach read off the site so the user knows the289  // generator is already tuned to it. Only shows when something interesting290  // was detected.291  const hintParts: string[] = [];292  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);293  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);294  if (policy.requiresSymbols) hintParts.push("requires symbols");295  if (policy.forbidsSymbols) hintParts.push("no symbols");296  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);297  if (hintParts.length > 0) {298    const hint = root.appendChild(document.createElement("div"));299    hint.className = "pwgen-policy-hint";300    const accent = document.createElement("span");301    accent.className = "pwgen-hint-accent";302    accent.textContent = "site rules · ";303    const text = document.createTextNode(hintParts.join(" · "));304    hint.appendChild(accent);305    hint.appendChild(text);306  }307308  function regenerate() {309    // Falls back gracefully when the user toggles every charset off — the310    // shared generator forces lowercase in that case rather than throwing.311    password = generatePassword({312      length,313      includeUppercase: upper,314      includeLowercase: lower,315      includeNumbers: numbers,316      includeSymbols: symbols,317      forbiddenChars,318    });319    output.textContent = password;320    opts.onChange?.(password);321  }322323  slider.addEventListener("input", () => {324    length = parseInt(slider.value, 10);325    lenNum.textContent = String(length);326    regenerate();327  });328  regenBtn.addEventListener("click", regenerate);329330  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;331  async function copy(): Promise<void> {332    try {333      await navigator.clipboard.writeText(password);334      copyBtn.classList.add("is-copied");335      if (copyResetTimer) clearTimeout(copyResetTimer);336      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);337    } catch {338      // Clipboard API may be denied — silently no-op; user still has regen UI.339    }340  }341  copyBtn.addEventListener("click", () => { void copy(); });342343  if (opts.initialPassword) {344    password = opts.initialPassword;345    output.textContent = password;346    opts.onChange?.(password);347  } else {348    regenerate();349  }350351  return {352    root,353    getPassword: () => password,354    copy,355  };356}357358export function observeAnchorPosition(359  anchorEl: HTMLElement,360  onUpdate: () => void361): () => void {362  let rafId = 0;363  let burstUntil = 0;364365  const runUpdate = () => {366    rafId = 0;367    onUpdate();368    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);369  };370  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };371  const scheduleBurst = (ms = 220) => {372    burstUntil = Math.max(burstUntil, performance.now() + ms);373    scheduleUpdate();374  };375376  const resizeObserver = new ResizeObserver(() => scheduleBurst());377  resizeObserver.observe(anchorEl);378  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);379380  const mutationObserver = new MutationObserver(() => scheduleBurst());381  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });382  if (anchorEl.parentElement) {383    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });384  }385386  const onScroll = () => scheduleUpdate();387  window.addEventListener("scroll", onScroll, true);388  window.addEventListener("resize", onScroll);389  window.visualViewport?.addEventListener("resize", onScroll);390  window.visualViewport?.addEventListener("scroll", onScroll);391  anchorEl.addEventListener("focus", () => scheduleBurst());392  anchorEl.addEventListener("input", () => scheduleBurst());393394  scheduleBurst(260);395396  return () => {397    if (rafId) cancelAnimationFrame(rafId);398    resizeObserver.disconnect();399    mutationObserver.disconnect();400    window.removeEventListener("scroll", onScroll, true);401    window.removeEventListener("resize", onScroll);402    window.visualViewport?.removeEventListener("resize", onScroll);403    window.visualViewport?.removeEventListener("scroll", onScroll);404  };405}406407export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {408  const button = document.createElement("button");409  button.type = "button";410  button.setAttribute("aria-label", "Peach autofill");411  button.title = "Fill with Peach";412  button.innerHTML = peachIconSvg();413  // position: fixed is load-bearing — not absolute. Absolute positioning414  // inherits the nearest positioned ancestor's box, which on sites with415  // overflow:hidden or sticky parents clips or offsets the icon. Fixed416  // anchors to the viewport and escapes all parent layout.417  button.style.cssText = `418    position: fixed; z-index: 2147483646;419    width: 26px; height: 26px; cursor: pointer;420    pointer-events: auto; border: none; padding: 3px;421    display: inline-flex; align-items: center; justify-content: center;422    background: transparent; border-radius: 999px;423    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;424    opacity: 0;425  `;426  button.addEventListener("mouseenter", () => {427    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;428    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;429    button.style.transform = "scale(1.08)";430  });431  button.addEventListener("mouseleave", () => {432    button.style.background = "transparent";433    button.style.boxShadow = "none";434    button.style.transform = "none";435  });436  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });437  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });438439  document.body.appendChild(button);440441  function updatePosition() {442    const rect = field.getBoundingClientRect();443    if (rect.width === 0 || rect.height === 0) {444      button.style.opacity = "0"; button.style.pointerEvents = "none";445      return;446    }447    const sz = 26;448    const inset = Math.max(5, Math.min(10, rect.height * 0.22));449    const top = rect.top + rect.height / 2 - sz / 2;450    // Clamp left so the icon stays fully inside the field's right edge, never451    // spilling onto an adjacent sibling button.452    const minLeft = rect.left + 4;453    const left = Math.max(minLeft, rect.right - sz - inset);454    // Hide if the field is too narrow to fit the icon cleanly (< 40px)455    if (rect.width < 40) {456      button.style.opacity = "0"; button.style.pointerEvents = "none";457      return;458    }459    button.style.top = `${top}px`;460    button.style.left = `${left}px`;461    button.style.opacity = "1"; button.style.pointerEvents = "auto";462  }463  updatePosition();464  requestAnimationFrame(() => { button.style.opacity = "1"; });465  const stopObserving = observeAnchorPosition(field, updatePosition);466  return () => { stopObserving(); button.remove(); };467}468469// All theme-dependent values resolve through tokens scoped to470// .peach-inline-popup[data-theme="dark|light"]. Accent variables471// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)472// are identical in both themes — only surface tokens differ. See473// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the474// theme switch — only literal brand-peach in peachIconSvg may stay raw.475const SELECTOR_STYLES = `476  :host { all: initial; }477  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }478479  .peach-inline-popup[data-theme="dark"] {480    --peach-bg:           #1a1410;481    --peach-bg-card:      #221c16;482    --peach-text:         #f5f0ea;483    --peach-text-dim:     #8a7a6a;484    --peach-text-muted:   #4a3a2a;485    --peach-border:       rgba(255,255,255,0.07);486    --peach-input-bg:     rgba(255,255,255,0.05);487    --peach-input-border: rgba(255,255,255,0.08);488  }489  .peach-inline-popup[data-theme="light"] {490    --peach-bg:           #fdf8f4;491    --peach-bg-card:      #f5ede4;492    --peach-text:         #1c1310;493    --peach-text-dim:     #6b5a4a;494    --peach-text-muted:   #a89080;495    --peach-border:       rgba(0,0,0,0.08);496    --peach-input-bg:     rgba(0,0,0,0.04);497    --peach-input-border: rgba(0,0,0,0.10);498  }499500  .peach-inline-popup {501    background: var(--peach-bg);502    border: 1px solid var(--peach-border-accent, var(--peach-border));503    border-radius: 14px;504    overflow: hidden;505    box-shadow:506      0 8px 40px var(--peach-glow, transparent),507      0 2px 12px rgba(0,0,0,0.5);508    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;509    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;510  }511  /* Light theme: shadow against a light page is too strong otherwise — drop both512     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */513  .peach-inline-popup[data-theme="light"] {514    box-shadow:515      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),516      0 2px 12px rgba(0,0,0,0.12);517  }518  .peach-inline-popup.is-exiting {519    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;520    pointer-events: none;521  }522523  @keyframes peach-enter {524    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }525    65%  { opacity: 1; filter: blur(0); }526    100% { opacity: 1; transform: translateY(0) scale(1); }527  }528  @keyframes peach-exit {529    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }530    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }531  }532  @keyframes peach-slide-in {533    from { opacity: 0; transform: translateX(12px); }534    to   { opacity: 1; transform: translateX(0); }535  }536  @keyframes peach-slide-back {537    from { opacity: 0; transform: translateX(-12px); }538    to   { opacity: 1; transform: translateX(0); }539  }540  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }541  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }542543  /* Domain header */544  .domain-header {545    padding: 9px 13px 7px;546    border-bottom: 1px solid var(--peach-border);547    display: flex; align-items: center; justify-content: space-between;548    gap: 8px;549  }550  .domain-header-text {551    display: flex; flex-direction: column; gap: 2px;552    min-width: 0; flex: 1;553  }554  .domain-eyebrow {555    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;556    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;557  }558  .domain-name {559    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);560    font-family: "IBM Plex Mono", monospace;561    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;562  }563  .domain-add-btn {564    flex-shrink: 0;565    width: 22px; height: 22px;566    display: inline-flex; align-items: center; justify-content: center;567    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);568    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);569    border-radius: 6px;570    color: var(--peach-accent);571    cursor: pointer; padding: 0;572    transition: background 120ms, border-color 120ms, transform 80ms;573    font-family: "IBM Plex Mono", monospace;574    font-size: 14px; line-height: 1;575  }576  .domain-add-btn:hover {577    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);578    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);579    transform: scale(1.06);580  }581  .domain-add-btn:active { transform: scale(0.96); }582583  /* Search */584  .search-wrap {585    padding: 9px 12px 7px;586    border-bottom: 1px solid var(--peach-border);587  }588  .search {589    width: 100%; background: var(--peach-input-bg);590    border: 1px solid var(--peach-input-border);591    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;592    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;593    transition: border-color 120ms, box-shadow 120ms;594  }595  .search:focus {596    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);597    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);598  }599  .search::placeholder { color: var(--peach-text-muted); }600601  /* Results */602  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }603  .results::-webkit-scrollbar { display: none; }604605  /* Entry rows */606  .entry {607    display: flex; align-items: center; padding: 8px 12px;608    cursor: pointer; border-bottom: 1px solid var(--peach-border);609    transition: background 70ms; position: relative; outline: none;610  }611  .entry:last-child { border-bottom: none; }612  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }613  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }614  .entry.focused::before {615    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;616    width: 2px; border-radius: 2px;617    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);618  }619620  .entry-icon {621    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;622    background: var(--peach-input-bg); border: 1px solid var(--peach-border);623    display: flex; align-items: center; justify-content: center;624    overflow: hidden; margin-right: 10px;625  }626  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }627  .entry-icon.is-new {628    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);629    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);630    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);631  }632633  .entry-info { flex: 1; min-width: 0; }634  .entry-title {635    font-size: 12.5px; color: var(--peach-text);636    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;637    line-height: 1.3;638  }639  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }640  .entry-sub {641    font-size: 10px; color: var(--peach-text-dim);642    font-family: "IBM Plex Mono", monospace;643    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;644    margin-top: 1px;645  }646647  .totp-badge {648    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;649    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);650    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);651    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;652  }653  .passkey-badge {654    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;655    border-radius: 4px;656    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);657    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);658    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);659    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;660  }661662  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }663664  .empty-hint {665    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);666    font-family: "IBM Plex Mono", monospace;667  }668669  /* Create form */670  .create-form-wrap {671    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;672  }673  .create-head {674    display: flex; align-items: center; gap: 8px;675    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);676  }677  .back-btn {678    background: transparent; border: none; cursor: pointer;679    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;680    display: flex; align-items: center; line-height: 0;681    transition: color 100ms, background 100ms;682  }683  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }684  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }685  /* minmax(0, 1fr) caps the grid track at the popup width — without it,686     long monospace content (e.g. a 60-char generated password) would687     auto-size the track wider than the popup and overflow the right edge. */688  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }689  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }690  .f-label {691    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;692    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;693  }694  .f-input {695    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);696    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;697    font-size: 11px; font-family: "IBM Plex Mono", monospace;698    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;699  }700  .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); }701  .f-input::placeholder { color: var(--peach-text-muted); }702  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }703  .f-row { display: flex; gap: 6px; }704  .f-row .f-input { flex: 1; min-width: 0; }705  .gen-btn {706    padding: 0 10px; border-radius: 7px; border: none;707    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);708    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);709    font-size: 10px; font-family: "IBM Plex Mono", monospace;710    cursor: pointer; white-space: nowrap; flex-shrink: 0;711    display: flex; align-items: center; gap: 4px;712    transition: background 100ms;713  }714  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }715  .save-btn {716    width: 100%; padding: 8px; border-radius: 8px; border: none;717    background: var(--peach-accent); color: #fff; font-size: 12px;718    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;719    transition: background 120ms, box-shadow 120ms, transform 80ms;720    letter-spacing: 0.01em;721  }722  .save-btn:hover {723    background: color-mix(in srgb, var(--peach-accent) 82%, #000);724    box-shadow: 0 4px 20px var(--peach-glow, transparent);725  }726  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }727  .url-hint {728    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);729    font-family: "IBM Plex Mono", monospace; font-style: italic;730  }731732  /* Success */733  .success-wrap {734    display: flex; flex-direction: column; align-items: center;735    padding: 24px 16px 20px; gap: 8px;736    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;737  }738  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }739  .success-ring {740    width: 40px; height: 40px; border-radius: 50%;741    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);742    display: flex; align-items: center; justify-content: center;743  }744  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }745  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }746747  /* Silver platter (State 1 — single match) */748  .silver-platter {749    padding: 14px 14px 12px;750    display: flex; flex-direction: column; gap: 6px;751  }752  .sp-title {753    font-size: 14px; font-weight: 500; color: var(--peach-text);754    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;755    line-height: 1.25;756  }757  .sp-identity-row {758    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;759  }760  .sp-identity-label {761    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;762    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;763  }764  .sp-username {765    font-size: 12px; color: var(--peach-text-dim);766    font-family: "IBM Plex Mono", monospace;767    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;768    margin-bottom: 0;769  }770  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }771  .sp-fill-btn {772    width: 100%; padding: 11px; border-radius: 9px; border: none;773    background: var(--peach-accent); color: #fff;774    font-size: 13px; font-weight: 500; cursor: pointer;775    font-family: Inter, sans-serif; letter-spacing: 0.01em;776    display: flex; align-items: center; justify-content: center; min-height: 38px;777    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;778  }779  .sp-fill-btn:hover {780    filter: brightness(1.1);781    box-shadow: 0 4px 20px var(--peach-glow, transparent);782    transform: translateY(-1px);783  }784  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }785  .sp-fill-btn.filled {786    background: #16a34a; transform: none; filter: none;787    box-shadow: 0 4px 16px rgba(22,163,74,0.35);788    cursor: default;789  }790  .sp-fill-btn:disabled { cursor: default; }791  .sp-actions {792    display: flex; gap: 4px; justify-content: space-between; align-items: center;793    margin-top: 4px;794  }795  .sp-action-btn {796    flex: 1; height: 28px; border: none; border-radius: 6px;797    background: transparent; color: var(--peach-text-dim);798    font-size: 12px; cursor: pointer;799    transition: background 120ms ease, color 120ms ease;800    font-family: Inter, sans-serif; letter-spacing: 0.04em;801    display: inline-flex; align-items: center; justify-content: center; gap: 4px;802    white-space: nowrap; overflow: hidden;803  }804  .sp-action-btn:hover:not(:disabled) {805    background: color-mix(in srgb, var(--peach-text) 5%, transparent);806    color: var(--peach-text);807  }808  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }809  .sp-action-btn.flashed {810    color: var(--peach-accent);811    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);812  }813814  /* TOTP tray — shown below the silver-platter secondary actions */815  .sp-tray {816    margin-top: 8px;817    padding: 10px 12px;818    border-radius: 9px;819    background: var(--peach-input-bg);820    border: 1px solid var(--peach-input-border);821    display: flex; align-items: center; gap: 12px;822    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;823  }824  .sp-tray-label {825    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;826    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;827    flex-shrink: 0;828  }829  .sp-totp-code {830    font-size: 18px; font-weight: 500;831    color: var(--peach-text);832    font-family: "IBM Plex Mono", monospace;833    letter-spacing: 0.12em;834    flex: 1;835    text-align: center;836  }837  .sp-totp-ring {838    width: 22px; height: 22px; flex-shrink: 0;839  }840  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }841  .sp-totp-ring .ring-fill {842    stroke: var(--peach-accent);843    transition: stroke-dashoffset 1s linear;844    transform: rotate(-90deg);845    transform-origin: center;846  }847  .sp-totp-copy {848    background: transparent; border: none; cursor: pointer;849    padding: 4px 8px; border-radius: 5px;850    color: var(--peach-text-dim); font-size: 11px;851    font-family: Inter, sans-serif;852    transition: background 120ms, color 120ms;853  }854  .sp-totp-copy:hover {855    background: color-mix(in srgb, var(--peach-text) 5%, transparent);856    color: var(--peach-text);857  }858859  /* Card silver platter (State 7) — reuses .sp-* primary action classes */860  .card-platter {861    padding: 12px 14px 10px;862    display: flex; flex-direction: column; gap: 4px;863  }864  .cp-network {865    font-size: 10px; font-weight: 600;866    color: var(--peach-accent);867    letter-spacing: 0.08em; text-transform: uppercase;868    font-family: Inter, sans-serif;869  }870  .cp-nickname {871    font-size: 14px; font-weight: 500; color: var(--peach-text);872    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;873    line-height: 1.2;874  }875  .cp-last4 {876    font-size: 12px; color: var(--peach-text-dim);877    font-family: "IBM Plex Mono", monospace;878    letter-spacing: 0.04em;879    margin-top: 2px;880  }881  .cp-meta {882    font-size: 11px; color: var(--peach-text-dim);883    font-family: "IBM Plex Mono", monospace;884    margin-top: 2px;885    display: flex; gap: 10px; align-items: center;886  }887  .cp-meta-sep { opacity: 0.5; }888  .cp-fill-wrap { margin-top: 10px; }889890  /* Locked state */891  .locked-wrap {892    display: flex; flex-direction: column; align-items: stretch;893    padding: 14px 13px 13px; gap: 9px;894  }895  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }896  .locked-icon {897    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;898    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);899    display: flex; align-items: center; justify-content: center;900  }901  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }902  .locked-input {903    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);904    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;905    font-size: 11px; font-family: "IBM Plex Mono", monospace;906    outline: none; transition: border-color 120ms, box-shadow 120ms;907  }908  .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); }909  .locked-input::placeholder { color: var(--peach-text-muted); }910  .locked-btn {911    width: 100%; padding: 8px; border-radius: 8px; border: none;912    background: var(--peach-accent); color: #fff; font-size: 12px;913    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;914    transition: background 120ms;915    letter-spacing: 0.01em;916    box-shadow: 0 2px 16px var(--peach-glow, transparent);917    animation: peach-pulse-glow 2.4s ease-in-out infinite;918  }919  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }920  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }921  .locked-error {922    font-size: 10px; color: rgba(220,80,60,0.85);923    font-family: "IBM Plex Mono", monospace;924  }925926  @keyframes peach-pulse-glow {927    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }928    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),929                            0 0 48px var(--peach-glow, transparent); }930  }931932  /* ── State 10: identity helper ─────────────────────────────── */933  .identity-list {934    max-height: 192px; overflow-y: auto; padding: 4px 0;935    scrollbar-width: none;936  }937  .identity-list::-webkit-scrollbar { display: none; }938  .peach-identity-row {939    display: flex; align-items: center; gap: 10px;940    padding: 9px 12px; cursor: pointer; border-radius: 8px;941    transition: background 100ms ease;942  }943  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }944  .peach-identity-value {945    font-family: "IBM Plex Mono", monospace; font-size: 13px;946    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;947  }948  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }949  .identity-alt-row {950    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;951    border-radius: 8px; transition: background 100ms ease;952    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;953  }954  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }955  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }956  .identity-alt-input-wrap.open { display: flex; }957  .identity-alt-input {958    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;959    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);960    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;961    outline: none; transition: border-color 120ms;962  }963  .identity-alt-input:focus {964    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);965    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);966  }967  .identity-alt-confirm {968    height: 32px; padding: 0 12px; border-radius: 7px; border: none;969    background: var(--peach-accent); color: #fff; font-size: 12px;970    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;971  }972  /* ── Generator view (after identity picked) ────────────────── */973  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }974  .gen-confirmed {975    display: flex; align-items: center; gap: 8px; padding: 7px 10px;976    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);977    border-radius: 8px;978  }979  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }980  .gen-confirmed-val {981    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);982    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;983  }984  .gen-label {985    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;986    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;987  }988  .gen-pw-row { display: flex; gap: 6px; align-items: center; }989  .gen-pw-val {990    flex: 1; padding: 8px 10px; border-radius: 7px;991    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);992    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);993    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;994  }995  .gen-regen-btn {996    height: 34px; padding: 0 10px; border-radius: 7px; border: none;997    background: color-mix(in srgb, var(--peach-text) 8%, transparent);998    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;999    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1000  }1001  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1002  .gen-fill-btn {1003    padding: 10px; border-radius: 8px; border: none;1004    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1005    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1006    transition: filter 120ms ease, transform 80ms ease;1007  }1008  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1009  .gen-fill-btn:active { transform: translateY(0); }10101011  /* ── Smart password generator (parity with main UI compact mode) ─── */1012  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1013  .pwgen-display-row {1014    display: flex; align-items: center; gap: 6px;1015    padding: 8px 10px; border-radius: 7px;1016    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1017  }1018  .pwgen-output {1019    flex: 1; min-width: 0;1020    font-family: "IBM Plex Mono", monospace; font-size: 12px;1021    color: var(--peach-text);1022    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1023    user-select: text;1024  }1025  .pwgen-icon-btn {1026    flex-shrink: 0;1027    width: 26px; height: 26px;1028    display: inline-flex; align-items: center; justify-content: center;1029    background: transparent; border: 1px solid var(--peach-input-border);1030    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1031    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1032  }1033  .pwgen-icon-btn:hover {1034    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1035    color: var(--peach-accent);1036    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1037  }1038  .pwgen-icon-btn.is-copied {1039    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1040    color: var(--peach-accent);1041    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1042  }1043  .pwgen-controls-row {1044    display: flex; align-items: center; gap: 8px;1045    flex-wrap: wrap;1046  }1047  .pwgen-slider {1048    flex: 1; min-width: 110px;1049    accent-color: var(--peach-accent);1050    cursor: pointer; height: 2px; background: transparent;1051  }1052  .pwgen-len-num {1053    font-family: "IBM Plex Mono", monospace; font-size: 11px;1054    color: var(--peach-accent); min-width: 22px; text-align: right;1055  }1056  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1057  .pwgen-pill {1058    padding: 3px 8px; border-radius: 999px;1059    border: 1px solid var(--peach-input-border);1060    background: transparent; color: var(--peach-text-muted);1061    font-family: "IBM Plex Mono", monospace; font-size: 9px;1062    letter-spacing: 0.06em; cursor: pointer;1063    transition: all 130ms ease;1064  }1065  .pwgen-pill.is-on {1066    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1067    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1068    color: var(--peach-accent);1069  }1070  .pwgen-pill:not(.is-on):hover {1071    color: var(--peach-text-dim);1072    border-color: var(--peach-text-muted);1073  }1074  .pwgen-policy-hint {1075    font-size: 10px; color: var(--peach-text-muted);1076    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1077    line-height: 1.3;1078  }1079  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }10801081  /* ── Save offer (after password filled) ───────────────────── */1082  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1083  .save-offer-title {1084    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1085  }1086  .save-offer-row {1087    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1088    border-radius: 7px; background: var(--peach-input-bg);1089    border: 1px solid var(--peach-input-border);1090  }1091  .save-offer-lbl {1092    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1093    font-family: "IBM Plex Mono", monospace;1094  }1095  .save-offer-val {1096    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1097    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1098  }1099  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1100  .save-offer-save {1101    flex: 1; padding: 9px; border-radius: 8px; border: none;1102    background: var(--peach-accent); color: #fff; font-size: 13px;1103    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1104  }1105  .save-offer-save:hover { filter: brightness(1.08); }1106  .save-offer-skip {1107    flex: 1; padding: 9px; border-radius: 8px; border: none;1108    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1109    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1110    font-family: Inter, sans-serif; transition: background 100ms ease;1111  }1112  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1113`;11141115export function showAutofillSelector(1116  anchorEl: HTMLInputElement,1117  entries: SelectorEntry[],1118  onSelect: (id: string) => void,1119  options: SelectorOptions = {}1120): () => void {1121  const host = document.createElement("div");1122  host.style.cssText = "position: absolute; z-index: 2147483647;";1123  host.style.setProperty("--peach-accent", accentHex);1124  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1125  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1126  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1127  const shadow = host.attachShadow({ mode: "closed" });11281129  const style = shadow.appendChild(document.createElement("style"));1130  style.textContent = SELECTOR_STYLES;11311132  const rect = anchorEl.getBoundingClientRect();1133  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1134  host.style.left = `${rect.left + window.scrollX}px`;1135  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1136  // wide single-input fields (e.g. centered email input on signup pages).1137  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;11381139  const container = shadow.appendChild(document.createElement("div"));1140  container.className = "peach-inline-popup";1141  container.setAttribute("data-theme", popupTheme);11421143  const searchableEntries = options.searchableEntries ?? [];1144  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();11451146  let query = "";1147  let focusedIndex = -1;1148  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1149  let searchInput: HTMLInputElement | null = null;1150  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1151  // setInterval. Add to this list — don't fan out the dismiss function.1152  const cleanupHooks: Array<() => void> = [];11531154  // Pre-capture the anchor field value for username prefill1155  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1156  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1157  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";11581159  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1160    const seen = new Set<string>();1161    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1162  }11631164  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1165    const q = value.trim().toLowerCase();1166    const deduped = uniqueEntries(source);1167    if (!q) return deduped.slice(0, 8);1168    return deduped.filter(e =>1169      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1170    ).slice(0, 12);1171  }11721173  function activeEntries(): SelectorEntry[] {1174    // When user is typing a search, filter across all known entries (domain matches + vault)1175    if (query.trim()) {1176      const merged = uniqueEntries([...entries, ...searchableEntries]);1177      return filterEntries(merged, query);1178    }1179    // Default: show domain matches; fall back to vault search when no matches1180    if (entries.length > 0) return entries;1181    return filterEntries(searchableEntries, "").slice(0, 8);1182  }11831184  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1185    const icon = document.createElement("div");1186    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1187    if (isNew) {1188      icon.innerHTML = plusSvgStr();1189    } else {1190      // Use the generic key glyph for all entries in the page-injected selector.1191      // Avoids disclosing vault domains to any third party and avoids needing1192      // to expose the browser favicon API to page context via web_accessible_resources.1193      void url;1194      icon.innerHTML = keySvgStr();1195    }1196    return icon;1197  }11981199  function renderIdentityHelper() {1200    container.innerHTML = "";1201    const identities = options.savedIdentities ?? [];12021203    // Header: "NEW ACCOUNT" + domain name1204    const hdr = container.appendChild(document.createElement("div"));1205    hdr.className = "domain-header";1206    const eyebrow = hdr.appendChild(document.createElement("div"));1207    eyebrow.className = "domain-eyebrow";1208    eyebrow.textContent = "NEW ACCOUNT";1209    const domName = hdr.appendChild(document.createElement("div"));1210    domName.className = "domain-name";1211    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");12121213    // Identity rows1214    const list = container.appendChild(document.createElement("div"));1215    list.className = "identity-list";1216    for (const id of identities) {1217      const row = list.appendChild(document.createElement("div"));1218      row.className = "peach-identity-row";1219      row.setAttribute("tabindex", "-1");1220      const val = row.appendChild(document.createElement("div"));1221      val.className = "peach-identity-value";1222      val.textContent = id.value;1223      const meta = row.appendChild(document.createElement("div"));1224      meta.className = "peach-identity-meta";1225      meta.textContent = `used ${id.useCount}×`;1226      row.addEventListener("click", () => {1227        options.onFillFields?.(id.value, "");1228        renderGenerator(id.value);1229      });1230    }12311232    // Divider before "Use a different email…"1233    if (identities.length > 0) {1234      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1235    }12361237    // "Use a different email…" expandable row1238    const altRow = container.appendChild(document.createElement("div"));1239    altRow.className = "identity-alt-row";1240    altRow.textContent = "+ Use a different email…";12411242    const altInputWrap = container.appendChild(document.createElement("div"));1243    altInputWrap.className = "identity-alt-input-wrap";1244    const altInput = altInputWrap.appendChild(document.createElement("input"));1245    altInput.className = "identity-alt-input";1246    altInput.type = "email";1247    altInput.placeholder = "[email protected]";1248    altInput.setAttribute("autocomplete", "off");1249    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1250    altConfirm.className = "identity-alt-confirm";1251    altConfirm.type = "button";1252    altConfirm.textContent = "✓";12531254    function fillCustomEmail() {1255      const v = altInput.value.trim();1256      if (!v) return;1257      options.onFillFields?.(v, "");1258      renderGenerator(v);1259    }12601261    altRow.addEventListener("click", () => {1262      altRow.style.display = "none";1263      altInputWrap.classList.add("open");1264      altInput.focus();1265    });1266    altConfirm.addEventListener("click", fillCustomEmail);1267    altInput.addEventListener("keydown", (e) => {1268      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1269    });1270  }12711272  function renderGenerator(filledEmail: string) {1273    container.innerHTML = "";1274    const sitePolicy = detectPasswordPolicy();12751276    const wrap = container.appendChild(document.createElement("div"));1277    wrap.className = "gen-view";12781279    // Header: domain + NEW ACCOUNT1280    const hdrRow = wrap.appendChild(document.createElement("div"));1281    hdrRow.className = "domain-header";1282    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1283    eyebrow2.className = "domain-eyebrow";1284    eyebrow2.textContent = "NEW ACCOUNT";1285    const domName2 = hdrRow.appendChild(document.createElement("div"));1286    domName2.className = "domain-name";1287    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");12881289    // Confirmed email row1290    const conf = wrap.appendChild(document.createElement("div"));1291    conf.className = "gen-confirmed";1292    const confCheck = conf.appendChild(document.createElement("span"));1293    confCheck.className = "gen-confirmed-check";1294    confCheck.textContent = "✓";1295    const confVal = conf.appendChild(document.createElement("div"));1296    confVal.className = "gen-confirmed-val";1297    confVal.textContent = filledEmail;12981299    const lbl = wrap.appendChild(document.createElement("div"));1300    lbl.className = "gen-label";1301    lbl.textContent = "Generate a password";13021303    let currentPw = "";1304    const smartGen = createSmartGenerator({1305      policy: sitePolicy,1306      onChange: (pw) => { currentPw = pw; },1307    });1308    wrap.appendChild(smartGen.root);13091310    const fillBtn = wrap.appendChild(document.createElement("button"));1311    fillBtn.className = "gen-fill-btn";1312    fillBtn.type = "button";1313    fillBtn.textContent = "Copy & fill";1314    fillBtn.addEventListener("click", () => {1315      if (!currentPw) return;1316      options.onFillFields?.("", currentPw);1317      renderSaveOffer(filledEmail, currentPw);1318    });1319  }13201321  function renderSaveOffer(filledEmail: string, filledPassword: string) {1322    container.innerHTML = "";1323    const domain = options.domain ?? location.hostname.replace(/^www\./, "");13241325    const wrap = container.appendChild(document.createElement("div"));1326    wrap.className = "save-offer";13271328    const title = wrap.appendChild(document.createElement("div"));1329    title.className = "save-offer-title";1330    title.textContent = "Save this login to Peach?";13311332    function detailRow(label: string, value: string) {1333      const row = wrap.appendChild(document.createElement("div"));1334      row.className = "save-offer-row";1335      const lbl = row.appendChild(document.createElement("div"));1336      lbl.className = "save-offer-lbl";1337      lbl.textContent = label;1338      const val = row.appendChild(document.createElement("div"));1339      val.className = "save-offer-val";1340      val.textContent = value;1341    }13421343    detailRow("site", domain);1344    detailRow("email", filledEmail);1345    detailRow("password", "••••••••••••••••");13461347    const btns = wrap.appendChild(document.createElement("div"));1348    btns.className = "save-offer-btns";13491350    const saveBtn = btns.appendChild(document.createElement("button"));1351    saveBtn.className = "save-offer-save";1352    saveBtn.type = "button";1353    saveBtn.textContent = "Save";1354    saveBtn.addEventListener("click", async () => {1355      saveBtn.disabled = true;1356      saveBtn.textContent = "Saving…";1357      try {1358        const res = await chrome.runtime.sendMessage({1359          type: "ADD_ENTRY",1360          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1361        });1362        if ((res as { ok?: boolean }).ok) {1363          showSuccess(sTitle);1364        } else {1365          saveBtn.disabled = false;1366          saveBtn.textContent = "Save";1367        }1368      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1369    });13701371    const skipBtn = btns.appendChild(document.createElement("button"));1372    skipBtn.className = "save-offer-skip";1373    skipBtn.type = "button";1374    skipBtn.textContent = "Not now";1375    skipBtn.addEventListener("click", () => { dismiss(true); });1376  }13771378  function renderList() {1379    container.innerHTML = "";1380    focusedIndex = -1;1381    searchInput = null;13821383    const current = activeEntries();13841385    // Domain header (always show) — eyebrow + domain on the left,1386    // a "+" shortcut to the create form on the right so the user is never1387    // trapped in the search list when they want to make a new entry.1388    const domHdr = document.createElement("div");1389    domHdr.className = "domain-header";1390    const headText = document.createElement("div");1391    headText.className = "domain-header-text";1392    const eyebrow = document.createElement("div");1393    eyebrow.className = "domain-eyebrow";1394    eyebrow.textContent = options.isSignup1395      ? "Sign up as"1396      : entries.length > 0 ? "Saved for this site" : "No saved login";1397    const domName = document.createElement("div");1398    domName.className = "domain-name";1399    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1400    headText.append(eyebrow, domName);1401    domHdr.appendChild(headText);14021403    if (!options.isSignup) {1404      const addBtn = document.createElement("button");1405      addBtn.className = "domain-add-btn";1406      addBtn.type = "button";1407      addBtn.setAttribute("aria-label", "Create new entry");1408      addBtn.title = "Create new entry";1409      addBtn.textContent = "+";1410      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1411      domHdr.appendChild(addBtn);1412    }14131414    container.appendChild(domHdr);14151416    // Search — always show so user can find entries beyond the domain matches1417    const sw = document.createElement("div"); sw.className = "search-wrap";1418    searchInput = document.createElement("input");1419    searchInput.className = "search";1420    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1421    searchInput.value = query;1422    searchInput.addEventListener("input", () => {1423      query = searchInput?.value ?? "";1424      renderList();1425      searchInput?.focus();1426      searchInput?.setSelectionRange(query.length, query.length);1427    });1428    sw.appendChild(searchInput);1429    container.appendChild(sw);14301431    // Results1432    const results = document.createElement("div");1433    results.className = "results";1434    container.appendChild(results);14351436    if (current.length === 0 && entries.length > 0) {1437      // Show a hint but don't render empty entries1438    }14391440    for (let i = 0; i < current.length; i++) {1441      const e = current[i]!;1442      const entryEl = document.createElement("div");1443      entryEl.className = "entry";1444      entryEl.dataset.id = e.id;1445      entryEl.dataset.index = String(i);1446      entryEl.setAttribute("tabindex", "-1");14471448      entryEl.appendChild(makeEntryIcon(e.url));14491450      const info = document.createElement("div"); info.className = "entry-info";1451      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1452      const subEl = document.createElement("div"); subEl.className = "entry-sub";1453      const domain = e.url ? getDomainFromUrl(e.url) : "";1454      subEl.textContent = domain || e.username || "";1455      info.append(titleEl, subEl);1456      entryEl.appendChild(info);14571458      if (e.hasTotp) {1459        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1460        entryEl.appendChild(badge);1461      }1462      if (e.hasPasskey) {1463        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1464        entryEl.appendChild(badge);1465      }14661467      entryEl.addEventListener("click", () => {1468        if (options.isSignup && options.onFillFields) {1469          // Signup mode: clicking a saved identity fills the username field1470          options.onFillFields(e.username ?? "", "");1471          dismiss();1472        } else {1473          onSelect(e.id);1474          dismiss();1475        }1476      });1477      results.appendChild(entryEl);1478    }14791480    // Divider before "New entry"1481    if (current.length > 0) {1482      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1483    }14841485    // "New entry" row — always present1486    const newEl = document.createElement("div");1487    newEl.className = "entry";1488    newEl.setAttribute("tabindex", "-1");1489    newEl.appendChild(makeEntryIcon(undefined, true));14901491    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1492    const newTitle = document.createElement("div");1493    newTitle.className = "entry-title is-new";1494    newTitle.textContent = `New entry for ${sTitle}`;1495    const newSub = document.createElement("div");1496    newSub.className = "entry-sub";1497    newSub.textContent = sOrigin;1498    newInfo.append(newTitle, newSub);1499    newEl.appendChild(newInfo);1500    newEl.addEventListener("click", showCreateForm);1501    results.appendChild(newEl);15021503    // Focus search if present1504    if (searchInput) {1505      requestAnimationFrame(() => searchInput?.focus());1506    }1507  }15081509  function setFocused(idx: number) {1510    const all = container.querySelectorAll<HTMLElement>(".entry");1511    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1512    focusedIndex = idx;1513    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1514  }15151516  async function showCreateForm() {1517    currentMode = "create";1518    container.innerHTML = "";15191520    // Guard: the service worker may lock the vault between when the selector1521    // opens and when the user clicks "New entry". Show the inline unlock form1522    // instead of silently failing on save.1523    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1524    if (!statusRes?.unlocked) {1525      renderLocked();1526      return;1527    }15281529    // Detect page password policy once for this form — reused on every1530    // regenerate click so the user always gets a compliant password.1531    const sitePolicy = detectPasswordPolicy();15321533    const wrap = document.createElement("div");1534    wrap.className = "create-form-wrap";15351536    // Header1537    const head = document.createElement("div"); head.className = "create-head";1538    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1539    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>`;1540    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1541    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1542    head.append(backBtn, lbl);15431544    // Body1545    const body = document.createElement("div"); body.className = "create-body";15461547    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1548      const g = document.createElement("div"); g.className = "f-group";1549      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1550      const inp = document.createElement("input"); inp.className = "f-input";1551      g.append(l, inp); return { g, inp };1552    }15531554    // Title1555    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1556    body.appendChild(tg.g);15571558    // URL1559    const ug = fGroup("website");1560    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1561    if (loginSubdomain) {1562      const h = document.createElement("div"); h.className = "url-hint";1563      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1564    }1565    body.appendChild(ug.g);15661567    // Username (pre-fill from anchor field)1568    const xg = fGroup("username / email");1569    xg.inp.value = preUsername; xg.inp.placeholder = "[email protected]";1570    xg.inp.setAttribute("autocomplete", "off");1571    body.appendChild(xg.g);15721573    // Password — full smart generator with charset pills + length slider +1574    // policy hint. Mirrors the main UI's compact generator so users get the1575    // same controls inline as in the popup.1576    const pg = fGroup("password");1577    let currentPassword = prePassword || "";1578    const smartGen = createSmartGenerator({1579      policy: sitePolicy,1580      initialPassword: prePassword || undefined,1581      onChange: (pw) => { currentPassword = pw; },1582    });1583    pg.g.appendChild(smartGen.root);1584    body.appendChild(pg.g);15851586    // Save1587    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1588    saveBtn.textContent = "Save entry";1589    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1590    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1591    saveBtn.addEventListener("click", async () => {1592      const title = tg.inp.value.trim();1593      const pw = currentPassword.trim();1594      const username = xg.inp.value.trim();1595      if (!title) {1596        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1597        showFormError("Entry needs a title");1598        return;1599      }1600      if (!pw) {1601        showFormError("Entry needs a password — tap regen to make one");1602        return;1603      }1604      errEl.style.display = "none";1605      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1606      try {1607        const res = await chrome.runtime.sendMessage({1608          type: "ADD_ENTRY",1609          payload: { title, url: ug.inp.value.trim(), username, password: pw, type: "login" },1610        });1611        if ((res as { ok?: boolean }).ok) {1612          // Fill the detected form regardless of mode. For login the user1613          // created an entry to use here; for signup the password was just1614          // generated for this site. Either way the credentials land in1615          // the form. options.onFillFields is wired by the caller (index.ts)1616          // and also records the form into filledForms so the popup will1617          // not re-attach to the filled fields.1618          options.onFillFields?.(username, pw);1619          showSuccess(title);1620        } else {1621          const errMsg = (res as { error?: string }).error === "vault locked"1622            ? "Vault locked — open Peach to save"1623            : "Could not save entry";1624          showFormError(errMsg);1625          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1626        }1627      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1628    });1629    body.appendChild(saveBtn);1630    body.appendChild(errEl);16311632    wrap.append(head, body);1633    container.appendChild(wrap);1634    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1635  }16361637  function showSuccess(title: string) {1638    currentMode = "success";1639    container.innerHTML = "";1640    const wrap = document.createElement("div"); wrap.className = "success-wrap";1641    const ring = document.createElement("div"); ring.className = "success-ring";1642    ring.innerHTML = checkSvgStr();1643    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1644    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1645    wrap.append(ring, t, s);1646    container.appendChild(wrap);1647    setTimeout(() => dismiss(), 1600);1648  }16491650  function flashActionBtn(btn: HTMLButtonElement) {1651    btn.classList.add("flashed");1652    setTimeout(() => btn.classList.remove("flashed"), 700);1653  }16541655  function renderSilverPlatter(entry: SelectorEntry) {1656    container.innerHTML = "";1657    searchInput = null;1658    focusedIndex = -1;1659    currentMode = "silver-platter";16601661    const domHdr = document.createElement("div");1662    domHdr.className = "domain-header";1663    const headText = document.createElement("div");1664    headText.className = "domain-header-text";1665    const eyebrow = document.createElement("div");1666    eyebrow.className = "domain-eyebrow";1667    eyebrow.textContent = "Saved for this site";1668    const domName = document.createElement("div");1669    domName.className = "domain-name";1670    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1671    headText.append(eyebrow, domName);1672    domHdr.appendChild(headText);1673    if (!options.isSignup) {1674      const addBtn = document.createElement("button");1675      addBtn.className = "domain-add-btn";1676      addBtn.type = "button";1677      addBtn.setAttribute("aria-label", "Create new entry");1678      addBtn.title = "Create new entry";1679      addBtn.textContent = "+";1680      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1681      domHdr.appendChild(addBtn);1682    }1683    container.appendChild(domHdr);16841685    const platter = document.createElement("div");1686    platter.className = "silver-platter";16871688    const titleEl = document.createElement("div");1689    titleEl.className = "sp-title";1690    titleEl.textContent = entry.title;1691    platter.appendChild(titleEl);16921693    if (entry.email) {1694      const emailEl = document.createElement("div");1695      emailEl.className = "sp-identity-row";1696      const emailLbl = document.createElement("span");1697      emailLbl.className = "sp-identity-label";1698      emailLbl.textContent = "email";1699      const emailVal = document.createElement("span");1700      emailVal.className = "sp-username";1701      emailVal.textContent = entry.email;1702      emailEl.append(emailLbl, emailVal);1703      platter.appendChild(emailEl);1704    }17051706    if (entry.username) {1707      const userEl = document.createElement("div");1708      userEl.className = "sp-identity-row";1709      const userLbl = document.createElement("span");1710      userLbl.className = "sp-identity-label";1711      userLbl.textContent = entry.username.includes("@") ? "email" : "username";1712      const userVal = document.createElement("span");1713      userVal.className = "sp-username";1714      userVal.textContent = entry.username;1715      userEl.append(userLbl, userVal);1716      platter.appendChild(userEl);1717    }17181719    const fillBtn = document.createElement("button");1720    fillBtn.className = "sp-fill-btn";1721    fillBtn.type = "button";1722    fillBtn.textContent = "Fill credentials";1723    fillBtn.addEventListener("click", () => {1724      if (fillBtn.disabled) return;1725      fillBtn.disabled = true;1726      fillBtn.classList.add("filled");1727      fillBtn.innerHTML = checkSvgStr();1728      // Fire the fill, then exit via the standard exit animation. The fill1729      // itself is async (handled in index.ts) — by 400ms the form is filled1730      // and the popup begins its exit. Total dwell from click to host1731      // removal: 400ms + 130ms (exit animation) = 530ms.1732      onSelect(entry.id);1733      setTimeout(() => dismiss(), 400);1734    });1735    platter.appendChild(fillBtn);17361737    const actions = document.createElement("div");1738    actions.className = "sp-actions";17391740    if (entry.email) {1741      const copyEmail = document.createElement("button");1742      copyEmail.className = "sp-action-btn";1743      copyEmail.type = "button";1744      copyEmail.title = "Copy email";1745      copyEmail.textContent = "Copy email";1746      copyEmail.addEventListener("click", async (e) => {1747        e.stopPropagation();1748        let alreadyWritten = false;1749        try { await navigator.clipboard.writeText(entry.email!); alreadyWritten = true; } catch {}1750        await chrome.runtime.sendMessage({1751          type: "COPY",1752          payload: { text: entry.email, label: "Email", alreadyWritten },1753        }).catch(() => {});1754        flashActionBtn(copyEmail);1755      });1756      actions.appendChild(copyEmail);1757    }17581759    const copyU = document.createElement("button");1760    copyU.className = "sp-action-btn";1761    copyU.type = "button";1762    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";1763    copyU.title = copyULabel;1764    copyU.textContent = copyULabel;1765    copyU.disabled = !entry.username;1766    copyU.addEventListener("click", async (e) => {1767      e.stopPropagation();1768      if (!entry.username) return;1769      let alreadyWritten = false;1770      try { await navigator.clipboard.writeText(entry.username); alreadyWritten = true; } catch {}1771      await chrome.runtime.sendMessage({1772        type: "COPY",1773        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },1774      }).catch(() => {});1775      flashActionBtn(copyU);1776    });1777    actions.appendChild(copyU);17781779    const copyP = document.createElement("button");1780    copyP.className = "sp-action-btn";1781    copyP.type = "button";1782    copyP.title = "Copy password";1783    copyP.textContent = "Copy password";1784    copyP.addEventListener("click", async (e) => {1785      e.stopPropagation();1786      const resp = await chrome.runtime.sendMessage({1787        type: "GET_ENTRY_FOR_FILL",1788        payload: { id: entry.id },1789      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;1790      if (!resp?.ok || !resp.data?.password) return;1791      let alreadyWritten = false;1792      try { await navigator.clipboard.writeText(resp.data.password); alreadyWritten = true; } catch {}1793      await chrome.runtime.sendMessage({1794        type: "COPY",1795        payload: { text: resp.data.password, label: "Password", alreadyWritten },1796      }).catch(() => {});1797      flashActionBtn(copyP);1798    });1799    actions.appendChild(copyP);18001801    let trayEl: HTMLDivElement | null = null;1802    let trayInterval: ReturnType<typeof setInterval> | null = null;18031804    function closeTray() {1805      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }1806      trayEl?.remove();1807      trayEl = null;1808    }1809    // Register so dismiss() will close the tray and clear the interval1810    // even if the user dismisses without explicitly closing the tray.1811    cleanupHooks.push(closeTray);18121813    async function openTOTPTray() {1814      // Fetch the entry to get the TOTP secret. The selector summary doesn't1815      // carry it (and shouldn't — passing secrets only at fill/copy time keeps1816      // the message-passing surface minimal per Projects.md §5.2).1817      const resp = await chrome.runtime.sendMessage({1818        type: "GET_ENTRY_FOR_FILL",1819        payload: { id: entry.id },1820      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;1821      const secret = resp?.ok ? resp.data?.totp : undefined;1822      if (!secret) return;18231824      trayEl = document.createElement("div");1825      trayEl.className = "sp-tray";18261827      const label = document.createElement("span");1828      label.className = "sp-tray-label";1829      label.textContent = "2FA";1830      trayEl.appendChild(label);18311832      const codeEl = document.createElement("div");1833      codeEl.className = "sp-totp-code";1834      trayEl.appendChild(codeEl);18351836      const ringNs = "http://www.w3.org/2000/svg";1837      const ring = document.createElementNS(ringNs, "svg");1838      ring.setAttribute("class", "sp-totp-ring");1839      ring.setAttribute("viewBox", "0 0 24 24");1840      const trackC = document.createElementNS(ringNs, "circle");1841      trackC.setAttribute("class", "ring-track");1842      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");1843      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");1844      const fillC = document.createElementNS(ringNs, "circle");1845      fillC.setAttribute("class", "ring-fill");1846      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");1847      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");1848      fillC.setAttribute("stroke-linecap", "round");1849      fillC.setAttribute("stroke-dasharray", "62.83");1850      ring.append(trackC, fillC);1851      trayEl.appendChild(ring);18521853      const copyBtn = document.createElement("button");1854      copyBtn.className = "sp-totp-copy";1855      copyBtn.type = "button";1856      copyBtn.textContent = "Copy";1857      trayEl.appendChild(copyBtn);18581859      function refresh() {1860        const { code, remaining } = generateTOTP(secret!);1861        // Group as "847 291" — easier to read than "847291"1862        codeEl.textContent = code.length === 61863          ? `${code.slice(0, 3)} ${code.slice(3)}`1864          : code;1865        // Ring fills counter-clockwise as time elapses: dashoffset goes from1866        // 0 (full ring) to 62.83 (empty) over the 30s window.1867        const fraction = (30 - remaining) / 30;1868        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));1869      }1870      refresh();1871      trayInterval = setInterval(refresh, 1000);18721873      copyBtn.addEventListener("click", async (e) => {1874        e.stopPropagation();1875        const { code } = generateTOTP(secret!);1876        let alreadyWritten = false;1877        try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}1878        await chrome.runtime.sendMessage({1879          type: "COPY",1880          payload: { text: code, label: "TOTP", alreadyWritten },1881        }).catch(() => {});1882        copyBtn.textContent = "Copied";1883        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);1884      });18851886      platter.appendChild(trayEl);1887    }18881889    const editBtn = document.createElement("button");1890    editBtn.className = "sp-action-btn sp-action-edit";1891    editBtn.type = "button";1892    editBtn.title = "Edit entry";1893    editBtn.textContent = "Edit";1894    editBtn.addEventListener("click", (e) => {1895      e.stopPropagation();1896      closeTray();1897      void renderInlineEdit(entry);1898    });1899    actions.appendChild(editBtn);19001901    // Always show the 2FA tray when the entry has TOTP — hiding it behind a1902    // "···" toggle was zero-savings (the toggle button took the same space1903    // the "2FA" label needed) and made the code one extra click away.1904    if (entry.hasTotp) void openTOTPTray();19051906    platter.appendChild(actions);1907    container.appendChild(platter);1908  }19091910  /**1911   * Inline-popup edit mode. Swaps the silver platter for an editable form1912   * over the same shadow-DOM surface so the user never leaves the page.1913   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter1914   * with the new fields. Cancel returns without writing.1915   */1916  async function renderInlineEdit(summary: SelectorEntry) {1917    container.innerHTML = "";1918    const wrap = document.createElement("div");1919    wrap.className = "create-form-wrap";19201921    const head = document.createElement("div");1922    head.className = "create-head";1923    const back = document.createElement("button");1924    back.className = "back-btn";1925    back.type = "button";1926    back.title = "Cancel";1927    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>`;1928    back.addEventListener("click", () => renderSilverPlatter(summary));1929    head.appendChild(back);1930    const headLbl = document.createElement("div");1931    headLbl.className = "create-label";1932    headLbl.textContent = "Edit entry";1933    head.appendChild(headLbl);1934    wrap.appendChild(head);19351936    const body = document.createElement("div");1937    body.className = "create-body";19381939    // Loading shimmer while we fetch the full entry1940    const loading = document.createElement("div");1941    loading.className = "empty-hint";1942    loading.textContent = "loading…";1943    body.appendChild(loading);1944    wrap.appendChild(body);1945    container.appendChild(wrap);19461947    const res = (await chrome.runtime.sendMessage({1948      type: "GET_ENTRY_FOR_FILL",1949      payload: { id: summary.id },1950    }).catch(() => null)) as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;19511952    if (!res || !res.ok || !res.data) {1953      loading.textContent = "couldn't load this entry. try again from the popup.";1954      return;1955    }1956    body.innerHTML = "";19571958    function field(label: string, value: string, type: "text" | "password" = "text"): HTMLInputElement {1959      const group = document.createElement("div");1960      group.className = "f-group";1961      const lbl = document.createElement("div");1962      lbl.className = "f-label";1963      lbl.textContent = label;1964      const input = document.createElement("input");1965      input.className = "f-input";1966      input.type = type;1967      input.value = value;1968      input.autocomplete = "off";1969      group.append(lbl, input);1970      body.appendChild(group);1971      return input;1972    }19731974    const titleInput = field("title", res.data.title ?? "");1975    const urlInput = field("url", res.data.url ?? "");1976    urlInput.classList.add("url-f");1977    const usernameLabel = (res.data.username ?? "").includes("@") ? "email" : "username";1978    const usernameInput = field(usernameLabel, res.data.username ?? "");1979    const emailInput = field("email", res.data.email ?? "");19801981    // Password row with reveal toggle1982    const pwGroup = document.createElement("div");1983    pwGroup.className = "f-group";1984    const pwLbl = document.createElement("div");1985    pwLbl.className = "f-label";1986    pwLbl.textContent = "password";1987    const pwRow = document.createElement("div");1988    pwRow.className = "f-row";1989    const pwInput = document.createElement("input");1990    pwInput.className = "f-input";1991    pwInput.type = "password";1992    pwInput.value = res.data.password ?? "";1993    pwInput.autocomplete = "new-password";1994    const revealBtn = document.createElement("button");1995    revealBtn.className = "gen-btn";1996    revealBtn.type = "button";1997    revealBtn.textContent = "show";1998    revealBtn.addEventListener("click", () => {1999      const reveal = pwInput.type === "password";2000      pwInput.type = reveal ? "text" : "password";2001      revealBtn.textContent = reveal ? "hide" : "show";2002    });2003    pwRow.append(pwInput, revealBtn);2004    pwGroup.append(pwLbl, pwRow);2005    body.appendChild(pwGroup);20062007    const totpInput = field("2fa secret", res.data.totp ?? "");20082009    // Notes2010    const notesGroup = document.createElement("div");2011    notesGroup.className = "f-group";2012    const notesLbl = document.createElement("div");2013    notesLbl.className = "f-label";2014    notesLbl.textContent = "notes";2015    const notesInput = document.createElement("textarea");2016    notesInput.className = "f-input";2017    notesInput.rows = 3;2018    notesInput.value = res.data.notes ?? "";2019    notesInput.style.fontFamily = "Inter, sans-serif";2020    notesInput.style.resize = "vertical";2021    notesGroup.append(notesLbl, notesInput);2022    body.appendChild(notesGroup);20232024    // Save / Cancel row2025    const actionsRow = document.createElement("div");2026    actionsRow.className = "f-row";2027    const saveBtn = document.createElement("button");2028    saveBtn.className = "save-btn";2029    saveBtn.type = "button";2030    saveBtn.textContent = "Save changes";2031    saveBtn.style.flex = "1";2032    const cancelBtn = document.createElement("button");2033    cancelBtn.className = "gen-btn";2034    cancelBtn.type = "button";2035    cancelBtn.textContent = "cancel";2036    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2037    actionsRow.append(saveBtn, cancelBtn);2038    body.appendChild(actionsRow);20392040    saveBtn.addEventListener("click", async () => {2041      saveBtn.disabled = true;2042      const originalLabel = saveBtn.textContent;2043      saveBtn.textContent = "Saving…";2044      const patch: Record<string, unknown> = {2045        title: titleInput.value.trim(),2046        url: urlInput.value.trim(),2047        username: usernameInput.value.trim(),2048        email: emailInput.value.trim() || undefined,2049        password: pwInput.value,2050        totp: totpInput.value.trim(),2051        notes: notesInput.value,2052      };2053      const updateRes = (await chrome.runtime.sendMessage({2054        type: "UPDATE_ENTRY",2055        payload: { id: summary.id, patch },2056      }).catch(() => null)) as { ok: boolean; error?: string } | null;2057      if (!updateRes?.ok) {2058        saveBtn.disabled = false;2059        saveBtn.textContent = originalLabel;2060        const err = document.createElement("div");2061        err.className = "empty-hint";2062        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2063        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2064        body.appendChild(err);2065        setTimeout(() => err.remove(), 3000);2066        return;2067      }2068      // Refresh the platter with updated summary fields2069      const refreshed: SelectorEntry = {2070        id: summary.id,2071        title: patch.title as string,2072        username: patch.username as string,2073        email: patch.email as string | undefined,2074        url: patch.url as string,2075        hasTotp: Boolean(patch.totp),2076        hasPasskey: summary.hasPasskey,2077      };2078      renderSilverPlatter(refreshed);2079    });20802081    queueMicrotask(() => titleInput.focus());2082  }20832084  function renderLocked() {2085    container.innerHTML = "";20862087    // Domain header (same as list view)2088    const domHdr = document.createElement("div");2089    domHdr.className = "domain-header";2090    const eyebrow = document.createElement("div");2091    eyebrow.className = "domain-eyebrow";2092    eyebrow.textContent = "vault locked";2093    const domName = document.createElement("div");2094    domName.className = "domain-name";2095    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2096    domHdr.append(eyebrow, domName);2097    container.appendChild(domHdr);20982099    const wrap = document.createElement("div");2100    wrap.className = "locked-wrap";21012102    // Icon + label row2103    const head = document.createElement("div"); head.className = "locked-head";2104    const icon = document.createElement("div"); icon.className = "locked-icon";2105    icon.innerHTML = keySvgStr();2106    const title = document.createElement("div"); title.className = "locked-title";2107    title.textContent = "unlock to autofill";2108    head.append(icon, title);21092110    // Password input2111    const pwInp = document.createElement("input");2112    pwInp.className = "locked-input";2113    pwInp.type = "password";2114    pwInp.placeholder = "master password";2115    pwInp.setAttribute("autocomplete", "current-password");21162117    // Error line (hidden initially)2118    const errEl = document.createElement("div");2119    errEl.className = "locked-error";2120    errEl.style.display = "none";21212122    // Unlock button2123    const unlockBtn = document.createElement("button");2124    unlockBtn.className = "locked-btn";2125    unlockBtn.type = "button";2126    unlockBtn.textContent = "unlock";21272128    async function tryUnlock() {2129      const pw = pwInp.value.trim();2130      if (!pw) { pwInp.focus(); return; }2131      unlockBtn.disabled = true;2132      unlockBtn.textContent = "unlocking…";2133      errEl.style.display = "none";2134      try {2135        const res = await chrome.runtime.sendMessage({2136          type: "UNLOCK",2137          payload: { password: pw },2138        });2139        if ((res as { ok?: boolean }).ok) {2140          dismiss();2141          options.onUnlocked?.();2142        } else {2143          errEl.textContent = "incorrect password";2144          errEl.style.display = "block";2145          pwInp.value = "";2146          pwInp.focus();2147          unlockBtn.disabled = false;2148          unlockBtn.textContent = "unlock";2149        }2150      } catch {2151        errEl.textContent = "could not reach Peach";2152        errEl.style.display = "block";2153        unlockBtn.disabled = false;2154        unlockBtn.textContent = "unlock";2155      }2156    }21572158    pwInp.addEventListener("keydown", (e) => {2159      e.stopPropagation();2160      if (e.key === "Enter") void tryUnlock();2161    });2162    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2163    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2164    unlockBtn.addEventListener("click", () => void tryUnlock());21652166    wrap.append(head, pwInp, errEl, unlockBtn);2167    container.appendChild(wrap);21682169    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2170    // the page reclaims focus from our Shadow DOM input before the user can2171    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2172    // Instead: intercept keystrokes at the document capture phase — this runs2173    // before any page handler regardless of which element technically has2174    // OS focus — and route them into our input.2175    const captureKeydown = (e: KeyboardEvent) => {2176      if (!host.isConnected) {2177        document.removeEventListener("keydown", captureKeydown, true);2178        return;2179      }2180      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2181      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2182      // Intercept before page handlers and give our input focus.2183      e.stopImmediatePropagation();2184      if (e.key === "Escape") { dismiss(true); return; }2185      if (e.key === "Enter") { void tryUnlock(); return; }2186      // For all other printable/editing keys, ensure our input has focus so2187      // the browser delivers the keystroke there naturally.2188      if (document.activeElement !== host) {2189        pwInp.focus({ preventScroll: true });2190      }2191    };2192    captureKeydownRef = captureKeydown;2193    document.addEventListener("keydown", captureKeydown, true);21942195    // Best-effort focus on open — may be overridden by page focus trap,2196    // but the capture listener above handles typing regardless.2197    pwInp.focus({ preventScroll: true });2198    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2199  }22002201  function handleKeyDown(e: KeyboardEvent) {2202    if (options.locked) {2203      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2204      return;2205    }2206    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2207      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2208      return;2209    }2210    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2211    const count = allEntryEls.length;2212    if (document.activeElement === searchInput) {2213      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2214      if (count === 0) return;2215      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2216    }2217    if (count === 0) return;2218    switch (e.key) {2219      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2220      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2221      case "Enter": {2222        if (focusedIndex >= 0) {2223          const el = allEntryEls[focusedIndex] as HTMLElement;2224          const id = el.dataset.id;2225          if (id) { onSelect(id); dismiss(); }2226          else if (el.classList.contains("is-new") || !id) {2227            // "New entry" row (last item, no data-id)2228            showCreateForm();2229          }2230        }2231        break;2232      }2233      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2234    }2235  }22362237  document.addEventListener("keydown", handleKeyDown);22382239  document.body.appendChild(host);22402241  function updatePosition() {2242    const r = anchorEl.getBoundingClientRect();2243    host.style.top = `${r.bottom + window.scrollY + 5}px`;2244    host.style.left = `${r.left + window.scrollX}px`;2245  }2246  // These bindings are referenced from renderLocked()/dismiss() — they MUST2247  // be initialized before renderLocked() runs, or the synchronous assignment2248  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2249  // and throws ReferenceError. The throw lands after the popup is rendered2250  // but before showAutofillSelector returns its dismiss handle, leaving an2251  // orphan host in the DOM (which is what caused the locked-popup stacking2252  // and missing autofocus on every click).2253  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2254  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);22552256  if (options.locked) {2257    renderLocked();2258  } else if (options.isSignup && options.savedIdentities) {2259    // State 10: identity helper — signup form detected, show derived2260    // identity list (emails then usernames) instead of vault entry list.2261    renderIdentityHelper();2262  } else if (entries.length === 1 && !options.isSignup) {2263    // Silver platter (State 1): single domain match → focused fill view.2264    // Multi-match goes through renderList instead.2265    renderSilverPlatter(entries[0]!);2266  } else {2267    renderList();2268  }22692270  let exitScheduled = false;2271  function dismiss(userAction = false) {2272    // Idempotent: dismiss() can be called from multiple paths (Escape,2273    // outside click, entry select, fill success, host page nav). The exit2274    // animation must only play once and host.remove() must run exactly once.2275    if (exitScheduled) return;2276    exitScheduled = true;2277    // Detach listeners synchronously so nothing can re-trigger during the2278    // 130ms exit window (a focusin firing here would race against the2279    // dismiss-lock work in Pass 2).2280    stopObserving();2281    document.removeEventListener("click", outsideClick, { capture: true });2282    document.removeEventListener("keydown", handleKeyDown);2283    if (captureKeydownRef) {2284      document.removeEventListener("keydown", captureKeydownRef, true);2285      captureKeydownRef = null;2286    }2287    for (const cleanup of cleanupHooks) {2288      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2289    }2290    if (userAction) options.onDismiss?.();2291    container.classList.add("is-exiting");2292    setTimeout(() => host.remove(), 130);2293  }22942295  function outsideClick(ev: MouseEvent) {2296    const path = ev.composedPath();2297    // Never dismiss when clicking the anchor field itself — that click is2298    // what triggered the selector to open, and the user may click the field2299    // again to re-focus it without intending to close the selector.2300    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2301  }2302  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2303  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);23042305  return dismiss;2306}23072308export interface CardSelectorEntry {2309  id: string;2310  title: string;2311  cardholderName?: string;2312  last4?: string;2313  expMonth?: string;2314  expYear?: string;2315  network?: import("../shared/types").CardNetwork;2316}23172318interface CardSelectorOptions {2319  domain?: string;2320  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2321  onFill: (entry: import("../shared/types").VaultEntry) => void;2322  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2323  onDismiss?: () => void;2324}23252326/**2327 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2328 * passkey create or get. Renders as a fixed-position floating popup (no2329 * field anchor needed — passkeys don't require a focused input). Uses the2330 * same theme tokens and entrance animation as all other inline popup states.2331 */2332export function showPasskeyProGate(): void {2333  const domain = location.hostname.replace(/^www\./, "");23342335  const host = document.createElement("div");2336  host.setAttribute("data-peach-passkey-gate", "1");2337  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2338  const shadow = host.attachShadow({ mode: "closed" });23392340  const style = document.createElement("style");2341  style.textContent = `2342    :host { all: initial; }2343    .gate-wrap {2344      position: fixed;2345      top: 50%;2346      left: 50%;2347      transform: translate(-50%, -50%);2348      width: 280px;2349      pointer-events: auto;2350      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2351    }2352    @keyframes g-in {2353      from { opacity:0; transform: translate(-50%,-52%); }2354      to   { opacity:1; transform: translate(-50%,-50%); }2355    }2356    .gate-wrap.is-exiting {2357      animation: g-out 130ms ease-in forwards;2358    }2359    @keyframes g-out {2360      to { opacity:0; transform: translate(-50%,-52%); }2361    }2362    .gate {2363      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2364      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2365      border-radius: 12px;2366      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2367      padding: 16px;2368      font-family: Inter, sans-serif;2369    }2370    .gate-header {2371      display: flex;2372      align-items: center;2373      gap: 7px;2374      margin-bottom: 12px;2375      padding-bottom: 10px;2376      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2377    }2378    .gate-domain {2379      font-size: 12px;2380      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2381      font-family: "IBM Plex Mono", monospace;2382      overflow: hidden;2383      text-overflow: ellipsis;2384      white-space: nowrap;2385    }2386    .gate-title {2387      font-size: 14px;2388      font-weight: 500;2389      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2390      margin-bottom: 6px;2391    }2392    .gate-subtitle {2393      font-size: 12px;2394      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2395      line-height: 1.5;2396      margin-bottom: 14px;2397    }2398    .gate-btn {2399      display: block;2400      width: 100%;2401      padding: 9px 0;2402      border-radius: 8px;2403      border: none;2404      cursor: pointer;2405      font-size: 13px;2406      font-family: Inter, sans-serif;2407      font-weight: 500;2408      transition: opacity 100ms;2409      margin-bottom: 7px;2410      text-align: center;2411    }2412    .gate-btn:last-child { margin-bottom: 0; }2413    .gate-btn--accent {2414      background: ${accentHex};2415      color: #fff;2416    }2417    .gate-btn--accent:hover { opacity: 0.88; }2418    .gate-btn--ghost {2419      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2420      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2421    }2422    .gate-btn--ghost:hover { opacity: 0.75; }2423    .backdrop {2424      position: fixed;2425      inset: 0;2426      pointer-events: auto;2427    }2428  `;2429  shadow.appendChild(style);24302431  const backdrop = document.createElement("div");2432  backdrop.className = "backdrop";2433  shadow.appendChild(backdrop);24342435  const wrap = document.createElement("div");2436  wrap.className = "gate-wrap";2437  shadow.appendChild(wrap);24382439  const gate = document.createElement("div");2440  gate.className = "gate";2441  wrap.appendChild(gate);24422443  // Header: peach icon + domain2444  const header = document.createElement("div");2445  header.className = "gate-header";2446  const icon = document.createElement("span");2447  icon.innerHTML = peachIconSvg();2448  const domainEl = document.createElement("span");2449  domainEl.className = "gate-domain";2450  domainEl.textContent = domain;2451  header.append(icon, domainEl);2452  gate.appendChild(header);24532454  const title = document.createElement("div");2455  title.className = "gate-title";2456  title.textContent = "Passkeys are part of Peach Pro.";2457  gate.appendChild(title);24582459  const subtitle = document.createElement("div");2460  subtitle.className = "gate-subtitle";2461  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2462  gate.appendChild(subtitle);24632464  const upgradeBtn = document.createElement("button");2465  upgradeBtn.className = "gate-btn gate-btn--accent";2466  upgradeBtn.type = "button";2467  upgradeBtn.textContent = "Upgrade to Pro";2468  gate.appendChild(upgradeBtn);24692470  const laterBtn = document.createElement("button");2471  laterBtn.className = "gate-btn gate-btn--ghost";2472  laterBtn.type = "button";2473  laterBtn.textContent = "Not right now";2474  gate.appendChild(laterBtn);24752476  function dismiss() {2477    wrap.classList.add("is-exiting");2478    setTimeout(() => host.remove(), 130);2479  }24802481  upgradeBtn.addEventListener("click", () => {2482    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2483    dismiss();2484  });2485  laterBtn.addEventListener("click", dismiss);2486  backdrop.addEventListener("click", dismiss);24872488  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2489    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2490  });24912492  document.body.appendChild(host);2493}24942495/**2496 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2497 * detector sees the page invoke navigator.credentials.create(); content/index.ts2498 * checks vault + decline state then calls this. "Save passkey to Peach"2499 * initiates the popup-context credential flow; "Not now" records a 30-day2500 * decline for the domain so we don't re-show on every page reload.2501 */2502export function showPasskeyRegistrationOffer(args: {2503  rpId: string;2504  rpName?: string;2505  userName?: string;2506  userDisplayName?: string;2507}): void {2508  const domain = location.hostname.replace(/^www\./, "");2509  const displayName = args.rpName || domain;25102511  const host = document.createElement("div");2512  host.setAttribute("data-peach-passkey-offer", "1");2513  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2514  const shadow = host.attachShadow({ mode: "closed" });25152516  const style = document.createElement("style");2517  style.textContent = `2518    :host { all: initial; }2519    .offer-wrap {2520      position: fixed;2521      top: 16px;2522      right: 16px;2523      width: 320px;2524      pointer-events: auto;2525      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2526    }2527    @keyframes o-in {2528      from { opacity: 0; transform: translateY(-6px); }2529      to   { opacity: 1; transform: translateY(0); }2530    }2531    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2532    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2533    .offer {2534      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2535      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2536      border-radius: 12px;2537      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2538      padding: 14px 14px 12px;2539      font-family: Inter, sans-serif;2540      position: relative;2541    }2542    .offer-close {2543      position: absolute;2544      top: 8px;2545      right: 8px;2546      width: 18px;2547      height: 18px;2548      border: none;2549      background: transparent;2550      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2551      cursor: pointer;2552      font-size: 14px;2553      line-height: 1;2554      padding: 0;2555    }2556    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2557    .offer-header {2558      display: flex;2559      align-items: center;2560      gap: 7px;2561      margin-bottom: 8px;2562      padding-bottom: 8px;2563      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2564    }2565    .offer-domain {2566      font-size: 12px;2567      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2568      font-family: "IBM Plex Mono", monospace;2569      overflow: hidden;2570      text-overflow: ellipsis;2571      white-space: nowrap;2572    }2573    .offer-title {2574      font-size: 13px;2575      font-weight: 500;2576      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2577      margin-bottom: 4px;2578    }2579    .offer-subtitle {2580      font-size: 11px;2581      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2582      line-height: 1.45;2583      margin-bottom: 12px;2584    }2585    .offer-btn {2586      display: block;2587      width: 100%;2588      padding: 8px 0;2589      border-radius: 7px;2590      border: none;2591      cursor: pointer;2592      font-size: 12px;2593      font-family: Inter, sans-serif;2594      font-weight: 500;2595      transition: opacity 100ms;2596      margin-bottom: 6px;2597      text-align: center;2598    }2599    .offer-btn:last-child { margin-bottom: 0; }2600    .offer-btn--accent { background: ${accentHex}; color: #fff; }2601    .offer-btn--accent:hover { opacity: 0.88; }2602    .offer-btn--ghost {2603      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2604      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2605    }2606    .offer-btn--ghost:hover { opacity: 0.75; }2607  `;2608  shadow.appendChild(style);26092610  const wrap = document.createElement("div");2611  wrap.className = "offer-wrap";2612  shadow.appendChild(wrap);26132614  const offer = document.createElement("div");2615  offer.className = "offer";2616  wrap.appendChild(offer);26172618  const closeBtn = document.createElement("button");2619  closeBtn.className = "offer-close";2620  closeBtn.type = "button";2621  closeBtn.setAttribute("aria-label", "Dismiss");2622  closeBtn.textContent = "✕";2623  offer.appendChild(closeBtn);26242625  const header = document.createElement("div");2626  header.className = "offer-header";2627  const icon = document.createElement("span");2628  icon.innerHTML = peachIconSvg();2629  const domainEl = document.createElement("span");2630  domainEl.className = "offer-domain";2631  domainEl.textContent = domain;2632  header.append(icon, domainEl);2633  offer.appendChild(header);26342635  const title = document.createElement("div");2636  title.className = "offer-title";2637  title.textContent = "This site supports passkeys.";2638  offer.appendChild(title);26392640  const subtitle = document.createElement("div");2641  subtitle.className = "offer-subtitle";2642  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2643  offer.appendChild(subtitle);26442645  const saveBtn = document.createElement("button");2646  saveBtn.className = "offer-btn offer-btn--accent";2647  saveBtn.type = "button";2648  saveBtn.textContent = "Save passkey to Peach";2649  offer.appendChild(saveBtn);26502651  const laterBtn = document.createElement("button");2652  laterBtn.className = "offer-btn offer-btn--ghost";2653  laterBtn.type = "button";2654  laterBtn.textContent = "Not now";2655  offer.appendChild(laterBtn);26562657  function dismiss(decline: boolean) {2658    if (decline) {2659      chrome.runtime.sendMessage({2660        type: "PASSKEY_OFFER_DECLINE",2661        payload: { domain },2662      }).catch(() => {});2663    }2664    wrap.classList.add("is-exiting");2665    setTimeout(() => host.remove(), 130);2666  }26672668  saveBtn.addEventListener("click", () => {2669    chrome.runtime.sendMessage({2670      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2671      payload: {2672        rpId: args.rpId,2673        rpName: args.rpName ?? displayName,2674        userName: args.userName ?? "user",2675        userDisplayName: args.userDisplayName,2676      },2677    }).catch(() => {});2678    dismiss(false);2679  });2680  laterBtn.addEventListener("click", () => dismiss(true));2681  closeBtn.addEventListener("click", () => dismiss(true));26822683  document.body.appendChild(host);2684}26852686/**2687 * State 11 — passkey available indicator. Shown when the user lands on a2688 * domain for which they already have a stored passkey. Tells them where to2689 * find it (the entry already shows in the vault list); the "Sign in with2690 * passkey" button opens the popup so they can use the platform authenticator2691 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2692 * the actual sign-in transparently, so this banner is informational only.2693 */2694export function showPasskeyAvailable(args: {2695  rpId: string;2696  userName: string;2697  fromBrowser?: "chrome" | "firefox";2698  currentBrowser?: "chrome" | "firefox" | "unknown";2699}): void {2700  const domain = location.hostname.replace(/^www\./, "");2701  const crossBrowser =2702    args.fromBrowser &&2703    args.currentBrowser &&2704    args.currentBrowser !== "unknown" &&2705    args.fromBrowser !== args.currentBrowser;27062707  const host = document.createElement("div");2708  host.setAttribute("data-peach-passkey-available", "1");2709  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2710  const shadow = host.attachShadow({ mode: "closed" });27112712  const style = document.createElement("style");2713  style.textContent = `2714    :host { all: initial; }2715    .avail-wrap {2716      position: fixed;2717      top: 16px;2718      right: 16px;2719      width: 320px;2720      pointer-events: auto;2721      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;2722    }2723    @keyframes a-in {2724      from { opacity: 0; transform: translateY(-6px); }2725      to   { opacity: 1; transform: translateY(0); }2726    }2727    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }2728    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }2729    .avail {2730      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2731      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2732      border-radius: 12px;2733      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2734      padding: 14px 14px 12px;2735      font-family: Inter, sans-serif;2736      position: relative;2737    }2738    .avail-close {2739      position: absolute;2740      top: 8px;2741      right: 8px;2742      width: 18px;2743      height: 18px;2744      border: none;2745      background: transparent;2746      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2747      cursor: pointer;2748      font-size: 14px;2749      line-height: 1;2750      padding: 0;2751    }2752    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2753    .avail-header {2754      display: flex;2755      align-items: center;2756      gap: 7px;2757      margin-bottom: 8px;2758      padding-bottom: 8px;2759      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2760    }2761    .avail-domain {2762      font-size: 12px;2763      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2764      font-family: "IBM Plex Mono", monospace;2765    }2766    .avail-label {2767      font-size: 9px;2768      letter-spacing: 0.16em;2769      text-transform: uppercase;2770      color: ${accentHex};2771      margin-bottom: 4px;2772    }2773    .avail-user {2774      font-size: 13px;2775      font-weight: 500;2776      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2777      margin-bottom: 12px;2778      overflow: hidden;2779      text-overflow: ellipsis;2780      white-space: nowrap;2781    }2782    .avail-cross {2783      font-size: 11px;2784      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2785      line-height: 1.45;2786      margin-bottom: 12px;2787      padding: 8px;2788      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};2789      border-radius: 6px;2790    }2791    .avail-btn {2792      display: block;2793      width: 100%;2794      padding: 8px 0;2795      border-radius: 7px;2796      border: none;2797      cursor: pointer;2798      font-size: 12px;2799      font-family: Inter, sans-serif;2800      font-weight: 500;2801      transition: opacity 100ms;2802      margin-bottom: 6px;2803      text-align: center;2804    }2805    .avail-btn:last-child { margin-bottom: 0; }2806    .avail-btn--accent { background: ${accentHex}; color: #fff; }2807    .avail-btn--accent:hover { opacity: 0.88; }2808    .avail-btn--ghost {2809      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2810      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2811    }2812    .avail-btn--ghost:hover { opacity: 0.75; }2813  `;2814  shadow.appendChild(style);28152816  const wrap = document.createElement("div");2817  wrap.className = "avail-wrap";2818  shadow.appendChild(wrap);28192820  const avail = document.createElement("div");2821  avail.className = "avail";2822  wrap.appendChild(avail);28232824  const closeBtn = document.createElement("button");2825  closeBtn.className = "avail-close";2826  closeBtn.type = "button";2827  closeBtn.setAttribute("aria-label", "Dismiss");2828  closeBtn.textContent = "✕";2829  avail.appendChild(closeBtn);28302831  const header = document.createElement("div");2832  header.className = "avail-header";2833  const icon = document.createElement("span");2834  icon.innerHTML = peachIconSvg();2835  const domainEl = document.createElement("span");2836  domainEl.className = "avail-domain";2837  domainEl.textContent = domain;2838  header.append(icon, domainEl);2839  avail.appendChild(header);28402841  const label = document.createElement("div");2842  label.className = "avail-label";2843  label.textContent = "PASSKEY";2844  avail.appendChild(label);28452846  const user = document.createElement("div");2847  user.className = "avail-user";2848  user.textContent = args.userName;2849  avail.appendChild(user);28502851  if (crossBrowser) {2852    const cross = document.createElement("div");2853    cross.className = "avail-cross";2854    cross.textContent =2855      args.fromBrowser === "chrome"2856        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."2857        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";2858    avail.appendChild(cross);2859  }28602861  const signInBtn = document.createElement("button");2862  signInBtn.className = "avail-btn avail-btn--accent";2863  signInBtn.type = "button";2864  signInBtn.textContent = "Sign in with passkey";2865  avail.appendChild(signInBtn);28662867  const passwordBtn = document.createElement("button");2868  passwordBtn.className = "avail-btn avail-btn--ghost";2869  passwordBtn.type = "button";2870  passwordBtn.textContent = "Use password instead";2871  avail.appendChild(passwordBtn);28722873  function dismiss() {2874    wrap.classList.add("is-exiting");2875    setTimeout(() => host.remove(), 130);2876  }28772878  signInBtn.addEventListener("click", () => {2879    // On Chrome: the user clicking the page's own Sign-in button is what2880    //   triggers webAuthenticationProxy → existing background flow handles it.2881    //   Our button just dismisses since the page itself drives auth.2882    // On Firefox: cross-browser passkeys can't be used, so we just dismiss2883    //   and surface the entry for manual reference (popup view).2884    dismiss();2885    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});2886  });2887  passwordBtn.addEventListener("click", dismiss);2888  closeBtn.addEventListener("click", dismiss);28892890  document.body.appendChild(host);2891}28922893/**2894 * State 7 — card silver platter. Single-card focused fill view rendered2895 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the2896 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes2897 * so card and login flows render identically. Multi-card list view is a2898 * follow-up; today this picks the first card.2899 */2900export function showCardSelector(2901  anchorEl: HTMLInputElement,2902  cards: CardSelectorEntry[],2903  options: CardSelectorOptions2904): () => void {2905  if (cards.length === 0) return () => {};2906  const card = cards[0]!;29072908  const host = document.createElement("div");2909  host.style.cssText = "position: absolute; z-index: 2147483647;";2910  host.style.setProperty("--peach-accent", accentHex);2911  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2912  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2913  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2914  const shadow = host.attachShadow({ mode: "closed" });29152916  const style = shadow.appendChild(document.createElement("style"));2917  style.textContent = SELECTOR_STYLES;29182919  const rect = anchorEl.getBoundingClientRect();2920  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2921  host.style.left = `${rect.left + window.scrollX}px`;2922  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;29232924  const container = shadow.appendChild(document.createElement("div"));2925  container.className = "peach-inline-popup";2926  container.setAttribute("data-theme", popupTheme);29272928  // Domain header — eyebrow communicates the card context, not the site2929  const domHdr = document.createElement("div");2930  domHdr.className = "domain-header";2931  const eyebrow = document.createElement("div");2932  eyebrow.className = "domain-eyebrow";2933  eyebrow.textContent = "Pay with Peach";2934  const domName = document.createElement("div");2935  domName.className = "domain-name";2936  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2937  domHdr.append(eyebrow, domName);2938  container.appendChild(domHdr);29392940  const platter = document.createElement("div");2941  platter.className = "card-platter";29422943  if (card.network && card.network !== "unknown") {2944    const net = document.createElement("div");2945    net.className = "cp-network";2946    net.textContent = card.network;2947    platter.appendChild(net);2948  }29492950  const nick = document.createElement("div");2951  nick.className = "cp-nickname";2952  nick.textContent = card.title;2953  platter.appendChild(nick);29542955  if (card.last4) {2956    const l4 = document.createElement("div");2957    l4.className = "cp-last4";2958    l4.textContent = `•••• ${card.last4}`;2959    platter.appendChild(l4);2960  }29612962  const meta = document.createElement("div");2963  meta.className = "cp-meta";2964  if (card.cardholderName) {2965    const name = document.createElement("span");2966    name.textContent = card.cardholderName;2967    meta.appendChild(name);2968  }2969  if (card.expMonth && card.expYear) {2970    if (card.cardholderName) {2971      const sep = document.createElement("span");2972      sep.className = "cp-meta-sep";2973      sep.textContent = "·";2974      meta.appendChild(sep);2975    }2976    const exp = document.createElement("span");2977    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;2978    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;2979    meta.appendChild(exp);2980  }2981  if (meta.childElementCount > 0) platter.appendChild(meta);29822983  const fillWrap = document.createElement("div");2984  fillWrap.className = "cp-fill-wrap";2985  const fillBtn = document.createElement("button");2986  fillBtn.className = "sp-fill-btn";2987  fillBtn.type = "button";2988  fillBtn.textContent = "Fill card details";2989  fillBtn.addEventListener("click", async () => {2990    if (fillBtn.disabled) return;2991    fillBtn.disabled = true;2992    fillBtn.classList.add("filled");2993    fillBtn.innerHTML = checkSvgStr();2994    const resp = await chrome.runtime.sendMessage({2995      type: "GET_ENTRY_FOR_FILL",2996      payload: { id: card.id },2997    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;2998    if (resp?.ok && resp.data) options.onFill(resp.data);2999    setTimeout(() => dismiss(), 400);3000  });3001  fillWrap.appendChild(fillBtn);3002  platter.appendChild(fillWrap);30033004  // Secondary actions — copy number, copy CVC, dismiss3005  const actions = document.createElement("div");3006  actions.className = "sp-actions";30073008  function flashBtn(b: HTMLButtonElement) {3009    b.classList.add("flashed");3010    setTimeout(() => b.classList.remove("flashed"), 700);3011  }30123013  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3014    const resp = await chrome.runtime.sendMessage({3015      type: "GET_ENTRY_FOR_FILL",3016      payload: { id: card.id },3017    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3018    return resp?.ok && resp.data ? resp.data : null;3019  }30203021  const copyNum = document.createElement("button");3022  copyNum.className = "sp-action-btn";3023  copyNum.type = "button";3024  copyNum.title = "Copy card number";3025  copyNum.textContent = "Copy number";3026  copyNum.addEventListener("click", async (e) => {3027    e.stopPropagation();3028    const full = await fetchFullCard();3029    if (!full?.cardNumber) return;3030    let alreadyWritten = false;3031    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}3032    await chrome.runtime.sendMessage({3033      type: "COPY",3034      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3035    }).catch(() => {});3036    flashBtn(copyNum);3037  });3038  actions.appendChild(copyNum);30393040  const copyCvc = document.createElement("button");3041  copyCvc.className = "sp-action-btn";3042  copyCvc.type = "button";3043  copyCvc.title = "Copy CVC";3044  copyCvc.textContent = "Copy CVC";3045  copyCvc.addEventListener("click", async (e) => {3046    e.stopPropagation();3047    const full = await fetchFullCard();3048    if (!full?.cvc) return;3049    let alreadyWritten = false;3050    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}3051    await chrome.runtime.sendMessage({3052      type: "COPY",3053      payload: { text: full.cvc, label: "CVC", alreadyWritten },3054    }).catch(() => {});3055    flashBtn(copyCvc);3056  });3057  actions.appendChild(copyCvc);30583059  const closeBtn = document.createElement("button");3060  closeBtn.className = "sp-action-btn";3061  closeBtn.type = "button";3062  closeBtn.title = "Dismiss";3063  closeBtn.textContent = "✕";3064  closeBtn.addEventListener("click", (e) => {3065    e.stopPropagation();3066    dismiss(true);3067  });3068  actions.appendChild(closeBtn);30693070  platter.appendChild(actions);3071  container.appendChild(platter);30723073  document.body.appendChild(host);3074  function updatePosition() {3075    const r = anchorEl.getBoundingClientRect();3076    host.style.top = `${r.bottom + window.scrollY + 5}px`;3077    host.style.left = `${r.left + window.scrollX}px`;3078  }3079  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);30803081  function onKeyDown(e: KeyboardEvent) {3082    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3083  }3084  document.addEventListener("keydown", onKeyDown);30853086  let exitScheduled = false;3087  function dismiss(userAction = false) {3088    if (exitScheduled) return;3089    exitScheduled = true;3090    stopObserving();3091    document.removeEventListener("click", outsideClick, { capture: true });3092    document.removeEventListener("keydown", onKeyDown);3093    if (userAction) options.onDismiss?.();3094    container.classList.add("is-exiting");3095    setTimeout(() => host.remove(), 130);3096  }30973098  function outsideClick(ev: MouseEvent) {3099    const path = ev.composedPath();3100    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3101  }3102  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);31033104  return dismiss;3105}