inject.ts

146.7 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { generatePassword } from "../shared/generate";14import { generateTOTP } from "../crypto/totp";15import { detectPasswordPolicy } from "./policy";1617let accentHex = "#E8956D";18let popupTheme: "dark" | "light" = "dark";19chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {20  const data = resp?.data;21  const name = data?.accentColor ?? "peach";22  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";23  popupTheme = data?.theme === "light" ? "light" : "dark";24});2526// 8-digit hex alpha helpers for the accent-derived shadow tokens.27// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing28// two hex digits as the alpha channel.29function withAlpha(hex: string, alpha: string): string {30  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS31  // always exposes 6-digit hex, so this is a guard against future changes32  // shipping shorthand colors that would silently break the var injection.33  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;34}3536export interface SelectorEntry {37  id: string;38  title: string;39  username?: string;40  email?: string;41  url?: string;42  hasTotp?: boolean;43  /** True when the entry also has a passkey credential attached. */44  hasPasskey?: boolean;45}4647interface SelectorOptions {48  domain?: string;49  searchableEntries?: SelectorEntry[];50  /** True when shown on a signup form — changes header label and entry-click behaviour */51  isSignup?: boolean;52  /**53   * Derived identity list (emails then usernames) for signup mode (State 10).54   * When present, renderIdentityHelper() is used instead of renderList().55   */56  savedIdentities?: SavedIdentity[];57  /**58   * Called after the user picks a saved identity (signup mode only) or59   * after successfully saving a new entry on a signup form.60   * Lets the caller fill the visible username + password fields.61   */62  onFillFields?: (username: string, password: string) => void;63  /**64   * When true, show an inline unlock form instead of the entries list.65   * Used when the vault is locked so the user can unlock without opening66   * the popup.67   */68  locked?: boolean;69  /**70   * Called after a successful inline unlock — the caller should re-query71   * entries and re-open the selector with real data.72   */73  onUnlocked?: () => void;74  /**75   * Called when the user explicitly dismisses the selector (Escape, Tab, or76   * click outside) — NOT when an entry is selected or on auto-close.77   * Used by the caller to suppress spurious reopens on the same field.78   */79  onDismiss?: () => void;80}8182function getDomainFromUrl(url: string): string {83  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }84}8586function keySvgStr(): string {87  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="rgba(240,232,216,0.35)" stroke-width="0.95" stroke-linecap="round"><rect x="2" y="5.5" width="8" height="6" rx="1.5"/><path d="M4 5.5V4.25A2 2 0 0 1 6 2.25A2 2 0 0 1 8 4.25V5.5"/></svg>`;88}8990function plusSvgStr(): string {91  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>`;92}9394function searchSvgStr(): string {95  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"><circle cx="5.25" cy="5.25" r="3.5"/><path d="M7.9 7.9l2.35 2.35"/></svg>`;96}9798function peachIconSvg(): string {99  // Peach body stays brand-peach regardless of `accentHex` — a sage or100  // sky accent must not turn the autofill icon green or blue. Accent101  // color still tints surrounding glow/hover halos below.102  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 240 240" fill="none" aria-hidden="true"><path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/><path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z" fill="#FFB082"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z" fill="#E5805C"/><ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/></svg>`;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="#5E7A42" 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}178179interface SmartGenerator {180  root: HTMLElement;181  getPassword: () => string;182  /** Copy the current password to the clipboard with the standard pulse UX. */183  copy: () => Promise<void>;184}185186interface SmartGeneratorOptions {187  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */188  policy: PasswordPolicy;189  /**190   * Seed value: used as the displayed password without regenerating, e.g. the191   * password the user already typed into the page. The generator still192   * regenerates the moment any control changes.193   */194  initialPassword?: string;195  /** Fires every time the password regenerates (initial + on changes). */196  onChange?: (pw: string) => void;197}198199/**200 * Build the inline-popup smart-password generator. Mirrors the main popup's201 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset202 * pills + a policy hint that names the constraints Peach detected on the203 * page. Writing this in pure DOM rather than reusing the Solid component204 * keeps the content-script bundle small.205 */206function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {207  const policy = opts.policy ?? {};208209  // Start at site max (strongest password the site accepts), fall back to 64210  let length = policy.maxLength ?? 64;211  if (policy.minLength) length = Math.max(length, policy.minLength);212  if (length < 8) length = 8;213  if (length > 128) length = 128;214215  let upper = true;216  let lower = true;217  let numbers = true;218  let symbols = !policy.forbidsSymbols;219  if (policy.requiresSymbols) symbols = true;220  const forbiddenChars = policy.forbiddenChars ?? "";221222  let password = "";223224  const root = document.createElement("div");225  root.className = "pwgen-block";226227  const displayRow = root.appendChild(document.createElement("div"));228  displayRow.className = "pwgen-display-row";229  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;230  output.type = "text";231  output.className = "pwgen-output";232  output.setAttribute("autocomplete", "off");233  output.setAttribute("spellcheck", "false");234  output.setAttribute("autocorrect", "off");235  output.setAttribute("autocapitalize", "off");236237  const regenBtn = displayRow.appendChild(document.createElement("button"));238  regenBtn.className = "pwgen-icon-btn";239  regenBtn.type = "button";240  regenBtn.setAttribute("aria-label", "Regenerate password");241  regenBtn.title = "Regenerate";242  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>`;243244  const copyBtn = displayRow.appendChild(document.createElement("button"));245  copyBtn.className = "pwgen-icon-btn";246  copyBtn.type = "button";247  copyBtn.setAttribute("aria-label", "Copy password");248  copyBtn.title = "Copy";249  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>`;250251  const controls = root.appendChild(document.createElement("div"));252  controls.className = "pwgen-controls-row";253  const slider = controls.appendChild(document.createElement("input"));254  slider.type = "range";255  slider.className = "pwgen-slider";256  slider.min = "8";257  slider.max = "128";258  slider.value = String(length);259  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));260  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));261  const lenNum = controls.appendChild(document.createElement("span"));262  lenNum.className = "pwgen-len-num pwgen-len-num--edit";263  lenNum.textContent = String(length);264  lenNum.addEventListener("click", () => {265    const li = document.createElement("input");266    li.type = "text"; li.inputMode = "numeric";267    li.className = "pwgen-len-input"; li.value = String(length);268    lenNum.replaceWith(li);269    requestAnimationFrame(() => li.select());270    function commitLenEdit() {271      const n = parseInt(li.value, 10);272      if (!isNaN(n)) {273        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));274        slider.value = String(length);275        regenerate();276      }277      lenNum.textContent = String(length);278      li.replaceWith(lenNum);279    }280    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });281    li.addEventListener("blur", commitLenEdit);282  });283284  const pills = root.appendChild(document.createElement("div"));285  pills.className = "pwgen-pills";286287  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {288    const b = document.createElement("button");289    b.type = "button";290    b.className = `pwgen-pill ${on ? "is-on" : ""}`;291    b.textContent = label;292    b.addEventListener("click", () => {293      const next = !b.classList.contains("is-on");294      b.classList.toggle("is-on", next);295      onToggle(next);296    });297    return b;298  }299  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));300  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));301  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));302  pills.appendChild(makePill("!@#", symbols, (next) => {303    // The site forbids symbols — UI lets the user override but still warn.304    symbols = next;305    regenerate();306  }));307308  // Policy hint — surfaces what Peach read off the site so the user knows the309  // generator is already tuned to it. Only shows when something interesting310  // was detected.311  const hintParts: string[] = [];312  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);313  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);314  if (policy.requiresSymbols) hintParts.push("requires symbols");315  if (policy.forbidsSymbols) hintParts.push("no symbols");316  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);317  if (hintParts.length > 0) {318    const hint = root.appendChild(document.createElement("div"));319    hint.className = "pwgen-policy-hint";320    const accent = document.createElement("span");321    accent.className = "pwgen-hint-accent";322    accent.textContent = "site rules · ";323    const text = document.createTextNode(hintParts.join(" · "));324    hint.appendChild(accent);325    hint.appendChild(text);326  }327328  function regenerate() {329    // Falls back gracefully when the user toggles every charset off — the330    // shared generator forces lowercase in that case rather than throwing.331    password = generatePassword({332      length,333      includeUppercase: upper,334      includeLowercase: lower,335      includeNumbers: numbers,336      includeSymbols: symbols,337      forbiddenChars,338    });339    output.value = password;340    opts.onChange?.(password);341  }342343  output.addEventListener("input", () => {344    password = output.value;345    length = password.length;346    slider.value = String(Math.max(8, Math.min(128, length)));347    lenNum.textContent = String(length);348    opts.onChange?.(password);349  });350351  slider.addEventListener("input", () => {352    length = parseInt(slider.value, 10);353    lenNum.textContent = String(length);354    regenerate();355  });356  regenBtn.addEventListener("click", regenerate);357358  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;359  async function copy(): Promise<void> {360    try {361      await navigator.clipboard.writeText(password);362      copyBtn.classList.add("is-copied");363      if (copyResetTimer) clearTimeout(copyResetTimer);364      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);365    } catch {366      // Clipboard API may be denied — silently no-op; user still has regen UI.367    }368  }369  copyBtn.addEventListener("click", () => { void copy(); });370371  if (opts.initialPassword) {372    password = opts.initialPassword;373    output.value = password;374    opts.onChange?.(password);375  } else {376    regenerate();377  }378379  return {380    root,381    getPassword: () => password,382    copy,383  };384}385386export function observeAnchorPosition(387  anchorEl: HTMLElement,388  onUpdate: () => void389): () => void {390  let rafId = 0;391  let burstUntil = 0;392393  const runUpdate = () => {394    rafId = 0;395    onUpdate();396    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);397  };398  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };399  const scheduleBurst = (ms = 220) => {400    burstUntil = Math.max(burstUntil, performance.now() + ms);401    scheduleUpdate();402  };403404  const resizeObserver = new ResizeObserver(() => scheduleBurst());405  resizeObserver.observe(anchorEl);406  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);407408  const mutationObserver = new MutationObserver(() => scheduleBurst());409  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });410  if (anchorEl.parentElement) {411    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });412  }413414  const onScroll = () => scheduleUpdate();415  window.addEventListener("scroll", onScroll, true);416  window.addEventListener("resize", onScroll);417  window.visualViewport?.addEventListener("resize", onScroll);418  window.visualViewport?.addEventListener("scroll", onScroll);419  anchorEl.addEventListener("focus", () => scheduleBurst());420  anchorEl.addEventListener("input", () => scheduleBurst());421422  scheduleBurst(260);423424  return () => {425    if (rafId) cancelAnimationFrame(rafId);426    resizeObserver.disconnect();427    mutationObserver.disconnect();428    window.removeEventListener("scroll", onScroll, true);429    window.removeEventListener("resize", onScroll);430    window.visualViewport?.removeEventListener("resize", onScroll);431    window.visualViewport?.removeEventListener("scroll", onScroll);432  };433}434435export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {436  const button = document.createElement("button");437  button.type = "button";438  button.setAttribute("aria-label", "Peach autofill");439  button.title = "Fill with Peach";440  button.innerHTML = peachIconSvg();441  // position: fixed is load-bearing — not absolute. Absolute positioning442  // inherits the nearest positioned ancestor's box, which on sites with443  // overflow:hidden or sticky parents clips or offsets the icon. Fixed444  // anchors to the viewport and escapes all parent layout.445  button.style.cssText = `446    position: fixed; z-index: 2147483646;447    width: 26px; height: 26px; cursor: pointer;448    pointer-events: auto; border: none; padding: 3px;449    display: inline-flex; align-items: center; justify-content: center;450    background: transparent; border-radius: 999px;451    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;452    opacity: 0;453  `;454  button.addEventListener("mouseenter", () => {455    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;456    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;457    button.style.transform = "scale(1.08)";458  });459  button.addEventListener("mouseleave", () => {460    button.style.background = "transparent";461    button.style.boxShadow = "none";462    button.style.transform = "none";463  });464  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });465  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });466467  document.body.appendChild(button);468469  function updatePosition() {470    const rect = field.getBoundingClientRect();471    if (rect.width === 0 || rect.height === 0) {472      button.style.opacity = "0"; button.style.pointerEvents = "none";473      return;474    }475    const sz = 26;476    const inset = Math.max(5, Math.min(10, rect.height * 0.22));477    const top = rect.top + rect.height / 2 - sz / 2;478    // Clamp left so the icon stays fully inside the field's right edge, never479    // spilling onto an adjacent sibling button.480    const minLeft = rect.left + 4;481    const left = Math.max(minLeft, rect.right - sz - inset);482    // Hide if the field is too narrow to fit the icon cleanly (< 40px)483    if (rect.width < 40) {484      button.style.opacity = "0"; button.style.pointerEvents = "none";485      return;486    }487    button.style.top = `${top}px`;488    button.style.left = `${left}px`;489    button.style.opacity = "1"; button.style.pointerEvents = "auto";490  }491  updatePosition();492  requestAnimationFrame(() => { button.style.opacity = "1"; });493  const stopObserving = observeAnchorPosition(field, updatePosition);494  return () => { stopObserving(); button.remove(); };495}496497// All theme-dependent values resolve through tokens scoped to498// .peach-inline-popup[data-theme="dark|light"]. Accent variables499// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)500// are identical in both themes — only surface tokens differ. See501// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the502// theme switch — only literal brand-peach in peachIconSvg may stay raw.503const SELECTOR_STYLES = `504  :host { all: initial; }505  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }506507  .peach-inline-popup[data-theme="dark"] {508    --peach-bg:           #1a1410;509    --peach-bg-card:      #221c16;510    --peach-text:         #f5f0ea;511    --peach-text-dim:     #8a7a6a;512    --peach-text-muted:   #4a3a2a;513    --peach-border:       rgba(255,255,255,0.07);514    --peach-input-bg:     rgba(255,255,255,0.05);515    --peach-input-border: rgba(255,255,255,0.08);516  }517  .peach-inline-popup[data-theme="light"] {518    --peach-bg:           #fdf8f4;519    --peach-bg-card:      #f5ede4;520    --peach-text:         #1c1310;521    --peach-text-dim:     #6b5a4a;522    --peach-text-muted:   #a89080;523    --peach-border:       rgba(0,0,0,0.08);524    --peach-input-bg:     rgba(0,0,0,0.04);525    --peach-input-border: rgba(0,0,0,0.10);526  }527528  .peach-inline-popup {529    background: var(--peach-bg);530    border: 1px solid var(--peach-border-accent, var(--peach-border));531    border-radius: 14px;532    overflow: hidden;533    box-shadow:534      0 8px 40px var(--peach-glow, transparent),535      0 2px 12px rgba(0,0,0,0.5);536    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;537    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;538    transition: height 220ms cubic-bezier(0.16,1,0.3,1);539  }540  /* Light theme: shadow against a light page is too strong otherwise — drop both541     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */542  .peach-inline-popup[data-theme="light"] {543    box-shadow:544      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),545      0 2px 12px rgba(0,0,0,0.12);546  }547  .peach-inline-popup.is-exiting {548    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;549    pointer-events: none;550  }551552  @keyframes peach-enter {553    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }554    65%  { opacity: 1; filter: blur(0); }555    100% { opacity: 1; transform: translateY(0) scale(1); }556  }557  @keyframes peach-exit {558    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }559    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }560  }561  @keyframes peach-slide-in {562    from { opacity: 0; transform: translateX(12px); }563    to   { opacity: 1; transform: translateX(0); }564  }565  @keyframes peach-slide-back {566    from { opacity: 0; transform: translateX(-12px); }567    to   { opacity: 1; transform: translateX(0); }568  }569  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }570  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }571572  /* Domain header */573  .domain-header {574    padding: 9px 13px 7px;575    border-bottom: 1px solid var(--peach-border);576    display: flex; align-items: center; justify-content: space-between;577    gap: 8px;578  }579  .domain-header-text {580    display: flex; flex-direction: column; gap: 2px;581    min-width: 0; flex: 1;582  }583  .domain-eyebrow {584    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;585    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;586  }587  .domain-name {588    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);589    font-family: "IBM Plex Mono", monospace;590    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;591  }592  .domain-header-actions {593    display: inline-flex; align-items: center; gap: 5px;594    flex-shrink: 0;595  }596  .domain-add-btn,597  .domain-search-btn {598    flex-shrink: 0;599    width: 22px; height: 22px;600    display: inline-flex; align-items: center; justify-content: center;601    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);602    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);603    border-radius: 6px;604    color: var(--peach-accent);605    cursor: pointer; padding: 0;606    transition: background 120ms, border-color 120ms, transform 80ms;607    font-family: "IBM Plex Mono", monospace;608    font-size: 14px; line-height: 1;609  }610  .domain-add-btn:hover,611  .domain-search-btn:hover {612    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);613    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);614    transform: scale(1.06);615  }616  .domain-add-btn:active,617  .domain-search-btn:active { transform: scale(0.96); }618619  /* Search */620  .search-wrap {621    padding: 9px 12px 7px;622    border-bottom: 1px solid var(--peach-border);623  }624  .search {625    width: 100%; background: var(--peach-input-bg);626    border: 1px solid var(--peach-input-border);627    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;628    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;629    transition: border-color 120ms, box-shadow 120ms;630  }631  .search:focus {632    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);633    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);634  }635  .search::placeholder { color: var(--peach-text-muted); }636637  /* Results */638  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }639  .results::-webkit-scrollbar { display: none; }640641  /* Entry rows */642  .entry {643    display: flex; align-items: center; padding: 8px 12px;644    cursor: pointer; border-bottom: 1px solid var(--peach-border);645    transition: background 70ms; position: relative; outline: none;646  }647  .entry:last-child { border-bottom: none; }648  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }649  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }650  .entry.focused::before {651    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;652    width: 2px; border-radius: 2px;653    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);654  }655656  .entry-icon {657    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;658    background: var(--peach-input-bg); border: 1px solid var(--peach-border);659    display: flex; align-items: center; justify-content: center;660    overflow: hidden; margin-right: 10px;661  }662  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }663  .entry-icon.is-new {664    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);665    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);666    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);667  }668669  .entry-info { flex: 1; min-width: 0; }670  .entry-title {671    font-size: 12.5px; color: var(--peach-text);672    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;673    line-height: 1.3;674  }675  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }676  .entry-sub {677    font-size: 10px; color: var(--peach-text-dim);678    font-family: "IBM Plex Mono", monospace;679    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;680    margin-top: 1px;681  }682683  .totp-badge {684    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;685    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);686    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);687    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;688  }689  .passkey-badge {690    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;691    border-radius: 4px;692    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);693    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);694    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);695    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;696  }697698  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }699700  .empty-hint {701    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);702    font-family: "IBM Plex Mono", monospace;703  }704705  /* Create form */706  .create-form-wrap {707    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;708  }709  .create-head {710    display: flex; align-items: center; gap: 8px;711    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);712  }713  .back-btn {714    background: transparent; border: none; cursor: pointer;715    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;716    display: flex; align-items: center; line-height: 0;717    transition: color 100ms, background 100ms;718  }719  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }720  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }721  /* minmax(0, 1fr) caps the grid track at the popup width — without it,722     long monospace content (e.g. a 60-char generated password) would723     auto-size the track wider than the popup and overflow the right edge. */724  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }725  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }726  .f-label {727    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;728    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;729  }730  .f-input {731    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);732    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;733    font-size: 11px; font-family: "IBM Plex Mono", monospace;734    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;735  }736  .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); }737  .f-input::placeholder { color: var(--peach-text-muted); }738  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }739  .f-row { display: flex; gap: 6px; }740  .f-row .f-input { flex: 1; min-width: 0; }741  .gen-btn {742    padding: 0 10px; border-radius: 7px; border: none;743    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);744    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);745    font-size: 10px; font-family: "IBM Plex Mono", monospace;746    cursor: pointer; white-space: nowrap; flex-shrink: 0;747    display: flex; align-items: center; gap: 4px;748    transition: background 100ms;749  }750  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }751  .gen-toggle-link {752    background: none; border: none; padding: 2px 0;753    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);754    font-size: 10px; font-family: "IBM Plex Mono", monospace;755    cursor: pointer; text-align: left; transition: color 100ms;756  }757  .gen-toggle-link:hover { color: var(--peach-accent); }758  .save-btn {759    width: 100%; padding: 8px; border-radius: 8px; border: none;760    background: var(--peach-accent); color: #fff; font-size: 12px;761    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;762    transition: background 120ms, box-shadow 120ms, transform 80ms;763    letter-spacing: 0.01em;764  }765  .save-btn:hover {766    background: color-mix(in srgb, var(--peach-accent) 82%, #000);767    box-shadow: 0 4px 20px var(--peach-glow, transparent);768  }769  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }770  .url-hint {771    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);772    font-family: "IBM Plex Mono", monospace; font-style: italic;773  }774775  /* Success */776  .success-wrap {777    display: flex; flex-direction: column; align-items: center;778    padding: 24px 16px 20px; gap: 8px;779    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;780  }781  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }782  .success-ring {783    width: 40px; height: 40px; border-radius: 50%;784    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);785    display: flex; align-items: center; justify-content: center;786  }787  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }788  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }789790  /* Silver platter (State 1 — single match) */791  .silver-platter {792    padding: 14px 14px 12px;793    display: flex; flex-direction: column; gap: 6px;794  }795  .sp-title {796    font-size: 14px; font-weight: 500; color: var(--peach-text);797    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;798    line-height: 1.25;799  }800  .sp-identity-row {801    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;802  }803  .sp-identity-label {804    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;805    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;806  }807  .sp-username {808    font-size: 12px; color: var(--peach-text-dim);809    font-family: "IBM Plex Mono", monospace;810    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;811    margin-bottom: 0;812  }813  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }814  .sp-fill-btn {815    width: 100%; padding: 11px; border-radius: 9px; border: none;816    background: var(--peach-accent); color: #fff;817    font-size: 13px; font-weight: 500; cursor: pointer;818    font-family: Inter, sans-serif; letter-spacing: 0.01em;819    display: flex; align-items: center; justify-content: center; min-height: 38px;820    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;821  }822  .sp-fill-btn:hover {823    filter: brightness(1.1);824    box-shadow: 0 4px 20px var(--peach-glow, transparent);825    transform: translateY(-1px);826  }827  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }828  .sp-fill-btn.filled {829    background: #16a34a; transform: none; filter: none;830    box-shadow: 0 4px 16px rgba(22,163,74,0.35);831    cursor: default;832  }833  .sp-fill-btn:disabled { cursor: default; }834  .sp-actions-group {835    margin-top: 6px;836    display: flex; flex-direction: column; gap: 4px;837  }838  .sp-actions-label {839    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;840    color: var(--peach-text-muted);841    font-family: "IBM Plex Mono", monospace;842    text-align: center;843  }844  .sp-actions {845    display: flex; gap: 4px; justify-content: space-between; align-items: center;846  }847  .sp-action-btn {848    flex: 1; height: 28px; border: none; border-radius: 6px;849    background: transparent; color: var(--peach-text-dim);850    font-size: 12px; cursor: pointer;851    transition: background 120ms ease, color 120ms ease;852    font-family: Inter, sans-serif; letter-spacing: 0.04em;853    display: inline-flex; align-items: center; justify-content: center; gap: 4px;854    white-space: nowrap; overflow: hidden;855  }856  .sp-action-btn:hover:not(:disabled) {857    background: color-mix(in srgb, var(--peach-text) 5%, transparent);858    color: var(--peach-text);859  }860  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }861  .sp-action-btn.flashed {862    color: var(--peach-accent);863    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);864  }865866  /* TOTP tray — shown below the silver-platter secondary actions */867  .sp-tray {868    margin-top: 8px;869    padding: 10px 12px;870    border-radius: 9px;871    background: var(--peach-input-bg);872    border: 1px solid var(--peach-input-border);873    display: flex; align-items: center; gap: 12px;874    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;875  }876  .sp-tray-label {877    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;878    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;879    flex-shrink: 0;880  }881  .sp-totp-code {882    font-size: 18px; font-weight: 500;883    color: var(--peach-text);884    font-family: "IBM Plex Mono", monospace;885    letter-spacing: 0.12em;886    flex: 1;887    text-align: center;888  }889  .sp-totp-ring {890    width: 22px; height: 22px; flex-shrink: 0;891  }892  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }893  .sp-totp-ring .ring-fill {894    stroke: var(--peach-accent);895    transition: stroke-dashoffset 1s linear;896    transform: rotate(-90deg);897    transform-origin: center;898  }899  .sp-totp-copy {900    background: transparent; border: none; cursor: pointer;901    padding: 4px 8px; border-radius: 5px;902    color: var(--peach-text-dim); font-size: 11px;903    font-family: Inter, sans-serif;904    transition: background 120ms, color 120ms;905  }906  .sp-totp-copy:hover {907    background: color-mix(in srgb, var(--peach-text) 5%, transparent);908    color: var(--peach-text);909  }910911  /* Card silver platter (State 7) — reuses .sp-* primary action classes */912  .card-platter {913    padding: 12px 14px 10px;914    display: flex; flex-direction: column; gap: 4px;915  }916  .cp-network {917    font-size: 10px; font-weight: 600;918    color: var(--peach-accent);919    letter-spacing: 0.08em; text-transform: uppercase;920    font-family: Inter, sans-serif;921  }922  .cp-nickname {923    font-size: 14px; font-weight: 500; color: var(--peach-text);924    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;925    line-height: 1.2;926  }927  .cp-last4 {928    font-size: 12px; color: var(--peach-text-dim);929    font-family: "IBM Plex Mono", monospace;930    letter-spacing: 0.04em;931    margin-top: 2px;932  }933  .cp-meta {934    font-size: 11px; color: var(--peach-text-dim);935    font-family: "IBM Plex Mono", monospace;936    margin-top: 2px;937    display: flex; gap: 10px; align-items: center;938  }939  .cp-meta-sep { opacity: 0.5; }940  .cp-fill-wrap { margin-top: 10px; }941942  /* Locked state */943  .locked-wrap {944    display: flex; flex-direction: column; align-items: stretch;945    padding: 14px 13px 13px; gap: 9px;946  }947  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }948  .locked-icon {949    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;950    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);951    display: flex; align-items: center; justify-content: center;952  }953  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }954  .locked-input {955    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);956    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;957    font-size: 11px; font-family: "IBM Plex Mono", monospace;958    outline: none; transition: border-color 120ms, box-shadow 120ms;959  }960  .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); }961  .locked-input::placeholder { color: var(--peach-text-muted); }962  .locked-btn {963    width: 100%; padding: 8px; border-radius: 8px; border: none;964    background: var(--peach-accent); color: #fff; font-size: 12px;965    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;966    transition: background 120ms;967    letter-spacing: 0.01em;968    box-shadow: 0 2px 16px var(--peach-glow, transparent);969    animation: peach-pulse-glow 2.4s ease-in-out infinite;970  }971  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }972  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }973  .locked-error {974    font-size: 10px; color: rgba(220,80,60,0.85);975    font-family: "IBM Plex Mono", monospace;976  }977978  @keyframes peach-pulse-glow {979    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }980    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),981                            0 0 48px var(--peach-glow, transparent); }982  }983984  /* ── State 10: identity helper ─────────────────────────────── */985  .identity-list {986    max-height: 192px; overflow-y: auto; padding: 4px 0;987    scrollbar-width: none;988  }989  .identity-list::-webkit-scrollbar { display: none; }990  .peach-identity-row {991    display: flex; align-items: center; gap: 10px;992    padding: 9px 12px; cursor: pointer; border-radius: 8px;993    transition: background 100ms ease;994  }995  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }996  .peach-identity-value {997    font-family: "IBM Plex Mono", monospace; font-size: 13px;998    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;999  }1000  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1001  .identity-alt-row {1002    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1003    border-radius: 8px; transition: background 100ms ease;1004    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1005  }1006  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1007  .identity-escape-row {1008    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1009    border-radius: 8px; transition: background 100ms ease; outline: none;1010    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1011    margin-top: 2px;1012  }1013  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1014  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1015  .identity-alt-input-wrap.open { display: flex; }1016  .identity-alt-input {1017    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1018    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1019    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1020    outline: none; transition: border-color 120ms;1021  }1022  .identity-alt-input:focus {1023    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1024    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1025  }1026  .identity-alt-confirm {1027    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1028    background: var(--peach-accent); color: #fff; font-size: 12px;1029    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1030  }1031  /* ── Generator view (after identity picked) ────────────────── */1032  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1033  .gen-confirmed {1034    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1035    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1036    border-radius: 8px;1037  }1038  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1039  .gen-confirmed-val {1040    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1041    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1042  }1043  .gen-label {1044    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1045    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1046  }1047  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1048  .gen-pw-val {1049    flex: 1; padding: 8px 10px; border-radius: 7px;1050    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1051    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1052    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1053  }1054  .gen-regen-btn {1055    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1056    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1057    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1058    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1059  }1060  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1061  .gen-fill-btn {1062    padding: 10px; border-radius: 8px; border: none;1063    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1064    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1065    transition: filter 120ms ease, transform 80ms ease;1066  }1067  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1068  .gen-fill-btn:active { transform: translateY(0); }10691070  /* ── Smart password generator (parity with main UI compact mode) ─── */1071  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1072  .pwgen-display-row {1073    display: flex; align-items: center; gap: 6px;1074    padding: 8px 10px; border-radius: 7px;1075    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1076  }1077  .pwgen-output {1078    flex: 1; min-width: 0; width: 0;1079    font-family: "IBM Plex Mono", monospace; font-size: 12px;1080    color: var(--peach-text);1081    background: transparent; border: none; outline: none; padding: 0;1082  }1083  .pwgen-icon-btn {1084    flex-shrink: 0;1085    width: 26px; height: 26px;1086    display: inline-flex; align-items: center; justify-content: center;1087    background: transparent; border: 1px solid var(--peach-input-border);1088    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1089    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1090  }1091  .pwgen-icon-btn:hover {1092    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1093    color: var(--peach-accent);1094    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1095  }1096  .pwgen-icon-btn.is-copied {1097    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1098    color: var(--peach-accent);1099    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1100  }1101  .pwgen-controls-row {1102    display: flex; align-items: center; gap: 8px;1103    flex-wrap: wrap;1104  }1105  .pwgen-slider {1106    flex: 1; min-width: 110px;1107    accent-color: var(--peach-accent);1108    cursor: pointer; height: 2px; background: transparent;1109  }1110  .pwgen-len-num {1111    font-family: "IBM Plex Mono", monospace; font-size: 11px;1112    color: var(--peach-accent); min-width: 22px; text-align: right;1113  }1114  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1115  .pwgen-len-input {1116    font-family: "IBM Plex Mono", monospace; font-size: 11px;1117    color: var(--peach-accent); width: 28px; text-align: right;1118    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1119    outline: none; padding: 0; min-width: 22px;1120  }1121  @keyframes identity-suggest-in {1122    from { opacity: 0; transform: translateY(-4px); }1123    to   { opacity: 1; transform: none; }1124  }1125  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1126    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1127  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1128  .identity-collapse-btn {1129    margin-left: auto; background: transparent; border: none; cursor: pointer;1130    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1131    line-height: 0; border-radius: 3px;1132    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1133  }1134  .identity-collapse-btn:hover { color: var(--peach-text); }1135  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1136  .identity-rows { display: grid; grid-template-rows: 1fr;1137    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1138  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1139  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1140    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1141    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1142    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1143  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1144  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1145  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1146  .identity-filter-pill {1147    padding: 2px 7px; border-radius: 999px;1148    border: 1px solid var(--peach-input-border);1149    background: transparent; color: var(--peach-text-muted);1150    font-family: "IBM Plex Mono", monospace; font-size: 9px;1151    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1152  }1153  .identity-filter-pill.is-on {1154    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1155    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1156    color: var(--peach-accent);1157  }1158  .identity-suggest-row {1159    display: flex; align-items: center; gap: 5px;1160    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1161    background: transparent; cursor: pointer; text-align: left;1162    transition: background 80ms;1163  }1164  .identity-suggest-row:hover,1165  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1166  .identity-suggest-val {1167    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1168    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1169  }1170  .identity-suggest-type {1171    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1172    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1173  }1174  .identity-suggest-type--email {1175    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1176    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1177  }1178  .identity-suggest-type--username {1179    color: var(--peach-text-muted);1180    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1181  }1182  .identity-suggest-meta {1183    font-family: "IBM Plex Mono", monospace; font-size: 9px;1184    color: var(--peach-text-muted); flex-shrink: 0;1185  }1186  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1187  .pwgen-pill {1188    padding: 3px 8px; border-radius: 999px;1189    border: 1px solid var(--peach-input-border);1190    background: transparent; color: var(--peach-text-muted);1191    font-family: "IBM Plex Mono", monospace; font-size: 9px;1192    letter-spacing: 0.06em; cursor: pointer;1193    transition: all 130ms ease;1194  }1195  .pwgen-pill.is-on {1196    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1197    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1198    color: var(--peach-accent);1199  }1200  .pwgen-pill:not(.is-on):hover {1201    color: var(--peach-text-dim);1202    border-color: var(--peach-text-muted);1203  }1204  .pwgen-policy-hint {1205    font-size: 10px; color: var(--peach-text-muted);1206    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1207    line-height: 1.3;1208  }1209  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }12101211  /* ── Save offer (after password filled) ───────────────────── */1212  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1213  .save-offer-title {1214    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1215  }1216  .save-offer-row {1217    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1218    border-radius: 7px; background: var(--peach-input-bg);1219    border: 1px solid var(--peach-input-border);1220  }1221  .save-offer-lbl {1222    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1223    font-family: "IBM Plex Mono", monospace;1224  }1225  .save-offer-val {1226    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1227    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1228  }1229  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1230  .save-offer-save {1231    flex: 1; padding: 9px; border-radius: 8px; border: none;1232    background: var(--peach-accent); color: #fff; font-size: 13px;1233    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1234  }1235  .save-offer-save:hover { filter: brightness(1.08); }1236  .save-offer-skip {1237    flex: 1; padding: 9px; border-radius: 8px; border: none;1238    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1239    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1240    font-family: Inter, sans-serif; transition: background 100ms ease;1241  }1242  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1243`;12441245export function showAutofillSelector(1246  anchorEl: HTMLInputElement,1247  entries: SelectorEntry[],1248  onSelect: (id: string) => void,1249  options: SelectorOptions = {}1250): () => void {1251  const host = document.createElement("div");1252  host.style.cssText = "position: absolute; z-index: 2147483647;";1253  host.style.setProperty("--peach-accent", accentHex);1254  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1255  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1256  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1257  const shadow = host.attachShadow({ mode: "closed" });12581259  const style = shadow.appendChild(document.createElement("style"));1260  style.textContent = SELECTOR_STYLES;12611262  const rect = anchorEl.getBoundingClientRect();1263  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1264  host.style.left = `${rect.left + window.scrollX}px`;1265  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1266  // wide single-input fields (e.g. centered email input on signup pages).1267  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1268  // expand the host after the initial measurement.1269  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1270  host.style.width = `${popupWidth}px`;12711272  const container = shadow.appendChild(document.createElement("div"));1273  container.className = "peach-inline-popup";1274  container.setAttribute("data-theme", popupTheme);12751276  const searchableEntries = options.searchableEntries ?? [];1277  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12781279  let query = "";1280  let focusedIndex = -1;1281  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1282  let searchInput: HTMLInputElement | null = null;1283  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1284  // setInterval. Add to this list — don't fan out the dismiss function.1285  const cleanupHooks: Array<() => void> = [];12861287  // Smooth height transitions whenever content changes height.1288  // ResizeObserver fires on natural height changes; we freeze the old height,1289  // then animate to the new one so the surface never jumps.1290  {1291    let prevH = 0;1292    let blocked = false;1293    const heightRo = new ResizeObserver(([entry]) => {1294      if (blocked) return;1295      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1296      if (prevH > 0 && Math.abs(h - prevH) > 1) {1297        blocked = true;1298        container.style.height = `${prevH}px`;1299        requestAnimationFrame(() => requestAnimationFrame(() => {1300          container.style.height = `${h}px`;1301          prevH = h;1302          const onEnd = (e: TransitionEvent) => {1303            if (e.propertyName !== "height") return;1304            container.style.height = "";1305            blocked = false;1306            container.removeEventListener("transitionend", onEnd);1307          };1308          container.addEventListener("transitionend", onEnd);1309        }));1310      } else {1311        prevH = h;1312      }1313    });1314    heightRo.observe(container);1315    cleanupHooks.push(() => heightRo.disconnect());1316  }13171318  // Pre-capture the anchor field value for username prefill1319  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1320  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1321  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13221323  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1324    const seen = new Set<string>();1325    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1326  }13271328  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1329    const q = value.trim().toLowerCase();1330    const deduped = uniqueEntries(source);1331    if (!q) return deduped.slice(0, 8);1332    return deduped.filter(e =>1333      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1334    ).slice(0, 12);1335  }13361337  function activeEntries(): SelectorEntry[] {1338    // When user is typing a search, filter across all known entries (domain matches + vault)1339    if (query.trim()) {1340      const merged = uniqueEntries([...entries, ...searchableEntries]);1341      return filterEntries(merged, query);1342    }1343    // Default: show domain matches; fall back to vault search when no matches1344    if (entries.length > 0) return entries;1345    return filterEntries(searchableEntries, "").slice(0, 8);1346  }13471348  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1349    const icon = document.createElement("div");1350    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1351    if (isNew) {1352      icon.innerHTML = plusSvgStr();1353    } else {1354      // Use the generic key glyph for all entries in the page-injected selector.1355      // Avoids disclosing vault domains to any third party and avoids needing1356      // to expose the browser favicon API to page context via web_accessible_resources.1357      void url;1358      icon.innerHTML = keySvgStr();1359    }1360    return icon;1361  }13621363  function renderIdentityHelper() {1364    container.innerHTML = "";1365    const identities = options.savedIdentities ?? [];13661367    // Header: "NEW ACCOUNT" + domain name1368    const hdr = container.appendChild(document.createElement("div"));1369    hdr.className = "domain-header";1370    const eyebrow = hdr.appendChild(document.createElement("div"));1371    eyebrow.className = "domain-eyebrow";1372    eyebrow.textContent = "NEW ACCOUNT";1373    const domName = hdr.appendChild(document.createElement("div"));1374    domName.className = "domain-name";1375    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13761377    // Identity rows1378    const list = container.appendChild(document.createElement("div"));1379    list.className = "identity-list";1380    for (const id of identities) {1381      const row = list.appendChild(document.createElement("div"));1382      row.className = "peach-identity-row";1383      row.setAttribute("tabindex", "-1");1384      const val = row.appendChild(document.createElement("div"));1385      val.className = "peach-identity-value";1386      val.textContent = id.value;1387      const meta = row.appendChild(document.createElement("div"));1388      meta.className = "peach-identity-meta";1389      meta.textContent = `used ${id.useCount}×`;1390      row.addEventListener("click", () => {1391        options.onFillFields?.(id.value, "");1392        renderGenerator(id.value);1393      });1394    }13951396    // Divider before "Use a different email…"1397    if (identities.length > 0) {1398      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1399    }14001401    // "Use a different email…" expandable row1402    const altRow = container.appendChild(document.createElement("div"));1403    altRow.className = "identity-alt-row";1404    altRow.textContent = "+ Use a different email…";14051406    const altInputWrap = container.appendChild(document.createElement("div"));1407    altInputWrap.className = "identity-alt-input-wrap";1408    const altInput = altInputWrap.appendChild(document.createElement("input"));1409    altInput.className = "identity-alt-input";1410    altInput.type = "email";1411    altInput.placeholder = "[email protected]";1412    altInput.setAttribute("autocomplete", "off");1413    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1414    altConfirm.className = "identity-alt-confirm";1415    altConfirm.type = "button";1416    altConfirm.textContent = "✓";14171418    function fillCustomEmail() {1419      const v = altInput.value.trim();1420      if (!v) return;1421      options.onFillFields?.(v, "");1422      renderGenerator(v);1423    }14241425    altRow.addEventListener("click", () => {1426      altRow.style.display = "none";1427      altInputWrap.classList.add("open");1428      altInput.focus();1429    });1430    altConfirm.addEventListener("click", fillCustomEmail);1431    altInput.addEventListener("keydown", (e) => {1432      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1433    });14341435    // Escape hatch: user already has a vault entry for this site but it1436    // wasn't detected (different domain, old entry, etc.). Tapping this1437    // switches to the full searchable list so they can find and fill it;1438    // selecting an entry there will trigger the remember-site toast if1439    // the domain isn't already associated.1440    if ((options.searchableEntries?.length ?? 0) > 0) {1441      const escapeRow = container.appendChild(document.createElement("div"));1442      escapeRow.className = "identity-escape-row";1443      escapeRow.textContent = "I already have an account →";1444      escapeRow.setAttribute("tabindex", "0");1445      escapeRow.addEventListener("click", () => renderList());1446      escapeRow.addEventListener("keydown", (e) => {1447        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1448      });1449    }1450  }14511452  function renderGenerator(filledEmail: string) {1453    container.innerHTML = "";1454    const sitePolicy = detectPasswordPolicy();14551456    const wrap = container.appendChild(document.createElement("div"));1457    wrap.className = "gen-view";14581459    // Header: domain + NEW ACCOUNT1460    const hdrRow = wrap.appendChild(document.createElement("div"));1461    hdrRow.className = "domain-header";1462    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1463    eyebrow2.className = "domain-eyebrow";1464    eyebrow2.textContent = "NEW ACCOUNT";1465    const domName2 = hdrRow.appendChild(document.createElement("div"));1466    domName2.className = "domain-name";1467    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14681469    // Confirmed email row1470    const conf = wrap.appendChild(document.createElement("div"));1471    conf.className = "gen-confirmed";1472    const confCheck = conf.appendChild(document.createElement("span"));1473    confCheck.className = "gen-confirmed-check";1474    confCheck.textContent = "✓";1475    const confVal = conf.appendChild(document.createElement("div"));1476    confVal.className = "gen-confirmed-val";1477    confVal.textContent = filledEmail;14781479    const lbl = wrap.appendChild(document.createElement("div"));1480    lbl.className = "gen-label";1481    lbl.textContent = "Generate a password";14821483    let currentPw = "";1484    const smartGen = createSmartGenerator({1485      policy: sitePolicy,1486      onChange: (pw) => { currentPw = pw; },1487    });1488    wrap.appendChild(smartGen.root);14891490    const fillBtn = wrap.appendChild(document.createElement("button"));1491    fillBtn.className = "gen-fill-btn";1492    fillBtn.type = "button";1493    fillBtn.textContent = "Copy & fill";1494    fillBtn.addEventListener("click", () => {1495      if (!currentPw) return;1496      options.onFillFields?.("", currentPw);1497      renderSaveOffer(filledEmail, currentPw);1498    });1499  }15001501  function renderSaveOffer(filledEmail: string, filledPassword: string) {1502    container.innerHTML = "";1503    const domain = options.domain ?? location.hostname.replace(/^www\./, "");15041505    const wrap = container.appendChild(document.createElement("div"));1506    wrap.className = "save-offer";15071508    const title = wrap.appendChild(document.createElement("div"));1509    title.className = "save-offer-title";1510    title.textContent = "Save this login to Peach?";15111512    function detailRow(label: string, value: string) {1513      const row = wrap.appendChild(document.createElement("div"));1514      row.className = "save-offer-row";1515      const lbl = row.appendChild(document.createElement("div"));1516      lbl.className = "save-offer-lbl";1517      lbl.textContent = label;1518      const val = row.appendChild(document.createElement("div"));1519      val.className = "save-offer-val";1520      val.textContent = value;1521    }15221523    detailRow("site", domain);1524    detailRow("email", filledEmail);1525    detailRow("password", "••••••••••••••••");15261527    const btns = wrap.appendChild(document.createElement("div"));1528    btns.className = "save-offer-btns";15291530    const saveBtn = btns.appendChild(document.createElement("button"));1531    saveBtn.className = "save-offer-save";1532    saveBtn.type = "button";1533    saveBtn.textContent = "Save";1534    saveBtn.addEventListener("click", async () => {1535      saveBtn.disabled = true;1536      saveBtn.textContent = "Saving…";1537      try {1538        const res = await chrome.runtime.sendMessage({1539          type: "ADD_ENTRY",1540          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1541        });1542        if ((res as { ok?: boolean }).ok) {1543          showSuccess(sTitle);1544        } else {1545          saveBtn.disabled = false;1546          saveBtn.textContent = "Save";1547        }1548      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1549    });15501551    const skipBtn = btns.appendChild(document.createElement("button"));1552    skipBtn.className = "save-offer-skip";1553    skipBtn.type = "button";1554    skipBtn.textContent = "Not now";1555    skipBtn.addEventListener("click", () => { dismiss(true); });1556  }15571558  function renderList() {1559    container.innerHTML = "";1560    focusedIndex = -1;1561    searchInput = null;1562    currentMode = "list";15631564    const current = activeEntries();15651566    // Domain header (always show) — eyebrow + domain on the left,1567    // a "+" shortcut to the create form on the right so the user is never1568    // trapped in the search list when they want to make a new entry.1569    const domHdr = document.createElement("div");1570    domHdr.className = "domain-header";1571    const headText = document.createElement("div");1572    headText.className = "domain-header-text";1573    const eyebrow = document.createElement("div");1574    eyebrow.className = "domain-eyebrow";1575    eyebrow.textContent = options.isSignup1576      ? "Sign up as"1577      : entries.length > 0 ? "Saved for this site" : "No saved login";1578    const domName = document.createElement("div");1579    domName.className = "domain-name";1580    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1581    headText.append(eyebrow, domName);1582    domHdr.appendChild(headText);15831584    if (!options.isSignup) {1585      const addBtn = document.createElement("button");1586      addBtn.className = "domain-add-btn";1587      addBtn.type = "button";1588      addBtn.setAttribute("aria-label", "Create new entry");1589      addBtn.title = "Create new entry";1590      addBtn.textContent = "+";1591      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1592      domHdr.appendChild(addBtn);1593    }15941595    container.appendChild(domHdr);15961597    // Search — always show so user can find entries beyond the domain matches1598    const sw = document.createElement("div"); sw.className = "search-wrap";1599    searchInput = document.createElement("input");1600    searchInput.className = "search";1601    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1602    searchInput.value = query;1603    searchInput.addEventListener("input", () => {1604      query = searchInput?.value ?? "";1605      renderList();1606      searchInput?.focus();1607      searchInput?.setSelectionRange(query.length, query.length);1608    });1609    sw.appendChild(searchInput);1610    container.appendChild(sw);16111612    // Results1613    const results = document.createElement("div");1614    results.className = "results";1615    container.appendChild(results);16161617    if (current.length === 0 && entries.length > 0) {1618      // Show a hint but don't render empty entries1619    }16201621    for (let i = 0; i < current.length; i++) {1622      const e = current[i]!;1623      const entryEl = document.createElement("div");1624      entryEl.className = "entry";1625      entryEl.dataset.id = e.id;1626      entryEl.dataset.index = String(i);1627      entryEl.setAttribute("tabindex", "-1");16281629      entryEl.appendChild(makeEntryIcon(e.url));16301631      const info = document.createElement("div"); info.className = "entry-info";1632      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1633      const subEl = document.createElement("div"); subEl.className = "entry-sub";1634      const domain = e.url ? getDomainFromUrl(e.url) : "";1635      subEl.textContent = domain || e.username || "";1636      info.append(titleEl, subEl);1637      entryEl.appendChild(info);16381639      if (e.hasTotp) {1640        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1641        entryEl.appendChild(badge);1642      }1643      if (e.hasPasskey) {1644        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1645        entryEl.appendChild(badge);1646      }16471648      entryEl.addEventListener("click", () => {1649        if (options.isSignup && options.onFillFields) {1650          // Signup mode: clicking a saved identity fills the username field1651          options.onFillFields(e.username ?? "", "");1652          dismiss();1653        } else {1654          onSelect(e.id);1655          dismiss();1656        }1657      });1658      results.appendChild(entryEl);1659    }16601661    // Divider before "New entry"1662    if (current.length > 0) {1663      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1664    }16651666    // "New entry" row — always present1667    const newEl = document.createElement("div");1668    newEl.className = "entry";1669    newEl.setAttribute("tabindex", "-1");1670    newEl.appendChild(makeEntryIcon(undefined, true));16711672    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1673    const newTitle = document.createElement("div");1674    newTitle.className = "entry-title is-new";1675    newTitle.textContent = `New entry for ${sTitle}`;1676    const newSub = document.createElement("div");1677    newSub.className = "entry-sub";1678    newSub.textContent = sOrigin;1679    newInfo.append(newTitle, newSub);1680    newEl.appendChild(newInfo);1681    newEl.addEventListener("click", showCreateForm);1682    results.appendChild(newEl);16831684    // Focus search if present1685    if (searchInput) {1686      requestAnimationFrame(() => {1687        searchInput?.focus();1688        // Seed query (from type-to-search or domain-search-btn) lands at the1689        // end so the next keystroke extends it, not overwrites.1690        searchInput?.setSelectionRange(query.length, query.length);1691      });1692    }1693  }16941695  function setFocused(idx: number) {1696    const all = container.querySelectorAll<HTMLElement>(".entry");1697    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1698    focusedIndex = idx;1699    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1700  }17011702  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1703    const typed = identities.filter(s => s.type === fieldType);1704    if (!typed.length) return;1705    let collapsed = false;1706    let suppressNextFocus = false;17071708    const list = g.appendChild(document.createElement("div"));1709    list.className = "identity-suggest-list";1710    list.style.display = "none";17111712    // Collapse toggle — sits alone now that filter pills are gone1713    const collapseRow = list.appendChild(document.createElement("div"));1714    collapseRow.className = "identity-filter-row";1715    collapseRow.style.justifyContent = "flex-end";1716    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1717    collapseBtn.type = "button";1718    collapseBtn.className = "identity-collapse-btn";1719    collapseBtn.innerHTML = `<svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 1L5 5L9 1"/></svg>`;1720    collapseBtn.addEventListener("mousedown", (e) => {1721      e.preventDefault();1722      collapsed = !collapsed;1723      collapseBtn.classList.toggle("is-collapsed", collapsed);1724      rowsWrapper.classList.toggle("is-collapsed", collapsed);1725    });17261727    const rowsWrapper = list.appendChild(document.createElement("div"));1728    rowsWrapper.className = "identity-rows";1729    const rows = rowsWrapper.appendChild(document.createElement("div"));1730    rows.className = "identity-rows-inner";17311732    function pick(value: string) {1733      inp.value = value;1734      list.style.display = "none";1735      suppressNextFocus = true;1736      inp.focus();1737    }17381739    function render() {1740      const q = inp.value.toLowerCase();1741      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1742      rows.innerHTML = "";1743      if (!filtered.length) { list.style.display = "none"; return; }1744      for (const s of filtered) {1745        const row = rows.appendChild(document.createElement("button"));1746        row.type = "button"; row.className = "identity-suggest-row";1747        const val = row.appendChild(document.createElement("span"));1748        val.className = "identity-suggest-val"; val.textContent = s.value;1749        const meta = row.appendChild(document.createElement("span"));1750        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1751        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1752        row.addEventListener("keydown", (e) => {1753          if (e.key === "ArrowDown") {1754            e.preventDefault();1755            (row.nextElementSibling as HTMLElement | null)?.focus();1756          } else if (e.key === "ArrowUp") {1757            e.preventDefault();1758            const prev = row.previousElementSibling as HTMLElement | null;1759            if (prev) prev.focus();1760            else inp.focus();1761          } else if (e.key === "Enter" || e.key === " ") {1762            e.preventDefault();1763            pick(s.value);1764          } else if (e.key === "Escape") {1765            e.preventDefault();1766            list.style.display = "none";1767            suppressNextFocus = true;1768            inp.focus();1769          }1770        });1771        row.addEventListener("blur", (e) => {1772          const rt = (e as FocusEvent).relatedTarget as Node | null;1773          if (rt && (rt === inp || list.contains(rt))) return;1774          setTimeout(() => { list.style.display = "none"; }, 150);1775        });1776      }1777      list.style.display = "";1778    }17791780    inp.addEventListener("focus", () => {1781      if (suppressNextFocus) { suppressNextFocus = false; return; }1782      render();1783    });1784    inp.addEventListener("input", render);1785    inp.addEventListener("keydown", (e) => {1786      if (list.style.display === "none") return;1787      if (e.key === "ArrowDown" && !collapsed) {1788        e.preventDefault();1789        (rows.firstElementChild as HTMLElement | null)?.focus();1790      } else if (e.key === "Escape") {1791        e.preventDefault();1792        list.style.display = "none";1793      }1794    });1795    inp.addEventListener("blur", (e) => {1796      const rt = (e as FocusEvent).relatedTarget as Node | null;1797      if (rt && list.contains(rt)) return;1798      setTimeout(() => { list.style.display = "none"; }, 150);1799    });1800  }18011802  async function showCreateForm() {1803    currentMode = "create";1804    container.innerHTML = "";18051806    // Guard: the service worker may lock the vault between when the selector1807    // opens and when the user clicks "New entry". Show the inline unlock form1808    // instead of silently failing on save.1809    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1810    if (!statusRes?.unlocked) {1811      renderLocked();1812      return;1813    }18141815    // Detect page password policy once for this form — reused on every1816    // regenerate click so the user always gets a compliant password.1817    const sitePolicy = detectPasswordPolicy();18181819    // Fetch identities on-demand — they're passed in signup context but not1820    // in login/search context where the user still clicks "New entry".1821    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1822    if (!formIdentities.length) {1823      try {1824        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1825        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1826      } catch { /* silent fallback */ }1827    }18281829    const wrap = document.createElement("div");1830    wrap.className = "create-form-wrap";18311832    // Header1833    const head = document.createElement("div"); head.className = "create-head";1834    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1835    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>`;1836    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1837    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1838    head.append(backBtn, lbl);18391840    // Body1841    const body = document.createElement("div"); body.className = "create-body";18421843    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1844      const g = document.createElement("div"); g.className = "f-group";1845      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1846      const inp = document.createElement("input"); inp.className = "f-input";1847      g.append(l, inp); return { g, inp };1848    }18491850    // Title1851    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1852    body.appendChild(tg.g);18531854    // URL1855    const ug = fGroup("website");1856    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1857    if (loginSubdomain) {1858      const h = document.createElement("div"); h.className = "url-hint";1859      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1860    }1861    body.appendChild(ug.g);18621863    // Username — pre-fill from anchor if it doesn't look like an email1864    const xg = fGroup("username");1865    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1866    xg.inp.placeholder = "johndoe";1867    xg.inp.setAttribute("autocomplete", "off");1868    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1869    body.appendChild(xg.g);18701871    // Email — pre-fill from anchor if it looks like an email1872    const eg = fGroup("email");1873    (eg.inp as HTMLInputElement).type = "email";1874    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1875    eg.inp.placeholder = "[email protected]";1876    eg.inp.setAttribute("autocomplete", "off");1877    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1878    body.appendChild(eg.g);18791880    // Password — full smart generator with charset pills + length slider +1881    // policy hint. Mirrors the main UI's compact generator so users get the1882    // same controls inline as in the popup.1883    const pg = fGroup("password");1884    pg.inp.remove(); // smartGen provides its own display — no separate input needed1885    let currentPassword = prePassword || "";1886    const smartGen = createSmartGenerator({1887      policy: sitePolicy,1888      initialPassword: prePassword || undefined,1889      onChange: (pw) => { currentPassword = pw; },1890    });1891    pg.g.appendChild(smartGen.root);1892    body.appendChild(pg.g);18931894    // Save1895    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1896    saveBtn.textContent = "Save entry";1897    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1898    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1899    saveBtn.addEventListener("click", async () => {1900      const title = tg.inp.value.trim();1901      const pw = currentPassword.trim();1902      const username = xg.inp.value.trim();1903      const email = eg.inp.value.trim();1904      if (!title) {1905        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1906        showFormError("Entry needs a title");1907        return;1908      }1909      if (!pw) {1910        showFormError("Entry needs a password — tap regen to make one");1911        return;1912      }1913      errEl.style.display = "none";1914      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1915      try {1916        const res = await chrome.runtime.sendMessage({1917          type: "ADD_ENTRY",1918          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1919        });1920        if ((res as { ok?: boolean }).ok) {1921          // Fill the detected form. onFillFields uses whichever identity the1922          // page anchored on — the vault captures both username and email.1923          options.onFillFields?.(username || email, pw);1924          showSuccess(title);1925        } else {1926          const errMsg = (res as { error?: string }).error === "vault locked"1927            ? "Vault locked — open Peach to save"1928            : "Could not save entry";1929          showFormError(errMsg);1930          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1931        }1932      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1933    });1934    body.appendChild(saveBtn);1935    body.appendChild(errEl);19361937    wrap.append(head, body);1938    container.appendChild(wrap);1939    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1940  }19411942  function showSuccess(title: string) {1943    currentMode = "success";1944    container.innerHTML = "";1945    const wrap = document.createElement("div"); wrap.className = "success-wrap";1946    const ring = document.createElement("div"); ring.className = "success-ring";1947    ring.innerHTML = checkSvgStr();1948    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1949    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1950    wrap.append(ring, t, s);1951    container.appendChild(wrap);1952    setTimeout(() => dismiss(), 1600);1953  }19541955  function flashActionBtn(btn: HTMLButtonElement) {1956    btn.classList.add("flashed");1957    setTimeout(() => btn.classList.remove("flashed"), 700);1958  }19591960  // M3/QUA-005: when both the direct clipboard write and the background COPY1961  // fallback fail, briefly show the user that the copy did not happen.1962  function flashCopyError(btn: HTMLButtonElement) {1963    const original = btn.textContent ?? "";1964    btn.textContent = "Blocked";1965    btn.classList.add("flashed");1966    setTimeout(() => {1967      btn.classList.remove("flashed");1968      if (btn.isConnected) btn.textContent = original;1969    }, 1200);1970  }19711972  function renderSilverPlatter(entry: SelectorEntry) {1973    container.innerHTML = "";1974    searchInput = null;1975    focusedIndex = -1;1976    currentMode = "silver-platter";19771978    const domHdr = document.createElement("div");1979    domHdr.className = "domain-header";1980    const headText = document.createElement("div");1981    headText.className = "domain-header-text";1982    const eyebrow = document.createElement("div");1983    eyebrow.className = "domain-eyebrow";1984    eyebrow.textContent = "Saved for this site";1985    const domName = document.createElement("div");1986    domName.className = "domain-name";1987    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1988    headText.append(eyebrow, domName);1989    domHdr.appendChild(headText);1990    if (!options.isSignup) {1991      const actions = document.createElement("div");1992      actions.className = "domain-header-actions";19931994      // Search shortcut — same idea as type-to-search below, but visible so1995      // the user can discover that another entry is reachable from a1996      // single-match platter. Sits to the left of the create button.1997      const searchBtn = document.createElement("button");1998      searchBtn.className = "domain-search-btn";1999      searchBtn.type = "button";2000      searchBtn.setAttribute("aria-label", "Search for a different entry");2001      searchBtn.title = "Search for a different entry";2002      searchBtn.innerHTML = searchSvgStr();2003      searchBtn.addEventListener("click", (e) => {2004        e.stopPropagation();2005        query = "";2006        renderList();2007      });2008      actions.appendChild(searchBtn);20092010      const addBtn = document.createElement("button");2011      addBtn.className = "domain-add-btn";2012      addBtn.type = "button";2013      addBtn.setAttribute("aria-label", "Create new entry");2014      addBtn.title = "Create new entry";2015      addBtn.textContent = "+";2016      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2017      actions.appendChild(addBtn);20182019      domHdr.appendChild(actions);2020    }2021    container.appendChild(domHdr);20222023    const platter = document.createElement("div");2024    platter.className = "silver-platter";20252026    const titleEl = document.createElement("div");2027    titleEl.className = "sp-title";2028    titleEl.textContent = entry.title;2029    platter.appendChild(titleEl);20302031    if (entry.email) {2032      const emailEl = document.createElement("div");2033      emailEl.className = "sp-identity-row";2034      const emailLbl = document.createElement("span");2035      emailLbl.className = "sp-identity-label";2036      emailLbl.textContent = "email";2037      const emailVal = document.createElement("span");2038      emailVal.className = "sp-username";2039      emailVal.textContent = entry.email;2040      emailEl.append(emailLbl, emailVal);2041      platter.appendChild(emailEl);2042    }20432044    if (entry.username) {2045      const userEl = document.createElement("div");2046      userEl.className = "sp-identity-row";2047      const userLbl = document.createElement("span");2048      userLbl.className = "sp-identity-label";2049      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2050      const userVal = document.createElement("span");2051      userVal.className = "sp-username";2052      userVal.textContent = entry.username;2053      userEl.append(userLbl, userVal);2054      platter.appendChild(userEl);2055    }20562057    const fillBtn = document.createElement("button");2058    fillBtn.className = "sp-fill-btn";2059    fillBtn.type = "button";2060    fillBtn.textContent = "Fill credentials";2061    fillBtn.addEventListener("click", () => {2062      if (fillBtn.disabled) return;2063      fillBtn.disabled = true;2064      fillBtn.classList.add("filled");2065      fillBtn.innerHTML = checkSvgStr();2066      // Fire the fill, then exit via the standard exit animation. The fill2067      // itself is async (handled in index.ts) — by 400ms the form is filled2068      // and the popup begins its exit. Total dwell from click to host2069      // removal: 400ms + 130ms (exit animation) = 530ms.2070      onSelect(entry.id);2071      setTimeout(() => dismiss(), 400);2072    });2073    platter.appendChild(fillBtn);20742075    const actionsGroup = document.createElement("div");2076    actionsGroup.className = "sp-actions-group";2077    const actionsLabel = document.createElement("div");2078    actionsLabel.className = "sp-actions-label";2079    actionsLabel.textContent = "Copy";2080    actionsGroup.appendChild(actionsLabel);20812082    const actions = document.createElement("div");2083    actions.className = "sp-actions";2084    actionsGroup.appendChild(actions);20852086    if (entry.email) {2087      const copyEmail = document.createElement("button");2088      copyEmail.className = "sp-action-btn";2089      copyEmail.type = "button";2090      copyEmail.title = "Copy email";2091      copyEmail.textContent = "Email";2092      copyEmail.addEventListener("click", async (e) => {2093        e.stopPropagation();2094        let alreadyWritten = false;2095        try {2096          await navigator.clipboard.writeText(entry.email!);2097          alreadyWritten = true;2098        } catch (err) {2099          console.warn("[Peach] clipboard write denied:", err);2100        }2101        const resp = await chrome.runtime.sendMessage({2102          type: "COPY",2103          payload: { text: entry.email, label: "Email", alreadyWritten },2104        }).catch(() => null) as { ok?: boolean } | null;2105        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2106        else flashCopyError(copyEmail);2107      });2108      actions.appendChild(copyEmail);2109    }21102111    const copyU = document.createElement("button");2112    copyU.className = "sp-action-btn";2113    copyU.type = "button";2114    const usernameIsEmail = entry.username?.includes("@") ?? false;2115    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2116    copyU.textContent = usernameIsEmail ? "Email" : "Username";2117    copyU.disabled = !entry.username;2118    copyU.addEventListener("click", async (e) => {2119      e.stopPropagation();2120      if (!entry.username) return;2121      let alreadyWritten = false;2122      try {2123        await navigator.clipboard.writeText(entry.username);2124        alreadyWritten = true;2125      } catch (err) {2126        console.warn("[Peach] clipboard write denied:", err);2127      }2128      const resp = await chrome.runtime.sendMessage({2129        type: "COPY",2130        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2131      }).catch(() => null) as { ok?: boolean } | null;2132      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2133      else flashCopyError(copyU);2134    });2135    actions.appendChild(copyU);21362137    const copyP = document.createElement("button");2138    copyP.className = "sp-action-btn";2139    copyP.type = "button";2140    copyP.title = "Copy password";2141    copyP.textContent = "Password";2142    copyP.addEventListener("click", async (e) => {2143      e.stopPropagation();2144      const resp = await chrome.runtime.sendMessage({2145        type: "GET_ENTRY_FOR_FILL",2146        payload: { id: entry.id },2147      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2148      if (!resp?.ok || !resp.data?.password) return;2149      let alreadyWritten = false;2150      try {2151        await navigator.clipboard.writeText(resp.data.password);2152        alreadyWritten = true;2153      } catch (err) {2154        console.warn("[Peach] clipboard write denied:", err);2155      }2156      const copyResp = await chrome.runtime.sendMessage({2157        type: "COPY",2158        payload: { text: resp.data.password, label: "Password", alreadyWritten },2159      }).catch(() => null) as { ok?: boolean } | null;2160      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2161      else flashCopyError(copyP);2162    });2163    actions.appendChild(copyP);21642165    let trayEl: HTMLDivElement | null = null;2166    let trayInterval: ReturnType<typeof setInterval> | null = null;21672168    function closeTray() {2169      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2170      trayEl?.remove();2171      trayEl = null;2172    }2173    // Register so dismiss() will close the tray and clear the interval2174    // even if the user dismisses without explicitly closing the tray.2175    cleanupHooks.push(closeTray);21762177    async function openTOTPTray() {2178      // Fetch the entry to get the TOTP secret. The selector summary doesn't2179      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2180      // the message-passing surface minimal per Projects.md §5.2).2181      const resp = await chrome.runtime.sendMessage({2182        type: "GET_ENTRY_FOR_FILL",2183        payload: { id: entry.id },2184      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2185      const secret = resp?.ok ? resp.data?.totp : undefined;2186      if (!secret) return;21872188      trayEl = document.createElement("div");2189      trayEl.className = "sp-tray";21902191      const label = document.createElement("span");2192      label.className = "sp-tray-label";2193      label.textContent = "2FA";2194      trayEl.appendChild(label);21952196      const codeEl = document.createElement("div");2197      codeEl.className = "sp-totp-code";2198      trayEl.appendChild(codeEl);21992200      const ringNs = "http://www.w3.org/2000/svg";2201      const ring = document.createElementNS(ringNs, "svg");2202      ring.setAttribute("class", "sp-totp-ring");2203      ring.setAttribute("viewBox", "0 0 24 24");2204      const trackC = document.createElementNS(ringNs, "circle");2205      trackC.setAttribute("class", "ring-track");2206      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2207      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2208      const fillC = document.createElementNS(ringNs, "circle");2209      fillC.setAttribute("class", "ring-fill");2210      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2211      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2212      fillC.setAttribute("stroke-linecap", "round");2213      fillC.setAttribute("stroke-dasharray", "62.83");2214      ring.append(trackC, fillC);2215      trayEl.appendChild(ring);22162217      const copyBtn = document.createElement("button");2218      copyBtn.className = "sp-totp-copy";2219      copyBtn.type = "button";2220      copyBtn.textContent = "Copy";2221      trayEl.appendChild(copyBtn);22222223      function refresh() {2224        const { code, remaining } = generateTOTP(secret!);2225        // Group as "847 291" — easier to read than "847291"2226        codeEl.textContent = code.length === 62227          ? `${code.slice(0, 3)} ${code.slice(3)}`2228          : code;2229        // Ring fills counter-clockwise as time elapses: dashoffset goes from2230        // 0 (full ring) to 62.83 (empty) over the 30s window.2231        const fraction = (30 - remaining) / 30;2232        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2233      }2234      refresh();2235      trayInterval = setInterval(refresh, 1000);22362237      copyBtn.addEventListener("click", async (e) => {2238        e.stopPropagation();2239        const { code } = generateTOTP(secret!);2240        let alreadyWritten = false;2241        try {2242          await navigator.clipboard.writeText(code);2243          alreadyWritten = true;2244        } catch (err) {2245          console.warn("[Peach] clipboard write denied:", err);2246        }2247        const resp = await chrome.runtime.sendMessage({2248          type: "COPY",2249          payload: { text: code, label: "TOTP", alreadyWritten },2250        }).catch(() => null) as { ok?: boolean } | null;2251        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2252        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2253      });22542255      platter.appendChild(trayEl);2256    }22572258    const editBtn = document.createElement("button");2259    editBtn.className = "sp-action-btn sp-action-edit";2260    editBtn.type = "button";2261    editBtn.title = "Edit entry";2262    editBtn.textContent = "Edit";2263    editBtn.addEventListener("click", (e) => {2264      e.stopPropagation();2265      closeTray();2266      void renderInlineEdit(entry);2267    });2268    actions.appendChild(editBtn);22692270    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2271    // "···" toggle was zero-savings (the toggle button took the same space2272    // the "2FA" label needed) and made the code one extra click away.2273    if (entry.hasTotp) void openTOTPTray();22742275    platter.appendChild(actionsGroup);2276    container.appendChild(platter);2277  }22782279  /**2280   * Inline-popup edit mode. Swaps the silver platter for an editable form2281   * over the same shadow-DOM surface so the user never leaves the page.2282   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2283   * with the new fields. Cancel returns without writing.2284   */2285  async function renderInlineEdit(summary: SelectorEntry) {2286    container.innerHTML = "";2287    const wrap = document.createElement("div");2288    wrap.className = "create-form-wrap";22892290    const head = document.createElement("div");2291    head.className = "create-head";2292    const back = document.createElement("button");2293    back.className = "back-btn";2294    back.type = "button";2295    back.title = "Cancel";2296    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>`;2297    back.addEventListener("click", () => renderSilverPlatter(summary));2298    head.appendChild(back);2299    const headLbl = document.createElement("div");2300    headLbl.className = "create-label";2301    headLbl.textContent = "Edit entry";2302    head.appendChild(headLbl);2303    wrap.appendChild(head);23042305    const body = document.createElement("div");2306    body.className = "create-body";23072308    // Loading shimmer while we fetch the full entry2309    const loading = document.createElement("div");2310    loading.className = "empty-hint";2311    loading.textContent = "loading…";2312    body.appendChild(loading);2313    wrap.appendChild(body);2314    container.appendChild(wrap);23152316    const [res, idRes] = await Promise.all([2317      chrome.runtime.sendMessage({2318        type: "GET_ENTRY_FOR_FILL",2319        payload: { id: summary.id },2320      }).catch(() => null),2321      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2322    ]);2323    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2324    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];23252326    if (!entryRes || !entryRes.ok || !entryRes.data) {2327      loading.textContent = "couldn't load this entry. try again from the popup.";2328      return;2329    }2330    body.innerHTML = "";23312332    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2333      const group = document.createElement("div");2334      group.className = "f-group";2335      const lbl = document.createElement("div");2336      lbl.className = "f-label";2337      lbl.textContent = label;2338      const input = document.createElement("input");2339      input.className = "f-input";2340      input.type = type;2341      input.value = value;2342      input.autocomplete = "off";2343      group.append(lbl, input);2344      body.appendChild(group);2345      return { g: group, inp: input };2346    }23472348    const titleInput = field("title", entryRes.data.title ?? "").inp;2349    const urlInput = field("url", entryRes.data.url ?? "").inp;2350    urlInput.classList.add("url-f");2351    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2352    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2353    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2354    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2355    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");23562357    // Password row with reveal toggle + generator2358    const pwGroup = document.createElement("div");2359    pwGroup.className = "f-group";2360    const pwLbl = document.createElement("div");2361    pwLbl.className = "f-label";2362    pwLbl.textContent = "password";2363    const pwRow = document.createElement("div");2364    pwRow.className = "f-row";2365    const pwInput = document.createElement("input");2366    pwInput.className = "f-input";2367    pwInput.type = "password";2368    pwInput.value = entryRes.data.password ?? "";2369    pwInput.autocomplete = "new-password";2370    const revealBtn = document.createElement("button");2371    revealBtn.className = "gen-btn";2372    revealBtn.type = "button";2373    revealBtn.textContent = "show";2374    revealBtn.addEventListener("click", () => {2375      const reveal = pwInput.type === "password";2376      pwInput.type = reveal ? "text" : "password";2377      revealBtn.textContent = reveal ? "hide" : "show";2378    });2379    pwRow.append(pwInput, revealBtn);2380    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2381    editSmartGen.root.style.display = "none";2382    let editGenVisible = false;2383    const genToggleBtn = document.createElement("button");2384    genToggleBtn.className = "gen-toggle-link";2385    genToggleBtn.type = "button";2386    genToggleBtn.textContent = "⚙ generate";2387    genToggleBtn.addEventListener("click", () => {2388      editGenVisible = !editGenVisible;2389      pwRow.style.display = editGenVisible ? "none" : "";2390      editSmartGen.root.style.display = editGenVisible ? "" : "none";2391      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2392    });2393    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2394    body.appendChild(pwGroup);23952396    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;23972398    // Notes2399    const notesGroup = document.createElement("div");2400    notesGroup.className = "f-group";2401    const notesLbl = document.createElement("div");2402    notesLbl.className = "f-label";2403    notesLbl.textContent = "notes";2404    const notesInput = document.createElement("textarea");2405    notesInput.className = "f-input";2406    notesInput.rows = 3;2407    notesInput.value = entryRes.data.notes ?? "";2408    notesInput.style.fontFamily = "Inter, sans-serif";2409    notesInput.style.resize = "vertical";2410    notesGroup.append(notesLbl, notesInput);2411    body.appendChild(notesGroup);24122413    // Save / Cancel row2414    const actionsRow = document.createElement("div");2415    actionsRow.className = "f-row";2416    const saveBtn = document.createElement("button");2417    saveBtn.className = "save-btn";2418    saveBtn.type = "button";2419    saveBtn.textContent = "Save changes";2420    saveBtn.style.flex = "1";2421    const cancelBtn = document.createElement("button");2422    cancelBtn.className = "gen-btn";2423    cancelBtn.type = "button";2424    cancelBtn.textContent = "cancel";2425    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2426    actionsRow.append(saveBtn, cancelBtn);2427    body.appendChild(actionsRow);24282429    saveBtn.addEventListener("click", async () => {2430      saveBtn.disabled = true;2431      const originalLabel = saveBtn.textContent;2432      saveBtn.textContent = "Saving…";2433      const patch: Record<string, unknown> = {2434        title: titleInput.value.trim(),2435        url: urlInput.value.trim(),2436        username: usernameInput.value.trim(),2437        email: emailInput.value.trim() || undefined,2438        password: pwInput.value,2439        totp: totpInput.value.trim(),2440        notes: notesInput.value,2441      };2442      const updateRes = (await chrome.runtime.sendMessage({2443        type: "UPDATE_ENTRY",2444        payload: { id: summary.id, patch },2445      }).catch(() => null)) as { ok: boolean; error?: string } | null;2446      if (!updateRes?.ok) {2447        saveBtn.disabled = false;2448        saveBtn.textContent = originalLabel;2449        const err = document.createElement("div");2450        err.className = "empty-hint";2451        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2452        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2453        body.appendChild(err);2454        setTimeout(() => err.remove(), 3000);2455        return;2456      }2457      // Refresh the platter with updated summary fields2458      const refreshed: SelectorEntry = {2459        id: summary.id,2460        title: patch.title as string,2461        username: patch.username as string,2462        email: patch.email as string | undefined,2463        url: patch.url as string,2464        hasTotp: Boolean(patch.totp),2465        hasPasskey: summary.hasPasskey,2466      };2467      renderSilverPlatter(refreshed);2468    });24692470    queueMicrotask(() => titleInput.focus());2471  }24722473  function renderLocked() {2474    container.innerHTML = "";24752476    // Domain header (same as list view)2477    const domHdr = document.createElement("div");2478    domHdr.className = "domain-header";2479    const eyebrow = document.createElement("div");2480    eyebrow.className = "domain-eyebrow";2481    eyebrow.textContent = "vault locked";2482    const domName = document.createElement("div");2483    domName.className = "domain-name";2484    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2485    domHdr.append(eyebrow, domName);2486    container.appendChild(domHdr);24872488    const wrap = document.createElement("div");2489    wrap.className = "locked-wrap";24902491    // Icon + label row2492    const head = document.createElement("div"); head.className = "locked-head";2493    const icon = document.createElement("div"); icon.className = "locked-icon";2494    icon.innerHTML = keySvgStr();2495    const title = document.createElement("div"); title.className = "locked-title";2496    title.textContent = "unlock to autofill";2497    head.append(icon, title);24982499    // Password input2500    const pwInp = document.createElement("input");2501    pwInp.className = "locked-input";2502    pwInp.type = "password";2503    pwInp.placeholder = "master password";2504    pwInp.setAttribute("autocomplete", "current-password");25052506    // Error line (hidden initially)2507    const errEl = document.createElement("div");2508    errEl.className = "locked-error";2509    errEl.style.display = "none";25102511    // Unlock button2512    const unlockBtn = document.createElement("button");2513    unlockBtn.className = "locked-btn";2514    unlockBtn.type = "button";2515    unlockBtn.textContent = "unlock";25162517    async function tryUnlock() {2518      const pw = pwInp.value.trim();2519      if (!pw) { pwInp.focus(); return; }2520      unlockBtn.disabled = true;2521      unlockBtn.textContent = "unlocking…";2522      errEl.style.display = "none";2523      try {2524        const res = await chrome.runtime.sendMessage({2525          type: "UNLOCK",2526          payload: { password: pw },2527        });2528        if ((res as { ok?: boolean }).ok) {2529          dismiss();2530          options.onUnlocked?.();2531        } else {2532          errEl.textContent = "incorrect password";2533          errEl.style.display = "block";2534          pwInp.value = "";2535          pwInp.focus();2536          unlockBtn.disabled = false;2537          unlockBtn.textContent = "unlock";2538        }2539      } catch {2540        errEl.textContent = "could not reach Peach";2541        errEl.style.display = "block";2542        unlockBtn.disabled = false;2543        unlockBtn.textContent = "unlock";2544      }2545    }25462547    pwInp.addEventListener("keydown", (e) => {2548      e.stopPropagation();2549      if (e.key === "Enter") void tryUnlock();2550    });2551    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2552    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2553    unlockBtn.addEventListener("click", () => void tryUnlock());25542555    wrap.append(head, pwInp, errEl, unlockBtn);2556    container.appendChild(wrap);25572558    // Keep the MV3 service worker alive while the locked popup is visible.2559    // Without this, the SW goes idle (~30 s) while the user types their2560    // password, and the UNLOCK message pays a 100-300 ms wakeup penalty2561    // before the crypto even starts — perceptible as a delay vs the always-2562    // live extension popup page.2563    const keepaliveId = setInterval(() => {2564      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});2565    }, 20_000);2566    cleanupHooks.push(() => clearInterval(keepaliveId));25672568    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2569    // the page reclaims focus from our Shadow DOM input before the user can2570    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2571    // Instead: intercept keystrokes at the document capture phase — this runs2572    // before any page handler regardless of which element technically has2573    // OS focus — and route them into our input.2574    const captureKeydown = (e: KeyboardEvent) => {2575      if (!host.isConnected) {2576        document.removeEventListener("keydown", captureKeydown, true);2577        return;2578      }2579      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2580      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2581      // Intercept before page handlers and give our input focus.2582      e.stopImmediatePropagation();2583      if (e.key === "Escape") { dismiss(true); return; }2584      if (e.key === "Enter") { void tryUnlock(); return; }2585      // For all other printable/editing keys, ensure our input has focus so2586      // the browser delivers the keystroke there naturally.2587      if (document.activeElement !== host) {2588        pwInp.focus({ preventScroll: true });2589      }2590    };2591    captureKeydownRef = captureKeydown;2592    document.addEventListener("keydown", captureKeydown, true);25932594    // Best-effort focus on open — may be overridden by page focus trap,2595    // but the capture listener above handles typing regardless.2596    pwInp.focus({ preventScroll: true });2597    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2598  }25992600  function handleKeyDown(e: KeyboardEvent) {2601    if (options.locked) {2602      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2603      return;2604    }2605    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2606      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2607      return;2608    }2609    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2610    const count = allEntryEls.length;2611    if (document.activeElement === searchInput) {2612      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2613      if (count === 0) return;2614      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2615    }2616    if (count === 0) return;2617    switch (e.key) {2618      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2619      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2620      case "Enter": {2621        if (focusedIndex >= 0) {2622          const el = allEntryEls[focusedIndex] as HTMLElement;2623          const id = el.dataset.id;2624          if (id) { onSelect(id); dismiss(); }2625          else if (el.classList.contains("is-new") || !id) {2626            // "New entry" row (last item, no data-id)2627            showCreateForm();2628          }2629        }2630        break;2631      }2632      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2633    }2634  }26352636  document.addEventListener("keydown", handleKeyDown);26372638  // Type-to-search from the silver platter. A printable single-character2639  // keystroke (no modifier) seeds the search query and switches into the2640  // list view, so the user can pivot to a different entry without first2641  // clicking the search icon. Capture phase so the anchor input does not2642  // receive the character before we hijack it.2643  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2644    if (currentMode !== "silver-platter") return;2645    if (e.ctrlKey || e.metaKey || e.altKey) return;2646    if (e.key.length !== 1) return;2647    e.preventDefault();2648    e.stopImmediatePropagation();2649    query = e.key;2650    renderList();2651  };2652  document.addEventListener("keydown", silverPlatterTypeHandler, true);2653  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));26542655  document.body.appendChild(host);26562657  function updatePosition() {2658    const r = anchorEl.getBoundingClientRect();2659    host.style.top = `${r.bottom + window.scrollY + 5}px`;2660    host.style.left = `${r.left + window.scrollX}px`;2661    host.style.width = `${popupWidth}px`;2662  }2663  // These bindings are referenced from renderLocked()/dismiss() — they MUST2664  // be initialized before renderLocked() runs, or the synchronous assignment2665  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2666  // and throws ReferenceError. The throw lands after the popup is rendered2667  // but before showAutofillSelector returns its dismiss handle, leaving an2668  // orphan host in the DOM (which is what caused the locked-popup stacking2669  // and missing autofocus on every click).2670  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2671  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26722673  if (options.locked) {2674    renderLocked();2675  } else if (options.isSignup && options.savedIdentities) {2676    // State 10: identity helper — signup form detected, show derived2677    // identity list (emails then usernames) instead of vault entry list.2678    renderIdentityHelper();2679  } else if (entries.length === 1 && !options.isSignup) {2680    // Silver platter (State 1): single domain match → focused fill view.2681    // Multi-match goes through renderList instead.2682    renderSilverPlatter(entries[0]!);2683  } else {2684    renderList();2685  }26862687  let exitScheduled = false;2688  function dismiss(userAction = false) {2689    // Idempotent: dismiss() can be called from multiple paths (Escape,2690    // outside click, entry select, fill success, host page nav). The exit2691    // animation must only play once and host.remove() must run exactly once.2692    if (exitScheduled) return;2693    exitScheduled = true;2694    // Detach listeners synchronously so nothing can re-trigger during the2695    // 130ms exit window (a focusin firing here would race against the2696    // dismiss-lock work in Pass 2).2697    stopObserving();2698    document.removeEventListener("click", outsideClick, { capture: true });2699    document.removeEventListener("keydown", handleKeyDown);2700    if (captureKeydownRef) {2701      document.removeEventListener("keydown", captureKeydownRef, true);2702      captureKeydownRef = null;2703    }2704    for (const cleanup of cleanupHooks) {2705      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2706    }2707    if (userAction) options.onDismiss?.();2708    container.classList.add("is-exiting");2709    setTimeout(() => host.remove(), 130);2710  }27112712  function outsideClick(ev: MouseEvent) {2713    const path = ev.composedPath();2714    // Never dismiss when clicking the anchor field itself — that click is2715    // what triggered the selector to open, and the user may click the field2716    // again to re-focus it without intending to close the selector.2717    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2718  }2719  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2720  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);27212722  return dismiss;2723}27242725export function showTOTPSelector(2726  anchorEl: HTMLInputElement,2727  entries: SelectorEntry[],2728  onFill: (id: string) => void,2729  options: { domain?: string; onDismiss?: () => void } = {}2730): () => void {2731  const host = document.createElement("div");2732  host.style.cssText = "position: absolute; z-index: 2147483647;";2733  host.style.setProperty("--peach-accent", accentHex);2734  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2735  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2736  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2737  const shadow = host.attachShadow({ mode: "closed" });27382739  const style = shadow.appendChild(document.createElement("style"));2740  style.textContent = SELECTOR_STYLES;27412742  const rect = anchorEl.getBoundingClientRect();2743  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2744  host.style.left = `${rect.left + window.scrollX}px`;2745  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2746  host.style.width = `${popupWidth}px`;27472748  const container = shadow.appendChild(document.createElement("div"));2749  container.className = "peach-inline-popup";2750  container.setAttribute("data-theme", popupTheme);27512752  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2753  const current = entries.filter((entry) => entry.hasTotp);2754  let focusedIndex = current.length === 1 ? 0 : -1;27552756  function updatePosition() {2757    const r = anchorEl.getBoundingClientRect();2758    host.style.top = `${r.bottom + window.scrollY + 5}px`;2759    host.style.left = `${r.left + window.scrollX}px`;2760    host.style.width = `${popupWidth}px`;2761  }27622763  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27642765  function choose(entry: SelectorEntry) {2766    onFill(entry.id);2767    dismiss();2768  }27692770  function render() {2771    container.innerHTML = "";27722773    const domHdr = document.createElement("div");2774    domHdr.className = "domain-header";2775    const headText = document.createElement("div");2776    headText.className = "domain-header-text";2777    const eyebrow = document.createElement("div");2778    eyebrow.className = "domain-eyebrow";2779    eyebrow.textContent = "2FA code";2780    const domName = document.createElement("div");2781    domName.className = "domain-name";2782    domName.textContent = domain;2783    headText.append(eyebrow, domName);2784    domHdr.appendChild(headText);2785    container.appendChild(domHdr);27862787    if (current.length === 1) {2788      const entry = current[0]!;2789      const platter = document.createElement("div");2790      platter.className = "silver-platter";27912792      const title = document.createElement("div");2793      title.className = "sp-title";2794      title.textContent = entry.title;2795      platter.appendChild(title);27962797      const sub = document.createElement("div");2798      sub.className = "sp-username";2799      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2800      platter.appendChild(sub);28012802      const fill = document.createElement("button");2803      fill.className = "sp-fill-btn";2804      fill.type = "button";2805      fill.textContent = "Fill 2FA code";2806      fill.addEventListener("click", () => choose(entry));2807      platter.appendChild(fill);28082809      container.appendChild(platter);2810      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2811      return;2812    }28132814    const results = document.createElement("div");2815    results.className = "results";2816    container.appendChild(results);28172818    for (let i = 0; i < current.length; i++) {2819      const entry = current[i]!;2820      const row = document.createElement("div");2821      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2822      row.dataset.index = String(i);2823      row.setAttribute("tabindex", "-1");28242825      const icon = document.createElement("div");2826      icon.className = "entry-icon";2827      icon.innerHTML = keySvgStr();2828      row.appendChild(icon);2829      const info = document.createElement("div");2830      info.className = "entry-info";2831      const title = document.createElement("div");2832      title.className = "entry-title";2833      title.textContent = entry.title;2834      const sub = document.createElement("div");2835      sub.className = "entry-sub";2836      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2837      info.append(title, sub);2838      row.appendChild(info);28392840      const badge = document.createElement("span");2841      badge.className = "totp-badge";2842      badge.textContent = "Fill";2843      row.appendChild(badge);2844      row.addEventListener("click", () => choose(entry));2845      results.appendChild(row);2846    }2847  }28482849  function setFocused(index: number) {2850    focusedIndex = index;2851    container.querySelectorAll(".entry").forEach((el, i) => {2852      el.classList.toggle("focused", i === focusedIndex);2853      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2854    });2855  }28562857  function handleKeyDown(e: KeyboardEvent) {2858    if (e.key === "Escape" || e.key === "Tab") {2859      e.preventDefault();2860      dismiss(true);2861      return;2862    }2863    if (current.length === 0) return;2864    if (e.key === "Enter") {2865      e.preventDefault();2866      choose(current[Math.max(0, focusedIndex)]!);2867      return;2868    }2869    if (current.length === 1) return;2870    if (e.key === "ArrowDown") {2871      e.preventDefault();2872      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2873    } else if (e.key === "ArrowUp") {2874      e.preventDefault();2875      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2876    }2877  }28782879  let exitScheduled = false;2880  function dismiss(userAction = false) {2881    if (exitScheduled) return;2882    exitScheduled = true;2883    stopObserving();2884    document.removeEventListener("click", outsideClick, { capture: true });2885    document.removeEventListener("keydown", handleKeyDown);2886    if (userAction) options.onDismiss?.();2887    container.classList.add("is-exiting");2888    setTimeout(() => host.remove(), 130);2889  }28902891  function outsideClick(ev: MouseEvent) {2892    const path = ev.composedPath();2893    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2894  }28952896  document.addEventListener("keydown", handleKeyDown);2897  document.body.appendChild(host);2898  render();2899  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);29002901  return dismiss;2902}29032904export interface CardSelectorEntry {2905  id: string;2906  title: string;2907  cardholderName?: string;2908  last4?: string;2909  expMonth?: string;2910  expYear?: string;2911  network?: import("../shared/types").CardNetwork;2912}29132914interface CardSelectorOptions {2915  domain?: string;2916  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2917  onFill: (entry: import("../shared/types").VaultEntry) => void;2918  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2919  onDismiss?: () => void;2920}29212922/**2923 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2924 * passkey create or get. Renders as a fixed-position floating popup (no2925 * field anchor needed — passkeys don't require a focused input). Uses the2926 * same theme tokens and entrance animation as all other inline popup states.2927 */2928export function showPasskeyProGate(): void {2929  const domain = location.hostname.replace(/^www\./, "");29302931  const host = document.createElement("div");2932  host.setAttribute("data-peach-passkey-gate", "1");2933  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2934  const shadow = host.attachShadow({ mode: "closed" });29352936  const style = document.createElement("style");2937  style.textContent = `2938    :host { all: initial; }2939    .gate-wrap {2940      position: fixed;2941      top: 50%;2942      left: 50%;2943      transform: translate(-50%, -50%);2944      width: 280px;2945      pointer-events: auto;2946      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2947    }2948    @keyframes g-in {2949      from { opacity:0; transform: translate(-50%,-52%); }2950      to   { opacity:1; transform: translate(-50%,-50%); }2951    }2952    .gate-wrap.is-exiting {2953      animation: g-out 130ms ease-in forwards;2954    }2955    @keyframes g-out {2956      to { opacity:0; transform: translate(-50%,-52%); }2957    }2958    .gate {2959      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2960      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2961      border-radius: 12px;2962      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2963      padding: 16px;2964      font-family: Inter, sans-serif;2965    }2966    .gate-header {2967      display: flex;2968      align-items: center;2969      gap: 7px;2970      margin-bottom: 12px;2971      padding-bottom: 10px;2972      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2973    }2974    .gate-domain {2975      font-size: 12px;2976      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2977      font-family: "IBM Plex Mono", monospace;2978      overflow: hidden;2979      text-overflow: ellipsis;2980      white-space: nowrap;2981    }2982    .gate-title {2983      font-size: 14px;2984      font-weight: 500;2985      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2986      margin-bottom: 6px;2987    }2988    .gate-subtitle {2989      font-size: 12px;2990      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2991      line-height: 1.5;2992      margin-bottom: 14px;2993    }2994    .gate-btn {2995      display: block;2996      width: 100%;2997      padding: 9px 0;2998      border-radius: 8px;2999      border: none;3000      cursor: pointer;3001      font-size: 13px;3002      font-family: Inter, sans-serif;3003      font-weight: 500;3004      transition: opacity 100ms;3005      margin-bottom: 7px;3006      text-align: center;3007    }3008    .gate-btn:last-child { margin-bottom: 0; }3009    .gate-btn--accent {3010      background: ${accentHex};3011      color: #fff;3012    }3013    .gate-btn--accent:hover { opacity: 0.88; }3014    .gate-btn--ghost {3015      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3016      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3017    }3018    .gate-btn--ghost:hover { opacity: 0.75; }3019    .backdrop {3020      position: fixed;3021      inset: 0;3022      pointer-events: auto;3023    }3024  `;3025  shadow.appendChild(style);30263027  const backdrop = document.createElement("div");3028  backdrop.className = "backdrop";3029  shadow.appendChild(backdrop);30303031  const wrap = document.createElement("div");3032  wrap.className = "gate-wrap";3033  shadow.appendChild(wrap);30343035  const gate = document.createElement("div");3036  gate.className = "gate";3037  wrap.appendChild(gate);30383039  // Header: peach icon + domain3040  const header = document.createElement("div");3041  header.className = "gate-header";3042  const icon = document.createElement("span");3043  icon.innerHTML = peachIconSvg();3044  const domainEl = document.createElement("span");3045  domainEl.className = "gate-domain";3046  domainEl.textContent = domain;3047  header.append(icon, domainEl);3048  gate.appendChild(header);30493050  const title = document.createElement("div");3051  title.className = "gate-title";3052  title.textContent = "Passkeys are part of Peach Pro.";3053  gate.appendChild(title);30543055  const subtitle = document.createElement("div");3056  subtitle.className = "gate-subtitle";3057  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3058  gate.appendChild(subtitle);30593060  const upgradeBtn = document.createElement("button");3061  upgradeBtn.className = "gate-btn gate-btn--accent";3062  upgradeBtn.type = "button";3063  upgradeBtn.textContent = "Upgrade to Pro";3064  gate.appendChild(upgradeBtn);30653066  const laterBtn = document.createElement("button");3067  laterBtn.className = "gate-btn gate-btn--ghost";3068  laterBtn.type = "button";3069  laterBtn.textContent = "Not right now";3070  gate.appendChild(laterBtn);30713072  function dismiss() {3073    wrap.classList.add("is-exiting");3074    setTimeout(() => host.remove(), 130);3075  }30763077  upgradeBtn.addEventListener("click", () => {3078    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3079    dismiss();3080  });3081  laterBtn.addEventListener("click", dismiss);3082  backdrop.addEventListener("click", dismiss);30833084  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3085    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3086  });30873088  document.body.appendChild(host);3089}30903091/**3092 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3093 * detector sees the page invoke navigator.credentials.create(); content/index.ts3094 * checks vault + decline state then calls this. "Save passkey to Peach"3095 * initiates the popup-context credential flow; "Not now" records a 30-day3096 * decline for the domain so we don't re-show on every page reload.3097 */3098export function showPasskeyRegistrationOffer(args: {3099  rpId: string;3100  rpName?: string;3101  userName?: string;3102  userDisplayName?: string;3103}): void {3104  const domain = location.hostname.replace(/^www\./, "");3105  const displayName = args.rpName || domain;31063107  const host = document.createElement("div");3108  host.setAttribute("data-peach-passkey-offer", "1");3109  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3110  const shadow = host.attachShadow({ mode: "closed" });31113112  const style = document.createElement("style");3113  style.textContent = `3114    :host { all: initial; }3115    .offer-wrap {3116      position: fixed;3117      top: 16px;3118      right: 16px;3119      width: 320px;3120      pointer-events: auto;3121      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3122    }3123    @keyframes o-in {3124      from { opacity: 0; transform: translateY(-6px); }3125      to   { opacity: 1; transform: translateY(0); }3126    }3127    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3128    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3129    .offer {3130      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3131      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3132      border-radius: 12px;3133      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3134      padding: 14px 14px 12px;3135      font-family: Inter, sans-serif;3136      position: relative;3137    }3138    .offer-close {3139      position: absolute;3140      top: 8px;3141      right: 8px;3142      width: 18px;3143      height: 18px;3144      border: none;3145      background: transparent;3146      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3147      cursor: pointer;3148      font-size: 14px;3149      line-height: 1;3150      padding: 0;3151    }3152    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3153    .offer-header {3154      display: flex;3155      align-items: center;3156      gap: 7px;3157      margin-bottom: 8px;3158      padding-bottom: 8px;3159      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3160    }3161    .offer-domain {3162      font-size: 12px;3163      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3164      font-family: "IBM Plex Mono", monospace;3165      overflow: hidden;3166      text-overflow: ellipsis;3167      white-space: nowrap;3168    }3169    .offer-title {3170      font-size: 13px;3171      font-weight: 500;3172      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3173      margin-bottom: 4px;3174    }3175    .offer-subtitle {3176      font-size: 11px;3177      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3178      line-height: 1.45;3179      margin-bottom: 12px;3180    }3181    .offer-btn {3182      display: block;3183      width: 100%;3184      padding: 8px 0;3185      border-radius: 7px;3186      border: none;3187      cursor: pointer;3188      font-size: 12px;3189      font-family: Inter, sans-serif;3190      font-weight: 500;3191      transition: opacity 100ms;3192      margin-bottom: 6px;3193      text-align: center;3194    }3195    .offer-btn:last-child { margin-bottom: 0; }3196    .offer-btn--accent { background: ${accentHex}; color: #fff; }3197    .offer-btn--accent:hover { opacity: 0.88; }3198    .offer-btn--ghost {3199      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3200      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3201    }3202    .offer-btn--ghost:hover { opacity: 0.75; }3203  `;3204  shadow.appendChild(style);32053206  const wrap = document.createElement("div");3207  wrap.className = "offer-wrap";3208  shadow.appendChild(wrap);32093210  const offer = document.createElement("div");3211  offer.className = "offer";3212  wrap.appendChild(offer);32133214  const closeBtn = document.createElement("button");3215  closeBtn.className = "offer-close";3216  closeBtn.type = "button";3217  closeBtn.setAttribute("aria-label", "Dismiss");3218  closeBtn.textContent = "✕";3219  offer.appendChild(closeBtn);32203221  const header = document.createElement("div");3222  header.className = "offer-header";3223  const icon = document.createElement("span");3224  icon.innerHTML = peachIconSvg();3225  const domainEl = document.createElement("span");3226  domainEl.className = "offer-domain";3227  domainEl.textContent = domain;3228  header.append(icon, domainEl);3229  offer.appendChild(header);32303231  const title = document.createElement("div");3232  title.className = "offer-title";3233  title.textContent = "This site supports passkeys.";3234  offer.appendChild(title);32353236  const subtitle = document.createElement("div");3237  subtitle.className = "offer-subtitle";3238  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3239  offer.appendChild(subtitle);32403241  const saveBtn = document.createElement("button");3242  saveBtn.className = "offer-btn offer-btn--accent";3243  saveBtn.type = "button";3244  saveBtn.textContent = "Save passkey to Peach";3245  offer.appendChild(saveBtn);32463247  const laterBtn = document.createElement("button");3248  laterBtn.className = "offer-btn offer-btn--ghost";3249  laterBtn.type = "button";3250  laterBtn.textContent = "Not now";3251  offer.appendChild(laterBtn);32523253  function dismiss(decline: boolean) {3254    if (decline) {3255      chrome.runtime.sendMessage({3256        type: "PASSKEY_OFFER_DECLINE",3257        payload: { domain },3258      }).catch(() => {});3259    }3260    wrap.classList.add("is-exiting");3261    setTimeout(() => host.remove(), 130);3262  }32633264  saveBtn.addEventListener("click", () => {3265    chrome.runtime.sendMessage({3266      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3267      payload: {3268        rpId: args.rpId,3269        rpName: args.rpName ?? displayName,3270        userName: args.userName ?? "user",3271        userDisplayName: args.userDisplayName,3272      },3273    }).catch(() => {});3274    dismiss(false);3275  });3276  laterBtn.addEventListener("click", () => dismiss(true));3277  closeBtn.addEventListener("click", () => dismiss(true));32783279  document.body.appendChild(host);3280}32813282/**3283 * State 11 — passkey available indicator. Shown when the user lands on a3284 * domain for which they already have a stored passkey. Tells them where to3285 * find it (the entry already shows in the vault list); the "Sign in with3286 * passkey" button opens the popup so they can use the platform authenticator3287 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3288 * the actual sign-in transparently, so this banner is informational only.3289 */3290export function showPasskeyAvailable(args: {3291  rpId: string;3292  userName: string;3293  fromBrowser?: "chrome" | "firefox";3294  currentBrowser?: "chrome" | "firefox" | "unknown";3295}): void {3296  const domain = location.hostname.replace(/^www\./, "");3297  const crossBrowser =3298    args.fromBrowser &&3299    args.currentBrowser &&3300    args.currentBrowser !== "unknown" &&3301    args.fromBrowser !== args.currentBrowser;33023303  const host = document.createElement("div");3304  host.setAttribute("data-peach-passkey-available", "1");3305  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3306  const shadow = host.attachShadow({ mode: "closed" });33073308  const style = document.createElement("style");3309  style.textContent = `3310    :host { all: initial; }3311    .avail-wrap {3312      position: fixed;3313      top: 16px;3314      right: 16px;3315      width: 320px;3316      pointer-events: auto;3317      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3318    }3319    @keyframes a-in {3320      from { opacity: 0; transform: translateY(-6px); }3321      to   { opacity: 1; transform: translateY(0); }3322    }3323    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3324    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3325    .avail {3326      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3327      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3328      border-radius: 12px;3329      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3330      padding: 14px 14px 12px;3331      font-family: Inter, sans-serif;3332      position: relative;3333    }3334    .avail-close {3335      position: absolute;3336      top: 8px;3337      right: 8px;3338      width: 18px;3339      height: 18px;3340      border: none;3341      background: transparent;3342      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3343      cursor: pointer;3344      font-size: 14px;3345      line-height: 1;3346      padding: 0;3347    }3348    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3349    .avail-header {3350      display: flex;3351      align-items: center;3352      gap: 7px;3353      margin-bottom: 8px;3354      padding-bottom: 8px;3355      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3356    }3357    .avail-domain {3358      font-size: 12px;3359      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3360      font-family: "IBM Plex Mono", monospace;3361    }3362    .avail-label {3363      font-size: 9px;3364      letter-spacing: 0.16em;3365      text-transform: uppercase;3366      color: ${accentHex};3367      margin-bottom: 4px;3368    }3369    .avail-user {3370      font-size: 13px;3371      font-weight: 500;3372      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3373      margin-bottom: 12px;3374      overflow: hidden;3375      text-overflow: ellipsis;3376      white-space: nowrap;3377    }3378    .avail-cross {3379      font-size: 11px;3380      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3381      line-height: 1.45;3382      margin-bottom: 12px;3383      padding: 8px;3384      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3385      border-radius: 6px;3386    }3387    .avail-btn {3388      display: block;3389      width: 100%;3390      padding: 8px 0;3391      border-radius: 7px;3392      border: none;3393      cursor: pointer;3394      font-size: 12px;3395      font-family: Inter, sans-serif;3396      font-weight: 500;3397      transition: opacity 100ms;3398      margin-bottom: 6px;3399      text-align: center;3400    }3401    .avail-btn:last-child { margin-bottom: 0; }3402    .avail-btn--accent { background: ${accentHex}; color: #fff; }3403    .avail-btn--accent:hover { opacity: 0.88; }3404    .avail-btn--ghost {3405      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3406      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3407    }3408    .avail-btn--ghost:hover { opacity: 0.75; }3409  `;3410  shadow.appendChild(style);34113412  const wrap = document.createElement("div");3413  wrap.className = "avail-wrap";3414  shadow.appendChild(wrap);34153416  const avail = document.createElement("div");3417  avail.className = "avail";3418  wrap.appendChild(avail);34193420  const closeBtn = document.createElement("button");3421  closeBtn.className = "avail-close";3422  closeBtn.type = "button";3423  closeBtn.setAttribute("aria-label", "Dismiss");3424  closeBtn.textContent = "✕";3425  avail.appendChild(closeBtn);34263427  const header = document.createElement("div");3428  header.className = "avail-header";3429  const icon = document.createElement("span");3430  icon.innerHTML = peachIconSvg();3431  const domainEl = document.createElement("span");3432  domainEl.className = "avail-domain";3433  domainEl.textContent = domain;3434  header.append(icon, domainEl);3435  avail.appendChild(header);34363437  const label = document.createElement("div");3438  label.className = "avail-label";3439  label.textContent = "PASSKEY";3440  avail.appendChild(label);34413442  const user = document.createElement("div");3443  user.className = "avail-user";3444  user.textContent = args.userName;3445  avail.appendChild(user);34463447  if (crossBrowser) {3448    const cross = document.createElement("div");3449    cross.className = "avail-cross";3450    cross.textContent =3451      args.fromBrowser === "chrome"3452        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3453        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3454    avail.appendChild(cross);3455  }34563457  const signInBtn = document.createElement("button");3458  signInBtn.className = "avail-btn avail-btn--accent";3459  signInBtn.type = "button";3460  signInBtn.textContent = "Sign in with passkey";3461  avail.appendChild(signInBtn);34623463  const passwordBtn = document.createElement("button");3464  passwordBtn.className = "avail-btn avail-btn--ghost";3465  passwordBtn.type = "button";3466  passwordBtn.textContent = "Use password instead";3467  avail.appendChild(passwordBtn);34683469  function dismiss() {3470    wrap.classList.add("is-exiting");3471    setTimeout(() => host.remove(), 130);3472  }34733474  signInBtn.addEventListener("click", () => {3475    // On Chrome: the user clicking the page's own Sign-in button is what3476    //   triggers webAuthenticationProxy → existing background flow handles it.3477    //   Our button just dismisses since the page itself drives auth.3478    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3479    //   and surface the entry for manual reference (popup view).3480    dismiss();3481    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3482  });3483  passwordBtn.addEventListener("click", dismiss);3484  closeBtn.addEventListener("click", dismiss);34853486  document.body.appendChild(host);3487}34883489/**3490 * State 7 — card silver platter. Single-card focused fill view rendered3491 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3492 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3493 * so card and login flows render identically. Multi-card list view is a3494 * follow-up; today this picks the first card.3495 */3496export function showCardSelector(3497  anchorEl: HTMLInputElement,3498  cards: CardSelectorEntry[],3499  options: CardSelectorOptions3500): () => void {3501  if (cards.length === 0) return () => {};3502  const card = cards[0]!;35033504  const host = document.createElement("div");3505  host.style.cssText = "position: absolute; z-index: 2147483647;";3506  host.style.setProperty("--peach-accent", accentHex);3507  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3508  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3509  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3510  const shadow = host.attachShadow({ mode: "closed" });35113512  const style = shadow.appendChild(document.createElement("style"));3513  style.textContent = SELECTOR_STYLES;35143515  const rect = anchorEl.getBoundingClientRect();3516  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3517  host.style.left = `${rect.left + window.scrollX}px`;3518  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;35193520  const container = shadow.appendChild(document.createElement("div"));3521  container.className = "peach-inline-popup";3522  container.setAttribute("data-theme", popupTheme);35233524  // Domain header — eyebrow communicates the card context, not the site3525  const domHdr = document.createElement("div");3526  domHdr.className = "domain-header";3527  const eyebrow = document.createElement("div");3528  eyebrow.className = "domain-eyebrow";3529  eyebrow.textContent = "Pay with Peach";3530  const domName = document.createElement("div");3531  domName.className = "domain-name";3532  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3533  domHdr.append(eyebrow, domName);3534  container.appendChild(domHdr);35353536  const platter = document.createElement("div");3537  platter.className = "card-platter";35383539  if (card.network && card.network !== "unknown") {3540    const net = document.createElement("div");3541    net.className = "cp-network";3542    net.textContent = card.network;3543    platter.appendChild(net);3544  }35453546  const nick = document.createElement("div");3547  nick.className = "cp-nickname";3548  nick.textContent = card.title;3549  platter.appendChild(nick);35503551  if (card.last4) {3552    const l4 = document.createElement("div");3553    l4.className = "cp-last4";3554    l4.textContent = `•••• ${card.last4}`;3555    platter.appendChild(l4);3556  }35573558  const meta = document.createElement("div");3559  meta.className = "cp-meta";3560  if (card.cardholderName) {3561    const name = document.createElement("span");3562    name.textContent = card.cardholderName;3563    meta.appendChild(name);3564  }3565  if (card.expMonth && card.expYear) {3566    if (card.cardholderName) {3567      const sep = document.createElement("span");3568      sep.className = "cp-meta-sep";3569      sep.textContent = "·";3570      meta.appendChild(sep);3571    }3572    const exp = document.createElement("span");3573    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3574    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3575    meta.appendChild(exp);3576  }3577  if (meta.childElementCount > 0) platter.appendChild(meta);35783579  const fillWrap = document.createElement("div");3580  fillWrap.className = "cp-fill-wrap";3581  const fillBtn = document.createElement("button");3582  fillBtn.className = "sp-fill-btn";3583  fillBtn.type = "button";3584  fillBtn.textContent = "Fill card details";3585  fillBtn.addEventListener("click", async () => {3586    if (fillBtn.disabled) return;3587    fillBtn.disabled = true;3588    fillBtn.classList.add("filled");3589    fillBtn.innerHTML = checkSvgStr();3590    const resp = await chrome.runtime.sendMessage({3591      type: "GET_ENTRY_FOR_FILL",3592      payload: { id: card.id },3593    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3594    if (resp?.ok && resp.data) options.onFill(resp.data);3595    setTimeout(() => dismiss(), 400);3596  });3597  fillWrap.appendChild(fillBtn);3598  platter.appendChild(fillWrap);35993600  // Secondary actions — copy number, copy CVC, dismiss3601  const actions = document.createElement("div");3602  actions.className = "sp-actions";36033604  function flashBtn(b: HTMLButtonElement) {3605    b.classList.add("flashed");3606    setTimeout(() => b.classList.remove("flashed"), 700);3607  }36083609  // M3/QUA-005: clipboard + background COPY both failed — show user.3610  function flashCopyError(b: HTMLButtonElement) {3611    const original = b.textContent ?? "";3612    b.textContent = "Blocked";3613    b.classList.add("flashed");3614    setTimeout(() => {3615      b.classList.remove("flashed");3616      if (b.isConnected) b.textContent = original;3617    }, 1200);3618  }36193620  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3621    const resp = await chrome.runtime.sendMessage({3622      type: "GET_ENTRY_FOR_FILL",3623      payload: { id: card.id },3624    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3625    return resp?.ok && resp.data ? resp.data : null;3626  }36273628  const copyNum = document.createElement("button");3629  copyNum.className = "sp-action-btn";3630  copyNum.type = "button";3631  copyNum.title = "Copy card number";3632  copyNum.textContent = "Copy number";3633  copyNum.addEventListener("click", async (e) => {3634    e.stopPropagation();3635    const full = await fetchFullCard();3636    if (!full?.cardNumber) return;3637    let alreadyWritten = false;3638    try {3639      await navigator.clipboard.writeText(full.cardNumber);3640      alreadyWritten = true;3641    } catch (err) {3642      console.warn("[Peach] clipboard write denied:", err);3643    }3644    const resp = await chrome.runtime.sendMessage({3645      type: "COPY",3646      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3647    }).catch(() => null) as { ok?: boolean } | null;3648    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3649    else flashCopyError(copyNum);3650  });3651  actions.appendChild(copyNum);36523653  const copyCvc = document.createElement("button");3654  copyCvc.className = "sp-action-btn";3655  copyCvc.type = "button";3656  copyCvc.title = "Copy CVC";3657  copyCvc.textContent = "Copy CVC";3658  copyCvc.addEventListener("click", async (e) => {3659    e.stopPropagation();3660    const full = await fetchFullCard();3661    if (!full?.cvc) return;3662    let alreadyWritten = false;3663    try {3664      await navigator.clipboard.writeText(full.cvc);3665      alreadyWritten = true;3666    } catch (err) {3667      console.warn("[Peach] clipboard write denied:", err);3668    }3669    const resp = await chrome.runtime.sendMessage({3670      type: "COPY",3671      payload: { text: full.cvc, label: "CVC", alreadyWritten },3672    }).catch(() => null) as { ok?: boolean } | null;3673    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3674    else flashCopyError(copyCvc);3675  });3676  actions.appendChild(copyCvc);36773678  const closeBtn = document.createElement("button");3679  closeBtn.className = "sp-action-btn";3680  closeBtn.type = "button";3681  closeBtn.title = "Dismiss";3682  closeBtn.textContent = "✕";3683  closeBtn.addEventListener("click", (e) => {3684    e.stopPropagation();3685    dismiss(true);3686  });3687  actions.appendChild(closeBtn);36883689  platter.appendChild(actions);3690  container.appendChild(platter);36913692  document.body.appendChild(host);3693  function updatePosition() {3694    const r = anchorEl.getBoundingClientRect();3695    host.style.top = `${r.bottom + window.scrollY + 5}px`;3696    host.style.left = `${r.left + window.scrollX}px`;3697  }3698  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);36993700  function onKeyDown(e: KeyboardEvent) {3701    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3702  }3703  document.addEventListener("keydown", onKeyDown);37043705  let exitScheduled = false;3706  function dismiss(userAction = false) {3707    if (exitScheduled) return;3708    exitScheduled = true;3709    stopObserving();3710    document.removeEventListener("click", outsideClick, { capture: true });3711    document.removeEventListener("keydown", onKeyDown);3712    if (userAction) options.onDismiss?.();3713    container.classList.add("is-exiting");3714    setTimeout(() => host.remove(), 130);3715  }37163717  function outsideClick(ev: MouseEvent) {3718    const path = ev.composedPath();3719    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3720  }3721  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);37223723  return dismiss;3724}