inject.ts

146.8 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 { detectPasswordPolicy } from "./policy";1516let accentHex = "#E8956D";17let popupTheme: "dark" | "light" = "dark";18chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {19  const data = resp?.data;20  const name = data?.accentColor ?? "peach";21  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";22  popupTheme = data?.theme === "light" ? "light" : "dark";23});2425// 8-digit hex alpha helpers for the accent-derived shadow tokens.26// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing27// two hex digits as the alpha channel.28function withAlpha(hex: string, alpha: string): string {29  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS30  // always exposes 6-digit hex, so this is a guard against future changes31  // shipping shorthand colors that would silently break the var injection.32  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;33}3435export interface SelectorEntry {36  id: string;37  title: string;38  username?: string;39  email?: string;40  url?: string;41  hasTotp?: boolean;42  /** True when the entry also has a passkey credential attached. */43  hasPasskey?: boolean;44}4546interface SelectorOptions {47  domain?: string;48  searchableEntries?: SelectorEntry[];49  /** True when shown on a signup form — changes header label and entry-click behaviour */50  isSignup?: boolean;51  /**52   * Derived identity list (emails then usernames) for signup mode (State 10).53   * When present, renderIdentityHelper() is used instead of renderList().54   */55  savedIdentities?: SavedIdentity[];56  /**57   * Called after the user picks a saved identity (signup mode only) or58   * after successfully saving a new entry on a signup form.59   * Lets the caller fill the visible username + password fields.60   */61  onFillFields?: (username: string, password: string) => void;62  /**63   * When true, show an inline unlock form instead of the entries list.64   * Used when the vault is locked so the user can unlock without opening65   * the popup.66   */67  locked?: boolean;68  /**69   * Called after a successful inline unlock — the caller should re-query70   * entries and re-open the selector with real data.71   */72  onUnlocked?: () => void;73  /**74   * Called when the user explicitly dismisses the selector (Escape, Tab, or75   * click outside) — NOT when an entry is selected or on auto-close.76   * Used by the caller to suppress spurious reopens on the same field.77   */78  onDismiss?: () => void;79}8081function getDomainFromUrl(url: string): string {82  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }83}8485function keySvgStr(): string {86  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>`;87}8889function plusSvgStr(): string {90  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>`;91}9293function searchSvgStr(): string {94  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>`;95}9697function backSvgStr(): string {98  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.4" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 2.5L3.5 6l4 3.5"/></svg>`;99}100101function peachIconSvg(): string {102  // Peach body stays brand-peach regardless of `accentHex` — a sage or103  // sky accent must not turn the autofill icon green or blue. Accent104  // color still tints surrounding glow/hover halos below.105  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>`;106}107108function checkSvgStr(): string {109  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>`;110}111112function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {113  const { hostname, origin } = location;114  const parts = hostname.split(".");115  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",116    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",117    "oidc", "federation", "saml", "cas", "ldap"];118  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());119  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;120  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);121  return { origin, title, loginSubdomain };122}123124/**125 * Shows a bottom-of-page toast after filling credentials when the entry has126 * never matched the current site — offering to add the current origin to the127 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.128 */129export function showRememberSiteToast(130  pageDomain: string,131  entryId: string,132): void {133  const host = document.createElement("div");134  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";135  host.style.setProperty("--peach-accent", accentHex);136  const shadow = host.attachShadow({ mode: "closed" });137138  const style = document.createElement("style");139  style.textContent = `140    .bar {141      display:flex;align-items:center;gap:10px;padding:10px 14px;142      background:#131109;border:1px solid rgba(240,232,216,0.09);143      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);144      font-family:Inter,sans-serif;white-space:nowrap;145      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;146    }147    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }148    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }149    .yes {150      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;151      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;152    }153    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }154    .no {155      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;156      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;157    }158  `;159  shadow.appendChild(style);160161  const bar = document.createElement("div"); bar.className = "bar";162  const txt = document.createElement("span"); txt.className = "txt";163  txt.textContent = `Remember ${pageDomain} for this entry?`;164  const yesBtn = document.createElement("button"); yesBtn.className = "yes";165  yesBtn.textContent = "Remember";166  yesBtn.addEventListener("click", async () => {167    await chrome.runtime.sendMessage({168      type: "ADD_ADDITIONAL_URL",169      payload: { id: entryId, url: location.origin },170    });171    host.remove();172  });173  const noBtn = document.createElement("button"); noBtn.className = "no";174  noBtn.textContent = "Not now";175  noBtn.addEventListener("click", () => host.remove());176  bar.append(txt, yesBtn, noBtn);177  shadow.appendChild(bar);178  document.body.appendChild(host);179  setTimeout(() => host.remove(), 9000);180}181182interface SmartGenerator {183  root: HTMLElement;184  getPassword: () => string;185  /** Copy the current password to the clipboard with the standard pulse UX. */186  copy: () => Promise<void>;187}188189interface SmartGeneratorOptions {190  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */191  policy: PasswordPolicy;192  /**193   * Seed value: used as the displayed password without regenerating, e.g. the194   * password the user already typed into the page. The generator still195   * regenerates the moment any control changes.196   */197  initialPassword?: string;198  /** Fires every time the password regenerates (initial + on changes). */199  onChange?: (pw: string) => void;200}201202/**203 * Build the inline-popup smart-password generator. Mirrors the main popup's204 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset205 * pills + a policy hint that names the constraints Peach detected on the206 * page. Writing this in pure DOM rather than reusing the Solid component207 * keeps the content-script bundle small.208 */209function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {210  const policy = opts.policy ?? {};211212  // Start at site max (strongest password the site accepts), fall back to 64213  let length = policy.maxLength ?? 64;214  if (policy.minLength) length = Math.max(length, policy.minLength);215  if (length < 8) length = 8;216  if (length > 128) length = 128;217218  let upper = true;219  let lower = true;220  let numbers = true;221  let symbols = !policy.forbidsSymbols;222  if (policy.requiresSymbols) symbols = true;223  const forbiddenChars = policy.forbiddenChars ?? "";224225  let password = "";226227  const root = document.createElement("div");228  root.className = "pwgen-block";229230  const displayRow = root.appendChild(document.createElement("div"));231  displayRow.className = "pwgen-display-row";232  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;233  output.type = "text";234  output.className = "pwgen-output";235  output.setAttribute("autocomplete", "off");236  output.setAttribute("spellcheck", "false");237  output.setAttribute("autocorrect", "off");238  output.setAttribute("autocapitalize", "off");239240  const regenBtn = displayRow.appendChild(document.createElement("button"));241  regenBtn.className = "pwgen-icon-btn";242  regenBtn.type = "button";243  regenBtn.setAttribute("aria-label", "Regenerate password");244  regenBtn.title = "Regenerate";245  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>`;246247  const copyBtn = displayRow.appendChild(document.createElement("button"));248  copyBtn.className = "pwgen-icon-btn";249  copyBtn.type = "button";250  copyBtn.setAttribute("aria-label", "Copy password");251  copyBtn.title = "Copy";252  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>`;253254  const controls = root.appendChild(document.createElement("div"));255  controls.className = "pwgen-controls-row";256  const slider = controls.appendChild(document.createElement("input"));257  slider.type = "range";258  slider.className = "pwgen-slider";259  slider.min = "8";260  slider.max = "128";261  slider.value = String(length);262  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));263  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));264  const lenNum = controls.appendChild(document.createElement("span"));265  lenNum.className = "pwgen-len-num pwgen-len-num--edit";266  lenNum.textContent = String(length);267  lenNum.addEventListener("click", () => {268    const li = document.createElement("input");269    li.type = "text"; li.inputMode = "numeric";270    li.className = "pwgen-len-input"; li.value = String(length);271    lenNum.replaceWith(li);272    requestAnimationFrame(() => li.select());273    function commitLenEdit() {274      const n = parseInt(li.value, 10);275      if (!isNaN(n)) {276        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));277        slider.value = String(length);278        regenerate();279      }280      lenNum.textContent = String(length);281      li.replaceWith(lenNum);282    }283    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });284    li.addEventListener("blur", commitLenEdit);285  });286287  const pills = root.appendChild(document.createElement("div"));288  pills.className = "pwgen-pills";289290  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {291    const b = document.createElement("button");292    b.type = "button";293    b.className = `pwgen-pill ${on ? "is-on" : ""}`;294    b.textContent = label;295    b.addEventListener("click", () => {296      const next = !b.classList.contains("is-on");297      b.classList.toggle("is-on", next);298      onToggle(next);299    });300    return b;301  }302  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));303  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));304  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));305  pills.appendChild(makePill("!@#", symbols, (next) => {306    // The site forbids symbols — UI lets the user override but still warn.307    symbols = next;308    regenerate();309  }));310311  // Policy hint — surfaces what Peach read off the site so the user knows the312  // generator is already tuned to it. Only shows when something interesting313  // was detected.314  const hintParts: string[] = [];315  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);316  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);317  if (policy.requiresSymbols) hintParts.push("requires symbols");318  if (policy.forbidsSymbols) hintParts.push("no symbols");319  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);320  if (hintParts.length > 0) {321    const hint = root.appendChild(document.createElement("div"));322    hint.className = "pwgen-policy-hint";323    const accent = document.createElement("span");324    accent.className = "pwgen-hint-accent";325    accent.textContent = "site rules · ";326    const text = document.createTextNode(hintParts.join(" · "));327    hint.appendChild(accent);328    hint.appendChild(text);329  }330331  function regenerate() {332    // Falls back gracefully when the user toggles every charset off — the333    // shared generator forces lowercase in that case rather than throwing.334    password = generatePassword({335      length,336      includeUppercase: upper,337      includeLowercase: lower,338      includeNumbers: numbers,339      includeSymbols: symbols,340      forbiddenChars,341    });342    output.value = password;343    opts.onChange?.(password);344  }345346  output.addEventListener("input", () => {347    password = output.value;348    length = password.length;349    slider.value = String(Math.max(8, Math.min(128, length)));350    lenNum.textContent = String(length);351    opts.onChange?.(password);352  });353354  slider.addEventListener("input", () => {355    length = parseInt(slider.value, 10);356    lenNum.textContent = String(length);357    regenerate();358  });359  regenBtn.addEventListener("click", regenerate);360361  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;362  async function copy(): Promise<void> {363    try {364      await navigator.clipboard.writeText(password);365      copyBtn.classList.add("is-copied");366      if (copyResetTimer) clearTimeout(copyResetTimer);367      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);368    } catch {369      // Clipboard API may be denied — silently no-op; user still has regen UI.370    }371  }372  copyBtn.addEventListener("click", () => { void copy(); });373374  if (opts.initialPassword) {375    password = opts.initialPassword;376    output.value = password;377    opts.onChange?.(password);378  } else {379    regenerate();380  }381382  return {383    root,384    getPassword: () => password,385    copy,386  };387}388389export function observeAnchorPosition(390  anchorEl: HTMLElement,391  onUpdate: () => void392): () => void {393  let rafId = 0;394  let burstUntil = 0;395396  const runUpdate = () => {397    rafId = 0;398    onUpdate();399    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);400  };401  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };402  const scheduleBurst = (ms = 220) => {403    burstUntil = Math.max(burstUntil, performance.now() + ms);404    scheduleUpdate();405  };406407  const resizeObserver = new ResizeObserver(() => scheduleBurst());408  resizeObserver.observe(anchorEl);409  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);410411  const mutationObserver = new MutationObserver(() => scheduleBurst());412  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });413  if (anchorEl.parentElement) {414    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });415  }416417  const onScroll = () => scheduleUpdate();418  window.addEventListener("scroll", onScroll, true);419  window.addEventListener("resize", onScroll);420  window.visualViewport?.addEventListener("resize", onScroll);421  window.visualViewport?.addEventListener("scroll", onScroll);422  anchorEl.addEventListener("focus", () => scheduleBurst());423  anchorEl.addEventListener("input", () => scheduleBurst());424425  scheduleBurst(260);426427  return () => {428    if (rafId) cancelAnimationFrame(rafId);429    resizeObserver.disconnect();430    mutationObserver.disconnect();431    window.removeEventListener("scroll", onScroll, true);432    window.removeEventListener("resize", onScroll);433    window.visualViewport?.removeEventListener("resize", onScroll);434    window.visualViewport?.removeEventListener("scroll", onScroll);435  };436}437438export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {439  const button = document.createElement("button");440  button.type = "button";441  button.setAttribute("aria-label", "Peach autofill");442  button.title = "Fill with Peach";443  button.innerHTML = peachIconSvg();444  // position: fixed is load-bearing — not absolute. Absolute positioning445  // inherits the nearest positioned ancestor's box, which on sites with446  // overflow:hidden or sticky parents clips or offsets the icon. Fixed447  // anchors to the viewport and escapes all parent layout.448  button.style.cssText = `449    position: fixed; z-index: 2147483646;450    width: 26px; height: 26px; cursor: pointer;451    pointer-events: auto; border: none; padding: 3px;452    display: inline-flex; align-items: center; justify-content: center;453    background: transparent; border-radius: 999px;454    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;455    opacity: 0;456  `;457  button.addEventListener("mouseenter", () => {458    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;459    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;460    button.style.transform = "scale(1.08)";461  });462  button.addEventListener("mouseleave", () => {463    button.style.background = "transparent";464    button.style.boxShadow = "none";465    button.style.transform = "none";466  });467  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });468  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });469470  document.body.appendChild(button);471472  function updatePosition() {473    const rect = field.getBoundingClientRect();474    if (rect.width === 0 || rect.height === 0) {475      button.style.opacity = "0"; button.style.pointerEvents = "none";476      return;477    }478    const sz = 26;479    const inset = Math.max(5, Math.min(10, rect.height * 0.22));480    const top = rect.top + rect.height / 2 - sz / 2;481    // Clamp left so the icon stays fully inside the field's right edge, never482    // spilling onto an adjacent sibling button.483    const minLeft = rect.left + 4;484    const left = Math.max(minLeft, rect.right - sz - inset);485    // Hide if the field is too narrow to fit the icon cleanly (< 40px)486    if (rect.width < 40) {487      button.style.opacity = "0"; button.style.pointerEvents = "none";488      return;489    }490    button.style.top = `${top}px`;491    button.style.left = `${left}px`;492    button.style.opacity = "1"; button.style.pointerEvents = "auto";493  }494  updatePosition();495  requestAnimationFrame(() => { button.style.opacity = "1"; });496  const stopObserving = observeAnchorPosition(field, updatePosition);497  return () => { stopObserving(); button.remove(); };498}499500// All theme-dependent values resolve through tokens scoped to501// .peach-inline-popup[data-theme="dark|light"]. Accent variables502// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)503// are identical in both themes — only surface tokens differ. See504// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the505// theme switch — only literal brand-peach in peachIconSvg may stay raw.506const SELECTOR_STYLES = `507  :host { all: initial; }508  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }509510  .peach-inline-popup[data-theme="dark"] {511    --peach-bg:           #1a1410;512    --peach-bg-card:      #221c16;513    --peach-text:         #f5f0ea;514    --peach-text-dim:     #8a7a6a;515    --peach-text-muted:   #4a3a2a;516    --peach-border:       rgba(255,255,255,0.07);517    --peach-input-bg:     rgba(255,255,255,0.05);518    --peach-input-border: rgba(255,255,255,0.08);519  }520  .peach-inline-popup[data-theme="light"] {521    --peach-bg:           #fdf8f4;522    --peach-bg-card:      #f5ede4;523    --peach-text:         #1c1310;524    --peach-text-dim:     #6b5a4a;525    --peach-text-muted:   #a89080;526    --peach-border:       rgba(0,0,0,0.08);527    --peach-input-bg:     rgba(0,0,0,0.04);528    --peach-input-border: rgba(0,0,0,0.10);529  }530531  .peach-inline-popup {532    background: var(--peach-bg);533    border: 1px solid var(--peach-border-accent, var(--peach-border));534    border-radius: 14px;535    overflow: hidden;536    box-shadow:537      0 8px 40px var(--peach-glow, transparent),538      0 2px 12px rgba(0,0,0,0.5);539    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;540    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;541    transition: height 220ms cubic-bezier(0.16,1,0.3,1);542  }543  /* Light theme: shadow against a light page is too strong otherwise — drop both544     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */545  .peach-inline-popup[data-theme="light"] {546    box-shadow:547      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),548      0 2px 12px rgba(0,0,0,0.12);549  }550  .peach-inline-popup.is-exiting {551    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;552    pointer-events: none;553  }554555  @keyframes peach-enter {556    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }557    65%  { opacity: 1; filter: blur(0); }558    100% { opacity: 1; transform: translateY(0) scale(1); }559  }560  @keyframes peach-exit {561    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }562    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }563  }564  @keyframes peach-slide-in {565    from { opacity: 0; transform: translateX(12px); }566    to   { opacity: 1; transform: translateX(0); }567  }568  @keyframes peach-slide-back {569    from { opacity: 0; transform: translateX(-12px); }570    to   { opacity: 1; transform: translateX(0); }571  }572  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }573  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }574575  /* Domain header */576  .domain-header {577    padding: 9px 13px 7px;578    border-bottom: 1px solid var(--peach-border);579    display: flex; align-items: center; justify-content: space-between;580    gap: 8px;581  }582  .domain-header-text {583    display: flex; flex-direction: column; gap: 2px;584    min-width: 0; flex: 1;585  }586  .domain-eyebrow {587    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;588    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;589  }590  .domain-name {591    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);592    font-family: "IBM Plex Mono", monospace;593    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;594  }595  .domain-header-actions {596    display: inline-flex; align-items: center; gap: 5px;597    flex-shrink: 0;598  }599  .domain-add-btn,600  .domain-search-btn {601    flex-shrink: 0;602    width: 22px; height: 22px;603    display: inline-flex; align-items: center; justify-content: center;604    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);605    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);606    border-radius: 6px;607    color: var(--peach-accent);608    cursor: pointer; padding: 0;609    transition: background 120ms, border-color 120ms, transform 80ms;610    font-family: "IBM Plex Mono", monospace;611    font-size: 14px; line-height: 1;612  }613  .domain-add-btn:hover,614  .domain-search-btn:hover {615    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);616    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);617    transform: scale(1.06);618  }619  .domain-add-btn:active,620  .domain-search-btn:active { transform: scale(0.96); }621622  /* Search */623  .search-wrap {624    padding: 9px 12px 7px;625    border-bottom: 1px solid var(--peach-border);626  }627  .search {628    width: 100%; background: var(--peach-input-bg);629    border: 1px solid var(--peach-input-border);630    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;631    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;632    transition: border-color 120ms, box-shadow 120ms;633  }634  .search:focus {635    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);636    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);637  }638  .search::placeholder { color: var(--peach-text-muted); }639640  /* Results */641  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }642  .results::-webkit-scrollbar { display: none; }643644  /* Entry rows */645  .entry {646    display: flex; align-items: center; padding: 8px 12px;647    cursor: pointer; border-bottom: 1px solid var(--peach-border);648    transition: background 70ms; position: relative; outline: none;649  }650  .entry:last-child { border-bottom: none; }651  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }652  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }653  .entry.focused::before {654    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;655    width: 2px; border-radius: 2px;656    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);657  }658659  .entry-icon {660    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;661    background: var(--peach-input-bg); border: 1px solid var(--peach-border);662    display: flex; align-items: center; justify-content: center;663    overflow: hidden; margin-right: 10px;664  }665  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }666  .entry-icon.is-new {667    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);668    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);669    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);670  }671672  .entry-info { flex: 1; min-width: 0; }673  .entry-title {674    font-size: 12.5px; color: var(--peach-text);675    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;676    line-height: 1.3;677  }678  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }679  .entry-sub {680    font-size: 10px; color: var(--peach-text-dim);681    font-family: "IBM Plex Mono", monospace;682    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;683    margin-top: 1px;684  }685686  .totp-badge {687    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;688    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);689    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);690    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;691  }692  .passkey-badge {693    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;694    border-radius: 4px;695    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);696    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);697    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);698    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;699  }700701  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }702703  .empty-hint {704    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);705    font-family: "IBM Plex Mono", monospace;706  }707708  /* Create form */709  .create-form-wrap {710    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;711  }712  .create-head {713    display: flex; align-items: center; gap: 8px;714    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);715  }716  .back-btn {717    background: transparent; border: none; cursor: pointer;718    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;719    display: flex; align-items: center; line-height: 0;720    transition: color 100ms, background 100ms;721  }722  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }723  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }724  /* minmax(0, 1fr) caps the grid track at the popup width — without it,725     long monospace content (e.g. a 60-char generated password) would726     auto-size the track wider than the popup and overflow the right edge. */727  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }728  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }729  .f-label {730    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;731    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;732  }733  .f-input {734    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);735    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;736    font-size: 11px; font-family: "IBM Plex Mono", monospace;737    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;738  }739  .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); }740  .f-input::placeholder { color: var(--peach-text-muted); }741  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }742  .f-row { display: flex; gap: 6px; }743  .f-row .f-input { flex: 1; min-width: 0; }744  .gen-btn {745    padding: 0 10px; border-radius: 7px; border: none;746    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);747    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);748    font-size: 10px; font-family: "IBM Plex Mono", monospace;749    cursor: pointer; white-space: nowrap; flex-shrink: 0;750    display: flex; align-items: center; gap: 4px;751    transition: background 100ms;752  }753  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }754  .gen-toggle-link {755    background: none; border: none; padding: 2px 0;756    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);757    font-size: 10px; font-family: "IBM Plex Mono", monospace;758    cursor: pointer; text-align: left; transition: color 100ms;759  }760  .gen-toggle-link:hover { color: var(--peach-accent); }761  .save-btn {762    width: 100%; padding: 8px; border-radius: 8px; border: none;763    background: var(--peach-accent); color: #fff; font-size: 12px;764    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;765    transition: background 120ms, box-shadow 120ms, transform 80ms;766    letter-spacing: 0.01em;767  }768  .save-btn:hover {769    background: color-mix(in srgb, var(--peach-accent) 82%, #000);770    box-shadow: 0 4px 20px var(--peach-glow, transparent);771  }772  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }773  .url-hint {774    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);775    font-family: "IBM Plex Mono", monospace; font-style: italic;776  }777778  /* Success */779  .success-wrap {780    display: flex; flex-direction: column; align-items: center;781    padding: 24px 16px 20px; gap: 8px;782    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;783  }784  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }785  .success-ring {786    width: 40px; height: 40px; border-radius: 50%;787    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);788    display: flex; align-items: center; justify-content: center;789  }790  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }791  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }792793  /* Silver platter (State 1 — single match) */794  .silver-platter {795    padding: 14px 14px 12px;796    display: flex; flex-direction: column; gap: 6px;797  }798  .sp-title {799    font-size: 14px; font-weight: 500; color: var(--peach-text);800    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;801    line-height: 1.25;802  }803  .sp-identity-row {804    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;805  }806  .sp-identity-label {807    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;808    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;809  }810  .sp-username {811    font-size: 12px; color: var(--peach-text-dim);812    font-family: "IBM Plex Mono", monospace;813    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;814    margin-bottom: 0;815  }816  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }817  .sp-fill-btn {818    width: 100%; padding: 11px; border-radius: 9px; border: none;819    background: var(--peach-accent); color: #fff;820    font-size: 13px; font-weight: 500; cursor: pointer;821    font-family: Inter, sans-serif; letter-spacing: 0.01em;822    display: flex; align-items: center; justify-content: center; min-height: 38px;823    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;824  }825  .sp-fill-btn:hover {826    filter: brightness(1.1);827    box-shadow: 0 4px 20px var(--peach-glow, transparent);828    transform: translateY(-1px);829  }830  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }831  .sp-fill-btn.filled {832    background: #16a34a; transform: none; filter: none;833    box-shadow: 0 4px 16px rgba(22,163,74,0.35);834    cursor: default;835  }836  .sp-fill-btn:disabled { cursor: default; }837  .sp-actions-group {838    margin-top: 6px;839    display: flex; flex-direction: column; gap: 4px;840  }841  .sp-actions-label {842    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;843    color: var(--peach-text-muted);844    font-family: "IBM Plex Mono", monospace;845    text-align: center;846  }847  .sp-actions {848    display: flex; gap: 4px; justify-content: space-between; align-items: center;849  }850  .sp-action-btn {851    flex: 1; height: 28px; border: none; border-radius: 6px;852    background: transparent; color: var(--peach-text-dim);853    font-size: 12px; cursor: pointer;854    transition: background 120ms ease, color 120ms ease;855    font-family: Inter, sans-serif; letter-spacing: 0.04em;856    display: inline-flex; align-items: center; justify-content: center; gap: 4px;857    white-space: nowrap; overflow: hidden;858  }859  .sp-action-btn:hover:not(:disabled) {860    background: color-mix(in srgb, var(--peach-text) 5%, transparent);861    color: var(--peach-text);862  }863  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }864  .sp-action-btn.flashed {865    color: var(--peach-accent);866    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);867  }868869  /* TOTP tray — shown below the silver-platter secondary actions */870  .sp-tray {871    margin-top: 8px;872    padding: 10px 12px;873    border-radius: 9px;874    background: var(--peach-input-bg);875    border: 1px solid var(--peach-input-border);876    display: flex; align-items: center; gap: 12px;877    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;878  }879  .sp-tray-label {880    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;881    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;882    flex-shrink: 0;883  }884  .sp-totp-code {885    font-size: 18px; font-weight: 500;886    color: var(--peach-text);887    font-family: "IBM Plex Mono", monospace;888    letter-spacing: 0.12em;889    flex: 1;890    text-align: center;891  }892  .sp-totp-ring {893    width: 22px; height: 22px; flex-shrink: 0;894  }895  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }896  .sp-totp-ring .ring-fill {897    stroke: var(--peach-accent);898    transition: stroke-dashoffset 1s linear;899    transform: rotate(-90deg);900    transform-origin: center;901  }902  .sp-totp-copy {903    background: transparent; border: none; cursor: pointer;904    padding: 4px 8px; border-radius: 5px;905    color: var(--peach-text-dim); font-size: 11px;906    font-family: Inter, sans-serif;907    transition: background 120ms, color 120ms;908  }909  .sp-totp-copy:hover {910    background: color-mix(in srgb, var(--peach-text) 5%, transparent);911    color: var(--peach-text);912  }913914  /* Card silver platter (State 7) — reuses .sp-* primary action classes */915  .card-platter {916    padding: 12px 14px 10px;917    display: flex; flex-direction: column; gap: 4px;918  }919  .cp-network {920    font-size: 10px; font-weight: 600;921    color: var(--peach-accent);922    letter-spacing: 0.08em; text-transform: uppercase;923    font-family: Inter, sans-serif;924  }925  .cp-nickname {926    font-size: 14px; font-weight: 500; color: var(--peach-text);927    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;928    line-height: 1.2;929  }930  .cp-last4 {931    font-size: 12px; color: var(--peach-text-dim);932    font-family: "IBM Plex Mono", monospace;933    letter-spacing: 0.04em;934    margin-top: 2px;935  }936  .cp-meta {937    font-size: 11px; color: var(--peach-text-dim);938    font-family: "IBM Plex Mono", monospace;939    margin-top: 2px;940    display: flex; gap: 10px; align-items: center;941  }942  .cp-meta-sep { opacity: 0.5; }943  .cp-fill-wrap { margin-top: 10px; }944945  /* Locked state */946  .locked-wrap {947    display: flex; flex-direction: column; align-items: stretch;948    padding: 14px 13px 13px; gap: 9px;949  }950  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }951  .locked-icon {952    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;953    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);954    display: flex; align-items: center; justify-content: center;955  }956  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }957  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }958  .locked-input {959    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);960    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;961    font-size: 11px; font-family: "IBM Plex Mono", monospace;962    outline: none; transition: border-color 120ms, box-shadow 120ms;963  }964  .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); }965  .locked-input::placeholder { color: var(--peach-text-muted); }966  .locked-btn {967    width: 100%; padding: 8px; border-radius: 8px; border: none;968    background: var(--peach-accent); color: #fff; font-size: 12px;969    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;970    transition: background 120ms;971    letter-spacing: 0.01em;972    box-shadow: 0 2px 16px var(--peach-glow, transparent);973    animation: peach-pulse-glow 2.4s ease-in-out infinite;974  }975  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }976  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }977  .locked-error {978    font-size: 10px; color: rgba(220,80,60,0.85);979    font-family: "IBM Plex Mono", monospace;980  }981982  @keyframes peach-pulse-glow {983    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }984    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),985                            0 0 48px var(--peach-glow, transparent); }986  }987988  /* ── State 10: identity helper ─────────────────────────────── */989  .identity-list {990    max-height: 192px; overflow-y: auto; padding: 4px 0;991    scrollbar-width: none;992  }993  .identity-list::-webkit-scrollbar { display: none; }994  .peach-identity-row {995    display: flex; align-items: center; gap: 10px;996    padding: 9px 12px; cursor: pointer; border-radius: 8px;997    transition: background 100ms ease;998  }999  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1000  .peach-identity-value {1001    font-family: "IBM Plex Mono", monospace; font-size: 13px;1002    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1003  }1004  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1005  .identity-alt-row {1006    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1007    border-radius: 8px; transition: background 100ms ease;1008    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1009  }1010  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1011  .identity-escape-row {1012    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1013    border-radius: 8px; transition: background 100ms ease; outline: none;1014    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1015    margin-top: 2px;1016  }1017  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1018  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1019  .identity-alt-input-wrap.open { display: flex; }1020  .identity-alt-input {1021    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1022    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1023    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1024    outline: none; transition: border-color 120ms;1025  }1026  .identity-alt-input:focus {1027    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1028    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1029  }1030  .identity-alt-confirm {1031    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1032    background: var(--peach-accent); color: #fff; font-size: 12px;1033    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1034  }1035  /* ── Generator view (after identity picked) ────────────────── */1036  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1037  .gen-confirmed {1038    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1039    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1040    border-radius: 8px;1041  }1042  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1043  .gen-confirmed-val {1044    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1045    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1046  }1047  .gen-label {1048    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1049    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1050  }1051  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1052  .gen-pw-val {1053    flex: 1; padding: 8px 10px; border-radius: 7px;1054    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1055    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1056    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1057  }1058  .gen-regen-btn {1059    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1060    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1061    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1062    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1063  }1064  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1065  .gen-fill-btn {1066    padding: 10px; border-radius: 8px; border: none;1067    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1068    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1069    transition: filter 120ms ease, transform 80ms ease;1070  }1071  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1072  .gen-fill-btn:active { transform: translateY(0); }10731074  /* ── Smart password generator (parity with main UI compact mode) ─── */1075  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1076  .pwgen-display-row {1077    display: flex; align-items: center; gap: 6px;1078    padding: 8px 10px; border-radius: 7px;1079    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1080  }1081  .pwgen-output {1082    flex: 1; min-width: 0; width: 0;1083    font-family: "IBM Plex Mono", monospace; font-size: 12px;1084    color: var(--peach-text);1085    background: transparent; border: none; outline: none; padding: 0;1086  }1087  .pwgen-icon-btn {1088    flex-shrink: 0;1089    width: 26px; height: 26px;1090    display: inline-flex; align-items: center; justify-content: center;1091    background: transparent; border: 1px solid var(--peach-input-border);1092    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1093    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1094  }1095  .pwgen-icon-btn:hover {1096    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1097    color: var(--peach-accent);1098    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1099  }1100  .pwgen-icon-btn.is-copied {1101    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1102    color: var(--peach-accent);1103    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1104  }1105  .pwgen-controls-row {1106    display: flex; align-items: center; gap: 8px;1107    flex-wrap: wrap;1108  }1109  .pwgen-slider {1110    flex: 1; min-width: 110px;1111    accent-color: var(--peach-accent);1112    cursor: pointer; height: 2px; background: transparent;1113  }1114  .pwgen-len-num {1115    font-family: "IBM Plex Mono", monospace; font-size: 11px;1116    color: var(--peach-accent); min-width: 22px; text-align: right;1117  }1118  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1119  .pwgen-len-input {1120    font-family: "IBM Plex Mono", monospace; font-size: 11px;1121    color: var(--peach-accent); width: 28px; text-align: right;1122    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1123    outline: none; padding: 0; min-width: 22px;1124  }1125  @keyframes identity-suggest-in {1126    from { opacity: 0; transform: translateY(-4px); }1127    to   { opacity: 1; transform: none; }1128  }1129  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1130    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1131  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1132  .identity-collapse-btn {1133    margin-left: auto; background: transparent; border: none; cursor: pointer;1134    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1135    line-height: 0; border-radius: 3px;1136    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1137  }1138  .identity-collapse-btn:hover { color: var(--peach-text); }1139  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1140  .identity-rows { display: grid; grid-template-rows: 1fr;1141    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1142  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1143  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1144    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1145    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1146    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1147  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1148  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1149  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1150  .identity-filter-pill {1151    padding: 2px 7px; border-radius: 999px;1152    border: 1px solid var(--peach-input-border);1153    background: transparent; color: var(--peach-text-muted);1154    font-family: "IBM Plex Mono", monospace; font-size: 9px;1155    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1156  }1157  .identity-filter-pill.is-on {1158    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1159    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1160    color: var(--peach-accent);1161  }1162  .identity-suggest-row {1163    display: flex; align-items: center; gap: 5px;1164    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1165    background: transparent; cursor: pointer; text-align: left;1166    transition: background 80ms;1167  }1168  .identity-suggest-row:hover,1169  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1170  .identity-suggest-val {1171    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1172    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1173  }1174  .identity-suggest-type {1175    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1176    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1177  }1178  .identity-suggest-type--email {1179    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1180    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1181  }1182  .identity-suggest-type--username {1183    color: var(--peach-text-muted);1184    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1185  }1186  .identity-suggest-meta {1187    font-family: "IBM Plex Mono", monospace; font-size: 9px;1188    color: var(--peach-text-muted); flex-shrink: 0;1189  }1190  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1191  .pwgen-pill {1192    padding: 3px 8px; border-radius: 999px;1193    border: 1px solid var(--peach-input-border);1194    background: transparent; color: var(--peach-text-muted);1195    font-family: "IBM Plex Mono", monospace; font-size: 9px;1196    letter-spacing: 0.06em; cursor: pointer;1197    transition: all 130ms ease;1198  }1199  .pwgen-pill.is-on {1200    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1201    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1202    color: var(--peach-accent);1203  }1204  .pwgen-pill:not(.is-on):hover {1205    color: var(--peach-text-dim);1206    border-color: var(--peach-text-muted);1207  }1208  .pwgen-policy-hint {1209    font-size: 10px; color: var(--peach-text-muted);1210    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1211    line-height: 1.3;1212  }1213  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }12141215  /* ── Save offer (after password filled) ───────────────────── */1216  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1217  .save-offer-title {1218    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1219  }1220  .save-offer-row {1221    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1222    border-radius: 7px; background: var(--peach-input-bg);1223    border: 1px solid var(--peach-input-border);1224  }1225  .save-offer-lbl {1226    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1227    font-family: "IBM Plex Mono", monospace;1228  }1229  .save-offer-val {1230    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1231    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1232  }1233  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1234  .save-offer-save {1235    flex: 1; padding: 9px; border-radius: 8px; border: none;1236    background: var(--peach-accent); color: #fff; font-size: 13px;1237    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1238  }1239  .save-offer-save:hover { filter: brightness(1.08); }1240  .save-offer-skip {1241    flex: 1; padding: 9px; border-radius: 8px; border: none;1242    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1243    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1244    font-family: Inter, sans-serif; transition: background 100ms ease;1245  }1246  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1247`;12481249export function showAutofillSelector(1250  anchorEl: HTMLInputElement,1251  entries: SelectorEntry[],1252  onSelect: (id: string) => void,1253  options: SelectorOptions = {}1254): () => void {1255  const host = document.createElement("div");1256  // When anchorEl is inside a focus-trapping modal (aria-modal, role=dialog, <dialog>),1257  // the modal's JS focus trap fires when Peach's internal inputs gain focus (they are1258  // outside the modal in the DOM), immediately blurring them and closing the identity1259  // suggest list. Fix: detect the modal ancestor and append the host inside it so focus1260  // traps see Peach as within the modal. Use position:fixed so the popup positions1261  // correctly relative to the viewport — overflow and transforms on the modal cannot1262  // clip or misplace a fixed child.1263  const modalAncestor = anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]');1264  host.style.cssText = `position: ${modalAncestor ? "fixed" : "absolute"}; z-index: 2147483647;`;1265  host.style.setProperty("--peach-accent", accentHex);1266  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1267  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1268  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1269  const shadow = host.attachShadow({ mode: "closed" });12701271  const style = shadow.appendChild(document.createElement("style"));1272  style.textContent = SELECTOR_STYLES;12731274  const rect = anchorEl.getBoundingClientRect();1275  // Fixed positioning uses viewport-relative coords; absolute uses document-relative.1276  host.style.top = `${rect.bottom + (modalAncestor ? 0 : window.scrollY) + 5}px`;1277  host.style.left = `${rect.left + (modalAncestor ? 0 : window.scrollX)}px`;1278  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1279  // wide single-input fields (e.g. centered email input on signup pages).1280  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1281  // expand the host after the initial measurement.1282  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1283  host.style.width = `${popupWidth}px`;12841285  const container = shadow.appendChild(document.createElement("div"));1286  container.className = "peach-inline-popup";1287  container.setAttribute("data-theme", popupTheme);12881289  const searchableEntries = options.searchableEntries ?? [];1290  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12911292  let query = "";1293  let focusedIndex = -1;1294  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1295  let searchInput: HTMLInputElement | null = null;1296  // Tracks the silver-platter entry the user pivoted away from, so the1297  // search/list header can offer a one-click way back to it. null when the1298  // popup never showed a single-match platter (e.g. multi-match list view).1299  let silverPlatterOrigin: SelectorEntry | null = null;1300  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1301  // setInterval. Add to this list — don't fan out the dismiss function.1302  const cleanupHooks: Array<() => void> = [];13031304  // Smooth height transitions whenever content changes height.1305  // ResizeObserver fires on natural height changes; we freeze the old height,1306  // then animate to the new one so the surface never jumps.1307  {1308    let prevH = 0;1309    let blocked = false;1310    const heightRo = new ResizeObserver(([entry]) => {1311      if (blocked) return;1312      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1313      if (prevH > 0 && Math.abs(h - prevH) > 1) {1314        blocked = true;1315        container.style.height = `${prevH}px`;1316        requestAnimationFrame(() => requestAnimationFrame(() => {1317          container.style.height = `${h}px`;1318          prevH = h;1319          const onEnd = (e: TransitionEvent) => {1320            if (e.propertyName !== "height") return;1321            container.style.height = "";1322            blocked = false;1323            container.removeEventListener("transitionend", onEnd);1324          };1325          container.addEventListener("transitionend", onEnd);1326        }));1327      } else {1328        prevH = h;1329      }1330    });1331    heightRo.observe(container);1332    cleanupHooks.push(() => heightRo.disconnect());1333  }13341335  // Pre-capture the anchor field value for username prefill1336  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1337  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1338  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13391340  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1341    const seen = new Set<string>();1342    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1343  }13441345  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1346    const q = value.trim().toLowerCase();1347    const deduped = uniqueEntries(source);1348    if (!q) return deduped.slice(0, 8);1349    return deduped.filter(e =>1350      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1351    ).slice(0, 12);1352  }13531354  function activeEntries(): SelectorEntry[] {1355    // When user is typing a search, filter across all known entries (domain matches + vault)1356    if (query.trim()) {1357      const merged = uniqueEntries([...entries, ...searchableEntries]);1358      return filterEntries(merged, query);1359    }1360    // Default: show domain matches; fall back to vault search when no matches1361    if (entries.length > 0) return entries;1362    return filterEntries(searchableEntries, "").slice(0, 8);1363  }13641365  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1366    const icon = document.createElement("div");1367    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1368    if (isNew) {1369      icon.innerHTML = plusSvgStr();1370    } else {1371      // Use the generic key glyph for all entries in the page-injected selector.1372      // Avoids disclosing vault domains to any third party and avoids needing1373      // to expose the browser favicon API to page context via web_accessible_resources.1374      void url;1375      icon.innerHTML = keySvgStr();1376    }1377    return icon;1378  }13791380  function renderIdentityHelper() {1381    container.innerHTML = "";1382    const identities = options.savedIdentities ?? [];13831384    // Header: "NEW ACCOUNT" + domain name1385    const hdr = container.appendChild(document.createElement("div"));1386    hdr.className = "domain-header";1387    const eyebrow = hdr.appendChild(document.createElement("div"));1388    eyebrow.className = "domain-eyebrow";1389    eyebrow.textContent = "NEW ACCOUNT";1390    const domName = hdr.appendChild(document.createElement("div"));1391    domName.className = "domain-name";1392    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13931394    // Identity rows1395    const list = container.appendChild(document.createElement("div"));1396    list.className = "identity-list";1397    for (const id of identities) {1398      const row = list.appendChild(document.createElement("div"));1399      row.className = "peach-identity-row";1400      row.setAttribute("tabindex", "-1");1401      const val = row.appendChild(document.createElement("div"));1402      val.className = "peach-identity-value";1403      val.textContent = id.value;1404      const meta = row.appendChild(document.createElement("div"));1405      meta.className = "peach-identity-meta";1406      meta.textContent = `used ${id.useCount}×`;1407      row.addEventListener("click", () => {1408        options.onFillFields?.(id.value, "");1409        renderGenerator(id.value);1410      });1411    }14121413    // Divider before "Use a different email…"1414    if (identities.length > 0) {1415      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1416    }14171418    // "Use a different email…" expandable row1419    const altRow = container.appendChild(document.createElement("div"));1420    altRow.className = "identity-alt-row";1421    altRow.textContent = "+ Use a different email…";14221423    const altInputWrap = container.appendChild(document.createElement("div"));1424    altInputWrap.className = "identity-alt-input-wrap";1425    const altInput = altInputWrap.appendChild(document.createElement("input"));1426    altInput.className = "identity-alt-input";1427    altInput.type = "email";1428    altInput.placeholder = "[email protected]";1429    altInput.setAttribute("autocomplete", "off");1430    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1431    altConfirm.className = "identity-alt-confirm";1432    altConfirm.type = "button";1433    altConfirm.textContent = "✓";14341435    function fillCustomEmail() {1436      const v = altInput.value.trim();1437      if (!v) return;1438      options.onFillFields?.(v, "");1439      renderGenerator(v);1440    }14411442    altRow.addEventListener("click", () => {1443      altRow.style.display = "none";1444      altInputWrap.classList.add("open");1445      altInput.focus();1446    });1447    altConfirm.addEventListener("click", fillCustomEmail);1448    altInput.addEventListener("keydown", (e) => {1449      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1450    });14511452    // Escape hatch: user already has a vault entry for this site but it1453    // wasn't detected (different domain, old entry, etc.). Tapping this1454    // switches to the full searchable list so they can find and fill it;1455    // selecting an entry there will trigger the remember-site toast if1456    // the domain isn't already associated.1457    if ((options.searchableEntries?.length ?? 0) > 0) {1458      const escapeRow = container.appendChild(document.createElement("div"));1459      escapeRow.className = "identity-escape-row";1460      escapeRow.textContent = "I already have an account →";1461      escapeRow.setAttribute("tabindex", "0");1462      escapeRow.addEventListener("click", () => renderList());1463      escapeRow.addEventListener("keydown", (e) => {1464        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1465      });1466    }1467  }14681469  function renderGenerator(filledEmail: string) {1470    container.innerHTML = "";1471    const sitePolicy = detectPasswordPolicy();14721473    const wrap = container.appendChild(document.createElement("div"));1474    wrap.className = "gen-view";14751476    // Header: domain + NEW ACCOUNT1477    const hdrRow = wrap.appendChild(document.createElement("div"));1478    hdrRow.className = "domain-header";1479    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1480    eyebrow2.className = "domain-eyebrow";1481    eyebrow2.textContent = "NEW ACCOUNT";1482    const domName2 = hdrRow.appendChild(document.createElement("div"));1483    domName2.className = "domain-name";1484    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14851486    // Confirmed email row1487    const conf = wrap.appendChild(document.createElement("div"));1488    conf.className = "gen-confirmed";1489    const confCheck = conf.appendChild(document.createElement("span"));1490    confCheck.className = "gen-confirmed-check";1491    confCheck.textContent = "✓";1492    const confVal = conf.appendChild(document.createElement("div"));1493    confVal.className = "gen-confirmed-val";1494    confVal.textContent = filledEmail;14951496    const lbl = wrap.appendChild(document.createElement("div"));1497    lbl.className = "gen-label";1498    lbl.textContent = "Generate a password";14991500    let currentPw = "";1501    const smartGen = createSmartGenerator({1502      policy: sitePolicy,1503      onChange: (pw) => { currentPw = pw; },1504    });1505    wrap.appendChild(smartGen.root);15061507    const fillBtn = wrap.appendChild(document.createElement("button"));1508    fillBtn.className = "gen-fill-btn";1509    fillBtn.type = "button";1510    fillBtn.textContent = "Copy & fill";1511    fillBtn.addEventListener("click", () => {1512      if (!currentPw) return;1513      options.onFillFields?.("", currentPw);1514      renderSaveOffer(filledEmail, currentPw);1515    });1516  }15171518  function renderSaveOffer(filledEmail: string, filledPassword: string) {1519    container.innerHTML = "";1520    const domain = options.domain ?? location.hostname.replace(/^www\./, "");15211522    const wrap = container.appendChild(document.createElement("div"));1523    wrap.className = "save-offer";15241525    const title = wrap.appendChild(document.createElement("div"));1526    title.className = "save-offer-title";1527    title.textContent = "Save this login to Peach?";15281529    function detailRow(label: string, value: string) {1530      const row = wrap.appendChild(document.createElement("div"));1531      row.className = "save-offer-row";1532      const lbl = row.appendChild(document.createElement("div"));1533      lbl.className = "save-offer-lbl";1534      lbl.textContent = label;1535      const val = row.appendChild(document.createElement("div"));1536      val.className = "save-offer-val";1537      val.textContent = value;1538    }15391540    detailRow("site", domain);1541    detailRow("email", filledEmail);1542    detailRow("password", "••••••••••••••••");15431544    const btns = wrap.appendChild(document.createElement("div"));1545    btns.className = "save-offer-btns";15461547    const saveBtn = btns.appendChild(document.createElement("button"));1548    saveBtn.className = "save-offer-save";1549    saveBtn.type = "button";1550    saveBtn.textContent = "Save";1551    saveBtn.addEventListener("click", async () => {1552      saveBtn.disabled = true;1553      saveBtn.textContent = "Saving…";1554      try {1555        const res = await chrome.runtime.sendMessage({1556          type: "ADD_ENTRY",1557          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1558        });1559        if ((res as { ok?: boolean }).ok) {1560          showSuccess(sTitle);1561        } else {1562          saveBtn.disabled = false;1563          saveBtn.textContent = "Save";1564        }1565      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1566    });15671568    const skipBtn = btns.appendChild(document.createElement("button"));1569    skipBtn.className = "save-offer-skip";1570    skipBtn.type = "button";1571    skipBtn.textContent = "Not now";1572    skipBtn.addEventListener("click", () => { dismiss(true); });1573  }15741575  function renderList() {1576    container.innerHTML = "";1577    focusedIndex = -1;1578    searchInput = null;1579    currentMode = "list";15801581    const current = activeEntries();15821583    // Domain header (always show) — eyebrow + domain on the left,1584    // a "+" shortcut to the create form on the right so the user is never1585    // trapped in the search list when they want to make a new entry.1586    const domHdr = document.createElement("div");1587    domHdr.className = "domain-header";1588    const headText = document.createElement("div");1589    headText.className = "domain-header-text";1590    const eyebrow = document.createElement("div");1591    eyebrow.className = "domain-eyebrow";1592    eyebrow.textContent = options.isSignup1593      ? "Sign up as"1594      : entries.length > 0 ? "Saved for this site" : "No saved login";1595    const domName = document.createElement("div");1596    domName.className = "domain-name";1597    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1598    headText.append(eyebrow, domName);1599    domHdr.appendChild(headText);16001601    if (!options.isSignup) {1602      const actions = document.createElement("div");1603      actions.className = "domain-header-actions";16041605      // Back arrow takes the place of the silver-platter's search icon when1606      // the user has pivoted away from a single-match platter — gives them1607      // a one-click way back to the original recommendation.1608      if (silverPlatterOrigin) {1609        const backBtn = document.createElement("button");1610        backBtn.className = "domain-search-btn";1611        backBtn.type = "button";1612        backBtn.setAttribute("aria-label", "Back to suggested entry");1613        backBtn.title = "Back to suggested entry";1614        backBtn.innerHTML = backSvgStr();1615        backBtn.addEventListener("click", (e) => {1616          e.stopPropagation();1617          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);1618        });1619        actions.appendChild(backBtn);1620      }16211622      const addBtn = document.createElement("button");1623      addBtn.className = "domain-add-btn";1624      addBtn.type = "button";1625      addBtn.setAttribute("aria-label", "Create new entry");1626      addBtn.title = "Create new entry";1627      addBtn.textContent = "+";1628      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1629      actions.appendChild(addBtn);16301631      domHdr.appendChild(actions);1632    }16331634    container.appendChild(domHdr);16351636    // Search — always show so user can find entries beyond the domain matches1637    const sw = document.createElement("div"); sw.className = "search-wrap";1638    searchInput = document.createElement("input");1639    searchInput.className = "search";1640    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1641    searchInput.value = query;1642    searchInput.addEventListener("input", () => {1643      query = searchInput?.value ?? "";1644      renderList();1645      searchInput?.focus();1646      searchInput?.setSelectionRange(query.length, query.length);1647    });1648    sw.appendChild(searchInput);1649    container.appendChild(sw);16501651    // Results1652    const results = document.createElement("div");1653    results.className = "results";1654    container.appendChild(results);16551656    if (current.length === 0 && entries.length > 0) {1657      // Show a hint but don't render empty entries1658    }16591660    for (let i = 0; i < current.length; i++) {1661      const e = current[i]!;1662      const entryEl = document.createElement("div");1663      entryEl.className = "entry";1664      entryEl.dataset.id = e.id;1665      entryEl.dataset.index = String(i);1666      entryEl.setAttribute("tabindex", "-1");16671668      entryEl.appendChild(makeEntryIcon(e.url));16691670      const info = document.createElement("div"); info.className = "entry-info";1671      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1672      const subEl = document.createElement("div"); subEl.className = "entry-sub";1673      const domain = e.url ? getDomainFromUrl(e.url) : "";1674      subEl.textContent = domain || e.username || "";1675      info.append(titleEl, subEl);1676      entryEl.appendChild(info);16771678      if (e.hasTotp) {1679        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1680        entryEl.appendChild(badge);1681      }1682      if (e.hasPasskey) {1683        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1684        entryEl.appendChild(badge);1685      }16861687      entryEl.addEventListener("click", () => {1688        if (options.isSignup && options.onFillFields) {1689          // Signup mode: clicking a saved identity fills the username field1690          options.onFillFields(e.username ?? "", "");1691          dismiss();1692        } else {1693          onSelect(e.id);1694          dismiss();1695        }1696      });1697      results.appendChild(entryEl);1698    }16991700    // Divider before "New entry"1701    if (current.length > 0) {1702      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1703    }17041705    // "New entry" row — always present1706    const newEl = document.createElement("div");1707    newEl.className = "entry";1708    newEl.setAttribute("tabindex", "-1");1709    newEl.appendChild(makeEntryIcon(undefined, true));17101711    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1712    const newTitle = document.createElement("div");1713    newTitle.className = "entry-title is-new";1714    newTitle.textContent = `New entry for ${sTitle}`;1715    const newSub = document.createElement("div");1716    newSub.className = "entry-sub";1717    newSub.textContent = sOrigin;1718    newInfo.append(newTitle, newSub);1719    newEl.appendChild(newInfo);1720    newEl.addEventListener("click", showCreateForm);1721    results.appendChild(newEl);17221723    // Focus search if present1724    if (searchInput) {1725      requestAnimationFrame(() => {1726        searchInput?.focus();1727        // Seed query (from type-to-search or domain-search-btn) lands at the1728        // end so the next keystroke extends it, not overwrites.1729        searchInput?.setSelectionRange(query.length, query.length);1730      });1731    }1732  }17331734  function setFocused(idx: number) {1735    const all = container.querySelectorAll<HTMLElement>(".entry");1736    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1737    focusedIndex = idx;1738    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1739  }17401741  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1742    const typed = identities.filter(s => s.type === fieldType);1743    if (!typed.length) return;1744    let collapsed = false;1745    let suppressNextFocus = false;17461747    const list = g.appendChild(document.createElement("div"));1748    list.className = "identity-suggest-list";1749    list.style.display = "none";17501751    // Collapse toggle — sits alone now that filter pills are gone1752    const collapseRow = list.appendChild(document.createElement("div"));1753    collapseRow.className = "identity-filter-row";1754    collapseRow.style.justifyContent = "flex-end";1755    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1756    collapseBtn.type = "button";1757    collapseBtn.className = "identity-collapse-btn";1758    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>`;1759    collapseBtn.addEventListener("mousedown", (e) => {1760      e.preventDefault();1761      collapsed = !collapsed;1762      collapseBtn.classList.toggle("is-collapsed", collapsed);1763      rowsWrapper.classList.toggle("is-collapsed", collapsed);1764    });17651766    const rowsWrapper = list.appendChild(document.createElement("div"));1767    rowsWrapper.className = "identity-rows";1768    const rows = rowsWrapper.appendChild(document.createElement("div"));1769    rows.className = "identity-rows-inner";17701771    function pick(value: string) {1772      inp.value = value;1773      list.style.display = "none";1774      suppressNextFocus = true;1775      inp.focus();1776    }17771778    function render() {1779      const q = inp.value.toLowerCase();1780      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1781      rows.innerHTML = "";1782      if (!filtered.length) { list.style.display = "none"; return; }1783      for (const s of filtered) {1784        const row = rows.appendChild(document.createElement("button"));1785        row.type = "button"; row.className = "identity-suggest-row";1786        const val = row.appendChild(document.createElement("span"));1787        val.className = "identity-suggest-val"; val.textContent = s.value;1788        const meta = row.appendChild(document.createElement("span"));1789        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1790        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1791        row.addEventListener("keydown", (e) => {1792          if (e.key === "ArrowDown") {1793            e.preventDefault();1794            (row.nextElementSibling as HTMLElement | null)?.focus();1795          } else if (e.key === "ArrowUp") {1796            e.preventDefault();1797            const prev = row.previousElementSibling as HTMLElement | null;1798            if (prev) prev.focus();1799            else inp.focus();1800          } else if (e.key === "Enter" || e.key === " ") {1801            e.preventDefault();1802            pick(s.value);1803          } else if (e.key === "Escape") {1804            e.preventDefault();1805            list.style.display = "none";1806            suppressNextFocus = true;1807            inp.focus();1808          }1809        });1810        row.addEventListener("blur", (e) => {1811          const rt = (e as FocusEvent).relatedTarget as Node | null;1812          if (rt && (rt === inp || list.contains(rt))) return;1813          setTimeout(() => { list.style.display = "none"; }, 150);1814        });1815      }1816      list.style.display = "";1817    }18181819    inp.addEventListener("focus", () => {1820      if (suppressNextFocus) { suppressNextFocus = false; return; }1821      render();1822    });1823    inp.addEventListener("input", render);1824    inp.addEventListener("keydown", (e) => {1825      if (list.style.display === "none") return;1826      if (e.key === "ArrowDown" && !collapsed) {1827        e.preventDefault();1828        (rows.firstElementChild as HTMLElement | null)?.focus();1829      } else if (e.key === "Escape") {1830        e.preventDefault();1831        list.style.display = "none";1832      }1833    });1834    inp.addEventListener("blur", (e) => {1835      const rt = (e as FocusEvent).relatedTarget as Node | null;1836      if (rt && list.contains(rt)) return;1837      setTimeout(() => { list.style.display = "none"; }, 150);1838    });1839  }18401841  async function showCreateForm() {1842    currentMode = "create";1843    container.innerHTML = "";18441845    // Guard: the service worker may lock the vault between when the selector1846    // opens and when the user clicks "New entry". Show the inline unlock form1847    // instead of silently failing on save.1848    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1849    if (!statusRes?.unlocked) {1850      renderLocked();1851      return;1852    }18531854    // Detect page password policy once for this form — reused on every1855    // regenerate click so the user always gets a compliant password.1856    const sitePolicy = detectPasswordPolicy();18571858    // Fetch identities on-demand — they're passed in signup context but not1859    // in login/search context where the user still clicks "New entry".1860    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1861    if (!formIdentities.length) {1862      try {1863        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1864        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1865      } catch { /* silent fallback */ }1866    }18671868    const wrap = document.createElement("div");1869    wrap.className = "create-form-wrap";18701871    // Header1872    const head = document.createElement("div"); head.className = "create-head";1873    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1874    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>`;1875    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1876    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1877    head.append(backBtn, lbl);18781879    // Body1880    const body = document.createElement("div"); body.className = "create-body";18811882    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1883      const g = document.createElement("div"); g.className = "f-group";1884      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1885      const inp = document.createElement("input"); inp.className = "f-input";1886      g.append(l, inp); return { g, inp };1887    }18881889    // Title1890    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1891    body.appendChild(tg.g);18921893    // URL1894    const ug = fGroup("website");1895    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1896    if (loginSubdomain) {1897      const h = document.createElement("div"); h.className = "url-hint";1898      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1899    }1900    body.appendChild(ug.g);19011902    // Username — pre-fill from anchor if it doesn't look like an email1903    const xg = fGroup("username");1904    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1905    xg.inp.placeholder = "johndoe";1906    xg.inp.setAttribute("autocomplete", "off");1907    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1908    body.appendChild(xg.g);19091910    // Email — pre-fill from anchor if it looks like an email1911    const eg = fGroup("email");1912    (eg.inp as HTMLInputElement).type = "email";1913    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1914    eg.inp.placeholder = "[email protected]";1915    eg.inp.setAttribute("autocomplete", "off");1916    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1917    body.appendChild(eg.g);19181919    // Password — full smart generator with charset pills + length slider +1920    // policy hint. Mirrors the main UI's compact generator so users get the1921    // same controls inline as in the popup.1922    const pg = fGroup("password");1923    pg.inp.remove(); // smartGen provides its own display — no separate input needed1924    let currentPassword = prePassword || "";1925    const smartGen = createSmartGenerator({1926      policy: sitePolicy,1927      initialPassword: prePassword || undefined,1928      onChange: (pw) => { currentPassword = pw; },1929    });1930    pg.g.appendChild(smartGen.root);1931    body.appendChild(pg.g);19321933    // Save1934    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1935    saveBtn.textContent = "Save entry";1936    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1937    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1938    saveBtn.addEventListener("click", async () => {1939      const title = tg.inp.value.trim();1940      const pw = currentPassword.trim();1941      const username = xg.inp.value.trim();1942      const email = eg.inp.value.trim();1943      if (!title) {1944        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1945        showFormError("Entry needs a title");1946        return;1947      }1948      if (!pw) {1949        showFormError("Entry needs a password — tap regen to make one");1950        return;1951      }1952      errEl.style.display = "none";1953      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1954      try {1955        const res = await chrome.runtime.sendMessage({1956          type: "ADD_ENTRY",1957          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1958        });1959        if ((res as { ok?: boolean }).ok) {1960          // Fill the detected form. onFillFields uses whichever identity the1961          // page anchored on — the vault captures both username and email.1962          options.onFillFields?.(username || email, pw);1963          showSuccess(title);1964        } else {1965          const errMsg = (res as { error?: string }).error === "vault locked"1966            ? "Vault locked — open Peach to save"1967            : "Could not save entry";1968          showFormError(errMsg);1969          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1970        }1971      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1972    });1973    body.appendChild(saveBtn);1974    body.appendChild(errEl);19751976    wrap.append(head, body);1977    container.appendChild(wrap);1978    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1979  }19801981  function showSuccess(title: string) {1982    currentMode = "success";1983    container.innerHTML = "";1984    const wrap = document.createElement("div"); wrap.className = "success-wrap";1985    const ring = document.createElement("div"); ring.className = "success-ring";1986    ring.innerHTML = checkSvgStr();1987    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1988    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1989    wrap.append(ring, t, s);1990    container.appendChild(wrap);1991    setTimeout(() => dismiss(), 1600);1992  }19931994  function flashActionBtn(btn: HTMLButtonElement) {1995    btn.classList.add("flashed");1996    setTimeout(() => btn.classList.remove("flashed"), 700);1997  }19981999  // M3/QUA-005: when both the direct clipboard write and the background COPY2000  // fallback fail, briefly show the user that the copy did not happen.2001  function flashCopyError(btn: HTMLButtonElement) {2002    const original = btn.textContent ?? "";2003    btn.textContent = "Blocked";2004    btn.classList.add("flashed");2005    setTimeout(() => {2006      btn.classList.remove("flashed");2007      if (btn.isConnected) btn.textContent = original;2008    }, 1200);2009  }20102011  function renderSilverPlatter(entry: SelectorEntry) {2012    container.innerHTML = "";2013    searchInput = null;2014    focusedIndex = -1;2015    currentMode = "silver-platter";2016    silverPlatterOrigin = entry;20172018    const domHdr = document.createElement("div");2019    domHdr.className = "domain-header";2020    const headText = document.createElement("div");2021    headText.className = "domain-header-text";2022    const eyebrow = document.createElement("div");2023    eyebrow.className = "domain-eyebrow";2024    eyebrow.textContent = "Saved for this site";2025    const domName = document.createElement("div");2026    domName.className = "domain-name";2027    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2028    headText.append(eyebrow, domName);2029    domHdr.appendChild(headText);2030    if (!options.isSignup) {2031      const actions = document.createElement("div");2032      actions.className = "domain-header-actions";20332034      // Search shortcut — same idea as type-to-search below, but visible so2035      // the user can discover that another entry is reachable from a2036      // single-match platter. Sits to the left of the create button.2037      const searchBtn = document.createElement("button");2038      searchBtn.className = "domain-search-btn";2039      searchBtn.type = "button";2040      searchBtn.setAttribute("aria-label", "Search for a different entry");2041      searchBtn.title = "Search for a different entry";2042      searchBtn.innerHTML = searchSvgStr();2043      searchBtn.addEventListener("click", (e) => {2044        e.stopPropagation();2045        query = "";2046        renderList();2047      });2048      actions.appendChild(searchBtn);20492050      const addBtn = document.createElement("button");2051      addBtn.className = "domain-add-btn";2052      addBtn.type = "button";2053      addBtn.setAttribute("aria-label", "Create new entry");2054      addBtn.title = "Create new entry";2055      addBtn.textContent = "+";2056      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2057      actions.appendChild(addBtn);20582059      domHdr.appendChild(actions);2060    }2061    container.appendChild(domHdr);20622063    const platter = document.createElement("div");2064    platter.className = "silver-platter";20652066    const titleEl = document.createElement("div");2067    titleEl.className = "sp-title";2068    titleEl.textContent = entry.title;2069    platter.appendChild(titleEl);20702071    if (entry.email) {2072      const emailEl = document.createElement("div");2073      emailEl.className = "sp-identity-row";2074      const emailLbl = document.createElement("span");2075      emailLbl.className = "sp-identity-label";2076      emailLbl.textContent = "email";2077      const emailVal = document.createElement("span");2078      emailVal.className = "sp-username";2079      emailVal.textContent = entry.email;2080      emailEl.append(emailLbl, emailVal);2081      platter.appendChild(emailEl);2082    }20832084    if (entry.username) {2085      const userEl = document.createElement("div");2086      userEl.className = "sp-identity-row";2087      const userLbl = document.createElement("span");2088      userLbl.className = "sp-identity-label";2089      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2090      const userVal = document.createElement("span");2091      userVal.className = "sp-username";2092      userVal.textContent = entry.username;2093      userEl.append(userLbl, userVal);2094      platter.appendChild(userEl);2095    }20962097    const fillBtn = document.createElement("button");2098    fillBtn.className = "sp-fill-btn";2099    fillBtn.type = "button";2100    fillBtn.textContent = "Fill credentials";2101    fillBtn.addEventListener("click", () => {2102      if (fillBtn.disabled) return;2103      fillBtn.disabled = true;2104      fillBtn.classList.add("filled");2105      fillBtn.innerHTML = checkSvgStr();2106      // Fire the fill, then exit via the standard exit animation. The fill2107      // itself is async (handled in index.ts) — by 400ms the form is filled2108      // and the popup begins its exit. Total dwell from click to host2109      // removal: 400ms + 130ms (exit animation) = 530ms.2110      onSelect(entry.id);2111      setTimeout(() => dismiss(), 400);2112    });2113    platter.appendChild(fillBtn);21142115    const actionsGroup = document.createElement("div");2116    actionsGroup.className = "sp-actions-group";2117    const actionsLabel = document.createElement("div");2118    actionsLabel.className = "sp-actions-label";2119    actionsLabel.textContent = "Copy";2120    actionsGroup.appendChild(actionsLabel);21212122    const actions = document.createElement("div");2123    actions.className = "sp-actions";2124    actionsGroup.appendChild(actions);21252126    if (entry.email) {2127      const copyEmail = document.createElement("button");2128      copyEmail.className = "sp-action-btn";2129      copyEmail.type = "button";2130      copyEmail.title = "Copy email";2131      copyEmail.textContent = "Email";2132      copyEmail.addEventListener("click", async (e) => {2133        e.stopPropagation();2134        let alreadyWritten = false;2135        try {2136          await navigator.clipboard.writeText(entry.email!);2137          alreadyWritten = true;2138        } catch (err) {2139          console.warn("[Peach] clipboard write denied:", err);2140        }2141        const resp = await chrome.runtime.sendMessage({2142          type: "COPY",2143          payload: { text: entry.email, label: "Email", alreadyWritten },2144        }).catch(() => null) as { ok?: boolean } | null;2145        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2146        else flashCopyError(copyEmail);2147      });2148      actions.appendChild(copyEmail);2149    }21502151    const copyU = document.createElement("button");2152    copyU.className = "sp-action-btn";2153    copyU.type = "button";2154    const usernameIsEmail = entry.username?.includes("@") ?? false;2155    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2156    copyU.textContent = usernameIsEmail ? "Email" : "Username";2157    copyU.disabled = !entry.username;2158    copyU.addEventListener("click", async (e) => {2159      e.stopPropagation();2160      if (!entry.username) return;2161      let alreadyWritten = false;2162      try {2163        await navigator.clipboard.writeText(entry.username);2164        alreadyWritten = true;2165      } catch (err) {2166        console.warn("[Peach] clipboard write denied:", err);2167      }2168      const resp = await chrome.runtime.sendMessage({2169        type: "COPY",2170        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2171      }).catch(() => null) as { ok?: boolean } | null;2172      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2173      else flashCopyError(copyU);2174    });2175    actions.appendChild(copyU);21762177    const copyP = document.createElement("button");2178    copyP.className = "sp-action-btn";2179    copyP.type = "button";2180    copyP.title = "Copy password";2181    copyP.textContent = "Password";2182    copyP.addEventListener("click", async (e) => {2183      e.stopPropagation();2184      const resp = await chrome.runtime.sendMessage({2185        type: "GET_ENTRY_FOR_FILL",2186        payload: { id: entry.id },2187      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2188      if (!resp?.ok || !resp.data?.password) return;2189      let alreadyWritten = false;2190      try {2191        await navigator.clipboard.writeText(resp.data.password);2192        alreadyWritten = true;2193      } catch (err) {2194        console.warn("[Peach] clipboard write denied:", err);2195      }2196      const copyResp = await chrome.runtime.sendMessage({2197        type: "COPY",2198        payload: { text: resp.data.password, label: "Password", alreadyWritten },2199      }).catch(() => null) as { ok?: boolean } | null;2200      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2201      else flashCopyError(copyP);2202    });2203    actions.appendChild(copyP);22042205    let trayEl: HTMLDivElement | null = null;2206    let trayInterval: ReturnType<typeof setInterval> | null = null;22072208    function closeTray() {2209      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2210      trayEl?.remove();2211      trayEl = null;2212    }2213    // Register so dismiss() will close the tray and clear the interval2214    // even if the user dismisses without explicitly closing the tray.2215    cleanupHooks.push(closeTray);22162217    async function openTOTPTray() {2218      // Fetch the current TOTP code from the background. The raw base32 seed2219      // never enters the content script (SEV-3-C): we receive the live 6-digit2220      // code plus the seconds remaining, count down locally, and re-fetch a2221      // fresh code only when the 30s window rolls over.2222      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2223        const r = await chrome.runtime.sendMessage({2224          type: "GET_ENTRY_FOR_FILL",2225          payload: { id: entry.id },2226        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2227        if (!r?.ok || !r.data?.totpCode) return null;2228        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2229      }2230      let current = await fetchCode();2231      if (!current) return;22322233      trayEl = document.createElement("div");2234      trayEl.className = "sp-tray";22352236      const label = document.createElement("span");2237      label.className = "sp-tray-label";2238      label.textContent = "2FA";2239      trayEl.appendChild(label);22402241      const codeEl = document.createElement("div");2242      codeEl.className = "sp-totp-code";2243      trayEl.appendChild(codeEl);22442245      const ringNs = "http://www.w3.org/2000/svg";2246      const ring = document.createElementNS(ringNs, "svg");2247      ring.setAttribute("class", "sp-totp-ring");2248      ring.setAttribute("viewBox", "0 0 24 24");2249      const trackC = document.createElementNS(ringNs, "circle");2250      trackC.setAttribute("class", "ring-track");2251      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2252      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2253      const fillC = document.createElementNS(ringNs, "circle");2254      fillC.setAttribute("class", "ring-fill");2255      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2256      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2257      fillC.setAttribute("stroke-linecap", "round");2258      fillC.setAttribute("stroke-dasharray", "62.83");2259      ring.append(trackC, fillC);2260      trayEl.appendChild(ring);22612262      const copyBtn = document.createElement("button");2263      copyBtn.className = "sp-totp-copy";2264      copyBtn.type = "button";2265      copyBtn.textContent = "Copy";2266      trayEl.appendChild(copyBtn);22672268      function render() {2269        const { code, remaining } = current!;2270        // Group as "847 291" — easier to read than "847291"2271        codeEl.textContent = code.length === 62272          ? `${code.slice(0, 3)} ${code.slice(3)}`2273          : code;2274        // Ring fills counter-clockwise as time elapses: dashoffset goes from2275        // 0 (full ring) to 62.83 (empty) over the 30s window.2276        const fraction = (30 - remaining) / 30;2277        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2278      }2279      render();2280      trayInterval = setInterval(async () => {2281        if (!current) return;2282        current = { code: current.code, remaining: current.remaining - 1 };2283        // Window rolled over — pull a fresh code from the background.2284        if (current.remaining <= 0) {2285          const next = await fetchCode();2286          current = next ?? { code: current.code, remaining: 30 };2287        }2288        render();2289      }, 1000);22902291      copyBtn.addEventListener("click", async (e) => {2292        e.stopPropagation();2293        const code = current?.code;2294        if (!code) return;2295        let alreadyWritten = false;2296        try {2297          await navigator.clipboard.writeText(code);2298          alreadyWritten = true;2299        } catch (err) {2300          console.warn("[Peach] clipboard write denied:", err);2301        }2302        const resp = await chrome.runtime.sendMessage({2303          type: "COPY",2304          payload: { text: code, label: "TOTP", alreadyWritten },2305        }).catch(() => null) as { ok?: boolean } | null;2306        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2307        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2308      });23092310      platter.appendChild(trayEl);2311    }23122313    const editBtn = document.createElement("button");2314    editBtn.className = "sp-action-btn sp-action-edit";2315    editBtn.type = "button";2316    editBtn.title = "Edit entry";2317    editBtn.textContent = "Edit";2318    editBtn.addEventListener("click", (e) => {2319      e.stopPropagation();2320      closeTray();2321      void renderInlineEdit(entry);2322    });2323    actions.appendChild(editBtn);23242325    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2326    // "···" toggle was zero-savings (the toggle button took the same space2327    // the "2FA" label needed) and made the code one extra click away.2328    if (entry.hasTotp) void openTOTPTray();23292330    platter.appendChild(actionsGroup);2331    container.appendChild(platter);2332  }23332334  /**2335   * Inline-popup edit mode. Swaps the silver platter for an editable form2336   * over the same shadow-DOM surface so the user never leaves the page.2337   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2338   * with the new fields. Cancel returns without writing.2339   */2340  async function renderInlineEdit(summary: SelectorEntry) {2341    container.innerHTML = "";2342    const wrap = document.createElement("div");2343    wrap.className = "create-form-wrap";23442345    const head = document.createElement("div");2346    head.className = "create-head";2347    const back = document.createElement("button");2348    back.className = "back-btn";2349    back.type = "button";2350    back.title = "Cancel";2351    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>`;2352    back.addEventListener("click", () => renderSilverPlatter(summary));2353    head.appendChild(back);2354    const headLbl = document.createElement("div");2355    headLbl.className = "create-label";2356    headLbl.textContent = "Edit entry";2357    head.appendChild(headLbl);2358    wrap.appendChild(head);23592360    const body = document.createElement("div");2361    body.className = "create-body";23622363    // Loading shimmer while we fetch the full entry2364    const loading = document.createElement("div");2365    loading.className = "empty-hint";2366    loading.textContent = "loading…";2367    body.appendChild(loading);2368    wrap.appendChild(body);2369    container.appendChild(wrap);23702371    const [res, idRes] = await Promise.all([2372      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2373      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2374      chrome.runtime.sendMessage({2375        type: "GET_ENTRY_FOR_EDIT",2376        payload: { id: summary.id },2377      }).catch(() => null),2378      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2379    ]);2380    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2381    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];23822383    if (!entryRes || !entryRes.ok || !entryRes.data) {2384      loading.textContent = "couldn't load this entry. try again from the popup.";2385      return;2386    }2387    body.innerHTML = "";23882389    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2390      const group = document.createElement("div");2391      group.className = "f-group";2392      const lbl = document.createElement("div");2393      lbl.className = "f-label";2394      lbl.textContent = label;2395      const input = document.createElement("input");2396      input.className = "f-input";2397      input.type = type;2398      input.value = value;2399      input.autocomplete = "off";2400      group.append(lbl, input);2401      body.appendChild(group);2402      return { g: group, inp: input };2403    }24042405    const titleInput = field("title", entryRes.data.title ?? "").inp;2406    const urlInput = field("url", entryRes.data.url ?? "").inp;2407    urlInput.classList.add("url-f");2408    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2409    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2410    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2411    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2412    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");24132414    // Password row with reveal toggle + generator2415    const pwGroup = document.createElement("div");2416    pwGroup.className = "f-group";2417    const pwLbl = document.createElement("div");2418    pwLbl.className = "f-label";2419    pwLbl.textContent = "password";2420    const pwRow = document.createElement("div");2421    pwRow.className = "f-row";2422    const pwInput = document.createElement("input");2423    pwInput.className = "f-input";2424    pwInput.type = "password";2425    pwInput.value = entryRes.data.password ?? "";2426    pwInput.autocomplete = "new-password";2427    const revealBtn = document.createElement("button");2428    revealBtn.className = "gen-btn";2429    revealBtn.type = "button";2430    revealBtn.textContent = "show";2431    revealBtn.addEventListener("click", () => {2432      const reveal = pwInput.type === "password";2433      pwInput.type = reveal ? "text" : "password";2434      revealBtn.textContent = reveal ? "hide" : "show";2435    });2436    pwRow.append(pwInput, revealBtn);2437    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2438    editSmartGen.root.style.display = "none";2439    let editGenVisible = false;2440    const genToggleBtn = document.createElement("button");2441    genToggleBtn.className = "gen-toggle-link";2442    genToggleBtn.type = "button";2443    genToggleBtn.textContent = "⚙ generate";2444    genToggleBtn.addEventListener("click", () => {2445      editGenVisible = !editGenVisible;2446      pwRow.style.display = editGenVisible ? "none" : "";2447      editSmartGen.root.style.display = editGenVisible ? "" : "none";2448      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2449    });2450    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2451    body.appendChild(pwGroup);24522453    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;24542455    // Notes2456    const notesGroup = document.createElement("div");2457    notesGroup.className = "f-group";2458    const notesLbl = document.createElement("div");2459    notesLbl.className = "f-label";2460    notesLbl.textContent = "notes";2461    const notesInput = document.createElement("textarea");2462    notesInput.className = "f-input";2463    notesInput.rows = 3;2464    notesInput.value = entryRes.data.notes ?? "";2465    notesInput.style.fontFamily = "Inter, sans-serif";2466    notesInput.style.resize = "vertical";2467    notesGroup.append(notesLbl, notesInput);2468    body.appendChild(notesGroup);24692470    // Save / Cancel row2471    const actionsRow = document.createElement("div");2472    actionsRow.className = "f-row";2473    const saveBtn = document.createElement("button");2474    saveBtn.className = "save-btn";2475    saveBtn.type = "button";2476    saveBtn.textContent = "Save changes";2477    saveBtn.style.flex = "1";2478    const cancelBtn = document.createElement("button");2479    cancelBtn.className = "gen-btn";2480    cancelBtn.type = "button";2481    cancelBtn.textContent = "cancel";2482    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2483    actionsRow.append(saveBtn, cancelBtn);2484    body.appendChild(actionsRow);24852486    saveBtn.addEventListener("click", async () => {2487      saveBtn.disabled = true;2488      const originalLabel = saveBtn.textContent;2489      saveBtn.textContent = "Saving…";2490      const patch: Record<string, unknown> = {2491        title: titleInput.value.trim(),2492        url: urlInput.value.trim(),2493        username: usernameInput.value.trim(),2494        email: emailInput.value.trim() || undefined,2495        password: pwInput.value,2496        totp: totpInput.value.trim(),2497        notes: notesInput.value,2498      };2499      const updateRes = (await chrome.runtime.sendMessage({2500        type: "UPDATE_ENTRY",2501        payload: { id: summary.id, patch },2502      }).catch(() => null)) as { ok: boolean; error?: string } | null;2503      if (!updateRes?.ok) {2504        saveBtn.disabled = false;2505        saveBtn.textContent = originalLabel;2506        const err = document.createElement("div");2507        err.className = "empty-hint";2508        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2509        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2510        body.appendChild(err);2511        setTimeout(() => err.remove(), 3000);2512        return;2513      }2514      // Refresh the platter with updated summary fields2515      const refreshed: SelectorEntry = {2516        id: summary.id,2517        title: patch.title as string,2518        username: patch.username as string,2519        email: patch.email as string | undefined,2520        url: patch.url as string,2521        hasTotp: Boolean(patch.totp),2522        hasPasskey: summary.hasPasskey,2523      };2524      renderSilverPlatter(refreshed);2525    });25262527    queueMicrotask(() => titleInput.focus());2528  }25292530  function renderLocked() {2531    container.innerHTML = "";25322533    // Domain header (same as list view)2534    const domHdr = document.createElement("div");2535    domHdr.className = "domain-header";2536    const eyebrow = document.createElement("div");2537    eyebrow.className = "domain-eyebrow";2538    eyebrow.textContent = "vault locked";2539    const domName = document.createElement("div");2540    domName.className = "domain-name";2541    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2542    domHdr.append(eyebrow, domName);2543    container.appendChild(domHdr);25442545    const wrap = document.createElement("div");2546    wrap.className = "locked-wrap";25472548    // Icon + label row2549    const head = document.createElement("div"); head.className = "locked-head";2550    const icon = document.createElement("div"); icon.className = "locked-icon";2551    icon.innerHTML = keySvgStr();2552    const title = document.createElement("div"); title.className = "locked-title";2553    title.textContent = "unlock to autofill";2554    head.append(icon, title);25552556    // The master password is NEVER collected in page-hosted DOM. A malicious2557    // page can observe keystrokes on the shared DOM event stream (a capture-2558    // phase listener registered before Peach injects sees every key before any2559    // stopImmediatePropagation), which would leak the vault's root secret2560    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2561    // where keystrokes are isolated from the page. After the user unlocks2562    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2563    // automatically (see content/index.ts), so the flow resumes on its own.2564    const sub = document.createElement("div");2565    sub.className = "locked-sub";2566    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";25672568    const openBtn = document.createElement("button");2569    openBtn.className = "locked-btn";2570    openBtn.type = "button";2571    openBtn.textContent = "Open Peach to unlock";2572    openBtn.addEventListener("click", () => {2573      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2574      openBtn.textContent = "opening Peach…";2575      openBtn.disabled = true;2576      // openPopup() can't always open programmatically (browser/version/gesture2577      // limits); reset so the user can retry or click the toolbar icon.2578      setTimeout(() => {2579        if (openBtn.isConnected) {2580          openBtn.textContent = "Open Peach to unlock";2581          openBtn.disabled = false;2582        }2583      }, 2500);2584    });25852586    wrap.append(head, sub, openBtn);2587    container.appendChild(wrap);2588  }25892590  function handleKeyDown(e: KeyboardEvent) {2591    if (options.locked) {2592      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2593      return;2594    }2595    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2596      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2597      return;2598    }2599    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2600    const count = allEntryEls.length;2601    if (document.activeElement === searchInput) {2602      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2603      if (count === 0) return;2604      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2605    }2606    if (count === 0) return;2607    switch (e.key) {2608      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2609      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2610      case "Enter": {2611        if (focusedIndex >= 0) {2612          const el = allEntryEls[focusedIndex] as HTMLElement;2613          const id = el.dataset.id;2614          if (id) { onSelect(id); dismiss(); }2615          else if (el.classList.contains("is-new") || !id) {2616            // "New entry" row (last item, no data-id)2617            showCreateForm();2618          }2619        }2620        break;2621      }2622      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2623    }2624  }26252626  document.addEventListener("keydown", handleKeyDown);26272628  // Type-to-search from the silver platter. A printable single-character2629  // keystroke (no modifier) seeds the search query and switches into the2630  // list view, so the user can pivot to a different entry without first2631  // clicking the search icon. Capture phase so the anchor input does not2632  // receive the character before we hijack it.2633  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2634    if (currentMode !== "silver-platter") return;2635    if (e.ctrlKey || e.metaKey || e.altKey) return;2636    if (e.key.length !== 1) return;2637    e.preventDefault();2638    e.stopImmediatePropagation();2639    query = e.key;2640    renderList();2641  };2642  document.addEventListener("keydown", silverPlatterTypeHandler, true);2643  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));26442645  (modalAncestor ?? document.body).appendChild(host);26462647  function updatePosition() {2648    const r = anchorEl.getBoundingClientRect();2649    host.style.top = `${r.bottom + (modalAncestor ? 0 : window.scrollY) + 5}px`;2650    host.style.left = `${r.left + (modalAncestor ? 0 : window.scrollX)}px`;2651    host.style.width = `${popupWidth}px`;2652  }2653  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26542655  if (options.locked) {2656    renderLocked();2657  } else if (options.isSignup && options.savedIdentities) {2658    // State 10: identity helper — signup form detected, show derived2659    // identity list (emails then usernames) instead of vault entry list.2660    renderIdentityHelper();2661  } else if (entries.length === 1 && !options.isSignup) {2662    // Silver platter (State 1): single domain match → focused fill view.2663    // Multi-match goes through renderList instead.2664    renderSilverPlatter(entries[0]!);2665  } else {2666    renderList();2667  }26682669  let exitScheduled = false;2670  function dismiss(userAction = false) {2671    // Idempotent: dismiss() can be called from multiple paths (Escape,2672    // outside click, entry select, fill success, host page nav). The exit2673    // animation must only play once and host.remove() must run exactly once.2674    if (exitScheduled) return;2675    exitScheduled = true;2676    // Detach listeners synchronously so nothing can re-trigger during the2677    // 130ms exit window (a focusin firing here would race against the2678    // dismiss-lock work in Pass 2).2679    stopObserving();2680    document.removeEventListener("click", outsideClick, { capture: true });2681    document.removeEventListener("keydown", handleKeyDown);2682    for (const cleanup of cleanupHooks) {2683      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2684    }2685    if (userAction) options.onDismiss?.();2686    container.classList.add("is-exiting");2687    setTimeout(() => host.remove(), 130);2688  }26892690  function outsideClick(ev: MouseEvent) {2691    const path = ev.composedPath();2692    // Never dismiss when clicking the anchor field itself — that click is2693    // what triggered the selector to open, and the user may click the field2694    // again to re-focus it without intending to close the selector.2695    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2696  }2697  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2698  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);26992700  return dismiss;2701}27022703export function showTOTPSelector(2704  anchorEl: HTMLInputElement,2705  entries: SelectorEntry[],2706  onFill: (id: string) => void,2707  options: { domain?: string; onDismiss?: () => void } = {}2708): () => void {2709  const host = document.createElement("div");2710  host.style.cssText = "position: absolute; z-index: 2147483647;";2711  host.style.setProperty("--peach-accent", accentHex);2712  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2713  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2714  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2715  const shadow = host.attachShadow({ mode: "closed" });27162717  const style = shadow.appendChild(document.createElement("style"));2718  style.textContent = SELECTOR_STYLES;27192720  const rect = anchorEl.getBoundingClientRect();2721  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2722  host.style.left = `${rect.left + window.scrollX}px`;2723  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2724  host.style.width = `${popupWidth}px`;27252726  const container = shadow.appendChild(document.createElement("div"));2727  container.className = "peach-inline-popup";2728  container.setAttribute("data-theme", popupTheme);27292730  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2731  const current = entries.filter((entry) => entry.hasTotp);2732  let focusedIndex = current.length === 1 ? 0 : -1;27332734  function updatePosition() {2735    const r = anchorEl.getBoundingClientRect();2736    host.style.top = `${r.bottom + window.scrollY + 5}px`;2737    host.style.left = `${r.left + window.scrollX}px`;2738    host.style.width = `${popupWidth}px`;2739  }27402741  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27422743  function choose(entry: SelectorEntry) {2744    onFill(entry.id);2745    dismiss();2746  }27472748  function render() {2749    container.innerHTML = "";27502751    const domHdr = document.createElement("div");2752    domHdr.className = "domain-header";2753    const headText = document.createElement("div");2754    headText.className = "domain-header-text";2755    const eyebrow = document.createElement("div");2756    eyebrow.className = "domain-eyebrow";2757    eyebrow.textContent = "2FA code";2758    const domName = document.createElement("div");2759    domName.className = "domain-name";2760    domName.textContent = domain;2761    headText.append(eyebrow, domName);2762    domHdr.appendChild(headText);2763    container.appendChild(domHdr);27642765    if (current.length === 1) {2766      const entry = current[0]!;2767      const platter = document.createElement("div");2768      platter.className = "silver-platter";27692770      const title = document.createElement("div");2771      title.className = "sp-title";2772      title.textContent = entry.title;2773      platter.appendChild(title);27742775      const sub = document.createElement("div");2776      sub.className = "sp-username";2777      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2778      platter.appendChild(sub);27792780      const fill = document.createElement("button");2781      fill.className = "sp-fill-btn";2782      fill.type = "button";2783      fill.textContent = "Fill 2FA code";2784      fill.addEventListener("click", () => choose(entry));2785      platter.appendChild(fill);27862787      container.appendChild(platter);2788      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2789      return;2790    }27912792    const results = document.createElement("div");2793    results.className = "results";2794    container.appendChild(results);27952796    for (let i = 0; i < current.length; i++) {2797      const entry = current[i]!;2798      const row = document.createElement("div");2799      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2800      row.dataset.index = String(i);2801      row.setAttribute("tabindex", "-1");28022803      const icon = document.createElement("div");2804      icon.className = "entry-icon";2805      icon.innerHTML = keySvgStr();2806      row.appendChild(icon);2807      const info = document.createElement("div");2808      info.className = "entry-info";2809      const title = document.createElement("div");2810      title.className = "entry-title";2811      title.textContent = entry.title;2812      const sub = document.createElement("div");2813      sub.className = "entry-sub";2814      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2815      info.append(title, sub);2816      row.appendChild(info);28172818      const badge = document.createElement("span");2819      badge.className = "totp-badge";2820      badge.textContent = "Fill";2821      row.appendChild(badge);2822      row.addEventListener("click", () => choose(entry));2823      results.appendChild(row);2824    }2825  }28262827  function setFocused(index: number) {2828    focusedIndex = index;2829    container.querySelectorAll(".entry").forEach((el, i) => {2830      el.classList.toggle("focused", i === focusedIndex);2831      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2832    });2833  }28342835  function handleKeyDown(e: KeyboardEvent) {2836    if (e.key === "Escape" || e.key === "Tab") {2837      e.preventDefault();2838      dismiss(true);2839      return;2840    }2841    if (current.length === 0) return;2842    if (e.key === "Enter") {2843      e.preventDefault();2844      choose(current[Math.max(0, focusedIndex)]!);2845      return;2846    }2847    if (current.length === 1) return;2848    if (e.key === "ArrowDown") {2849      e.preventDefault();2850      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2851    } else if (e.key === "ArrowUp") {2852      e.preventDefault();2853      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2854    }2855  }28562857  let exitScheduled = false;2858  function dismiss(userAction = false) {2859    if (exitScheduled) return;2860    exitScheduled = true;2861    stopObserving();2862    document.removeEventListener("click", outsideClick, { capture: true });2863    document.removeEventListener("keydown", handleKeyDown);2864    if (userAction) options.onDismiss?.();2865    container.classList.add("is-exiting");2866    setTimeout(() => host.remove(), 130);2867  }28682869  function outsideClick(ev: MouseEvent) {2870    const path = ev.composedPath();2871    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2872  }28732874  document.addEventListener("keydown", handleKeyDown);2875  document.body.appendChild(host);2876  render();2877  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);28782879  return dismiss;2880}28812882export interface CardSelectorEntry {2883  id: string;2884  title: string;2885  cardholderName?: string;2886  last4?: string;2887  expMonth?: string;2888  expYear?: string;2889  network?: import("../shared/types").CardNetwork;2890}28912892interface CardSelectorOptions {2893  domain?: string;2894  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2895  onFill: (entry: import("../shared/types").VaultEntry) => void;2896  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2897  onDismiss?: () => void;2898}28992900/**2901 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2902 * passkey create or get. Renders as a fixed-position floating popup (no2903 * field anchor needed — passkeys don't require a focused input). Uses the2904 * same theme tokens and entrance animation as all other inline popup states.2905 */2906export function showPasskeyProGate(): void {2907  const domain = location.hostname.replace(/^www\./, "");29082909  const host = document.createElement("div");2910  host.setAttribute("data-peach-passkey-gate", "1");2911  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2912  const shadow = host.attachShadow({ mode: "closed" });29132914  const style = document.createElement("style");2915  style.textContent = `2916    :host { all: initial; }2917    .gate-wrap {2918      position: fixed;2919      top: 50%;2920      left: 50%;2921      transform: translate(-50%, -50%);2922      width: 280px;2923      pointer-events: auto;2924      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2925    }2926    @keyframes g-in {2927      from { opacity:0; transform: translate(-50%,-52%); }2928      to   { opacity:1; transform: translate(-50%,-50%); }2929    }2930    .gate-wrap.is-exiting {2931      animation: g-out 130ms ease-in forwards;2932    }2933    @keyframes g-out {2934      to { opacity:0; transform: translate(-50%,-52%); }2935    }2936    .gate {2937      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2938      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2939      border-radius: 12px;2940      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2941      padding: 16px;2942      font-family: Inter, sans-serif;2943    }2944    .gate-header {2945      display: flex;2946      align-items: center;2947      gap: 7px;2948      margin-bottom: 12px;2949      padding-bottom: 10px;2950      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2951    }2952    .gate-domain {2953      font-size: 12px;2954      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2955      font-family: "IBM Plex Mono", monospace;2956      overflow: hidden;2957      text-overflow: ellipsis;2958      white-space: nowrap;2959    }2960    .gate-title {2961      font-size: 14px;2962      font-weight: 500;2963      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2964      margin-bottom: 6px;2965    }2966    .gate-subtitle {2967      font-size: 12px;2968      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2969      line-height: 1.5;2970      margin-bottom: 14px;2971    }2972    .gate-btn {2973      display: block;2974      width: 100%;2975      padding: 9px 0;2976      border-radius: 8px;2977      border: none;2978      cursor: pointer;2979      font-size: 13px;2980      font-family: Inter, sans-serif;2981      font-weight: 500;2982      transition: opacity 100ms;2983      margin-bottom: 7px;2984      text-align: center;2985    }2986    .gate-btn:last-child { margin-bottom: 0; }2987    .gate-btn--accent {2988      background: ${accentHex};2989      color: #fff;2990    }2991    .gate-btn--accent:hover { opacity: 0.88; }2992    .gate-btn--ghost {2993      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2994      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2995    }2996    .gate-btn--ghost:hover { opacity: 0.75; }2997    .backdrop {2998      position: fixed;2999      inset: 0;3000      pointer-events: auto;3001    }3002  `;3003  shadow.appendChild(style);30043005  const backdrop = document.createElement("div");3006  backdrop.className = "backdrop";3007  shadow.appendChild(backdrop);30083009  const wrap = document.createElement("div");3010  wrap.className = "gate-wrap";3011  shadow.appendChild(wrap);30123013  const gate = document.createElement("div");3014  gate.className = "gate";3015  wrap.appendChild(gate);30163017  // Header: peach icon + domain3018  const header = document.createElement("div");3019  header.className = "gate-header";3020  const icon = document.createElement("span");3021  icon.innerHTML = peachIconSvg();3022  const domainEl = document.createElement("span");3023  domainEl.className = "gate-domain";3024  domainEl.textContent = domain;3025  header.append(icon, domainEl);3026  gate.appendChild(header);30273028  const title = document.createElement("div");3029  title.className = "gate-title";3030  title.textContent = "Passkeys are part of Peach Pro.";3031  gate.appendChild(title);30323033  const subtitle = document.createElement("div");3034  subtitle.className = "gate-subtitle";3035  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3036  gate.appendChild(subtitle);30373038  const upgradeBtn = document.createElement("button");3039  upgradeBtn.className = "gate-btn gate-btn--accent";3040  upgradeBtn.type = "button";3041  upgradeBtn.textContent = "Upgrade to Pro";3042  gate.appendChild(upgradeBtn);30433044  const laterBtn = document.createElement("button");3045  laterBtn.className = "gate-btn gate-btn--ghost";3046  laterBtn.type = "button";3047  laterBtn.textContent = "Not right now";3048  gate.appendChild(laterBtn);30493050  function dismiss() {3051    wrap.classList.add("is-exiting");3052    setTimeout(() => host.remove(), 130);3053  }30543055  upgradeBtn.addEventListener("click", () => {3056    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3057    dismiss();3058  });3059  laterBtn.addEventListener("click", dismiss);3060  backdrop.addEventListener("click", dismiss);30613062  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3063    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3064  });30653066  document.body.appendChild(host);3067}30683069/**3070 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3071 * detector sees the page invoke navigator.credentials.create(); content/index.ts3072 * checks vault + decline state then calls this. "Save passkey to Peach"3073 * initiates the popup-context credential flow; "Not now" records a 30-day3074 * decline for the domain so we don't re-show on every page reload.3075 */3076export function showPasskeyRegistrationOffer(args: {3077  rpId: string;3078  rpName?: string;3079  userName?: string;3080  userDisplayName?: string;3081}): void {3082  const domain = location.hostname.replace(/^www\./, "");3083  const displayName = args.rpName || domain;30843085  const host = document.createElement("div");3086  host.setAttribute("data-peach-passkey-offer", "1");3087  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3088  const shadow = host.attachShadow({ mode: "closed" });30893090  const style = document.createElement("style");3091  style.textContent = `3092    :host { all: initial; }3093    .offer-wrap {3094      position: fixed;3095      top: 16px;3096      right: 16px;3097      width: 320px;3098      pointer-events: auto;3099      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3100    }3101    @keyframes o-in {3102      from { opacity: 0; transform: translateY(-6px); }3103      to   { opacity: 1; transform: translateY(0); }3104    }3105    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3106    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3107    .offer {3108      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3109      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3110      border-radius: 12px;3111      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3112      padding: 14px 14px 12px;3113      font-family: Inter, sans-serif;3114      position: relative;3115    }3116    .offer-close {3117      position: absolute;3118      top: 8px;3119      right: 8px;3120      width: 18px;3121      height: 18px;3122      border: none;3123      background: transparent;3124      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3125      cursor: pointer;3126      font-size: 14px;3127      line-height: 1;3128      padding: 0;3129    }3130    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3131    .offer-header {3132      display: flex;3133      align-items: center;3134      gap: 7px;3135      margin-bottom: 8px;3136      padding-bottom: 8px;3137      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3138    }3139    .offer-domain {3140      font-size: 12px;3141      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3142      font-family: "IBM Plex Mono", monospace;3143      overflow: hidden;3144      text-overflow: ellipsis;3145      white-space: nowrap;3146    }3147    .offer-title {3148      font-size: 13px;3149      font-weight: 500;3150      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3151      margin-bottom: 4px;3152    }3153    .offer-subtitle {3154      font-size: 11px;3155      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3156      line-height: 1.45;3157      margin-bottom: 12px;3158    }3159    .offer-btn {3160      display: block;3161      width: 100%;3162      padding: 8px 0;3163      border-radius: 7px;3164      border: none;3165      cursor: pointer;3166      font-size: 12px;3167      font-family: Inter, sans-serif;3168      font-weight: 500;3169      transition: opacity 100ms;3170      margin-bottom: 6px;3171      text-align: center;3172    }3173    .offer-btn:last-child { margin-bottom: 0; }3174    .offer-btn--accent { background: ${accentHex}; color: #fff; }3175    .offer-btn--accent:hover { opacity: 0.88; }3176    .offer-btn--ghost {3177      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3178      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3179    }3180    .offer-btn--ghost:hover { opacity: 0.75; }3181  `;3182  shadow.appendChild(style);31833184  const wrap = document.createElement("div");3185  wrap.className = "offer-wrap";3186  shadow.appendChild(wrap);31873188  const offer = document.createElement("div");3189  offer.className = "offer";3190  wrap.appendChild(offer);31913192  const closeBtn = document.createElement("button");3193  closeBtn.className = "offer-close";3194  closeBtn.type = "button";3195  closeBtn.setAttribute("aria-label", "Dismiss");3196  closeBtn.textContent = "✕";3197  offer.appendChild(closeBtn);31983199  const header = document.createElement("div");3200  header.className = "offer-header";3201  const icon = document.createElement("span");3202  icon.innerHTML = peachIconSvg();3203  const domainEl = document.createElement("span");3204  domainEl.className = "offer-domain";3205  domainEl.textContent = domain;3206  header.append(icon, domainEl);3207  offer.appendChild(header);32083209  const title = document.createElement("div");3210  title.className = "offer-title";3211  title.textContent = "This site supports passkeys.";3212  offer.appendChild(title);32133214  const subtitle = document.createElement("div");3215  subtitle.className = "offer-subtitle";3216  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3217  offer.appendChild(subtitle);32183219  const saveBtn = document.createElement("button");3220  saveBtn.className = "offer-btn offer-btn--accent";3221  saveBtn.type = "button";3222  saveBtn.textContent = "Save passkey to Peach";3223  offer.appendChild(saveBtn);32243225  const laterBtn = document.createElement("button");3226  laterBtn.className = "offer-btn offer-btn--ghost";3227  laterBtn.type = "button";3228  laterBtn.textContent = "Not now";3229  offer.appendChild(laterBtn);32303231  function dismiss(decline: boolean) {3232    if (decline) {3233      chrome.runtime.sendMessage({3234        type: "PASSKEY_OFFER_DECLINE",3235        payload: { domain },3236      }).catch(() => {});3237    }3238    wrap.classList.add("is-exiting");3239    setTimeout(() => host.remove(), 130);3240  }32413242  saveBtn.addEventListener("click", () => {3243    chrome.runtime.sendMessage({3244      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3245      payload: {3246        rpId: args.rpId,3247        rpName: args.rpName ?? displayName,3248        userName: args.userName ?? "user",3249        userDisplayName: args.userDisplayName,3250      },3251    }).catch(() => {});3252    dismiss(false);3253  });3254  laterBtn.addEventListener("click", () => dismiss(true));3255  closeBtn.addEventListener("click", () => dismiss(true));32563257  document.body.appendChild(host);3258}32593260/**3261 * State 11 — passkey available indicator. Shown when the user lands on a3262 * domain for which they already have a stored passkey. Tells them where to3263 * find it (the entry already shows in the vault list); the "Sign in with3264 * passkey" button opens the popup so they can use the platform authenticator3265 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3266 * the actual sign-in transparently, so this banner is informational only.3267 */3268export function showPasskeyAvailable(args: {3269  rpId: string;3270  userName: string;3271  fromBrowser?: "chrome" | "firefox";3272  currentBrowser?: "chrome" | "firefox" | "unknown";3273}): void {3274  const domain = location.hostname.replace(/^www\./, "");3275  const crossBrowser =3276    args.fromBrowser &&3277    args.currentBrowser &&3278    args.currentBrowser !== "unknown" &&3279    args.fromBrowser !== args.currentBrowser;32803281  const host = document.createElement("div");3282  host.setAttribute("data-peach-passkey-available", "1");3283  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3284  const shadow = host.attachShadow({ mode: "closed" });32853286  const style = document.createElement("style");3287  style.textContent = `3288    :host { all: initial; }3289    .avail-wrap {3290      position: fixed;3291      top: 16px;3292      right: 16px;3293      width: 320px;3294      pointer-events: auto;3295      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3296    }3297    @keyframes a-in {3298      from { opacity: 0; transform: translateY(-6px); }3299      to   { opacity: 1; transform: translateY(0); }3300    }3301    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3302    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3303    .avail {3304      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3305      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3306      border-radius: 12px;3307      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3308      padding: 14px 14px 12px;3309      font-family: Inter, sans-serif;3310      position: relative;3311    }3312    .avail-close {3313      position: absolute;3314      top: 8px;3315      right: 8px;3316      width: 18px;3317      height: 18px;3318      border: none;3319      background: transparent;3320      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3321      cursor: pointer;3322      font-size: 14px;3323      line-height: 1;3324      padding: 0;3325    }3326    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3327    .avail-header {3328      display: flex;3329      align-items: center;3330      gap: 7px;3331      margin-bottom: 8px;3332      padding-bottom: 8px;3333      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3334    }3335    .avail-domain {3336      font-size: 12px;3337      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3338      font-family: "IBM Plex Mono", monospace;3339    }3340    .avail-label {3341      font-size: 9px;3342      letter-spacing: 0.16em;3343      text-transform: uppercase;3344      color: ${accentHex};3345      margin-bottom: 4px;3346    }3347    .avail-user {3348      font-size: 13px;3349      font-weight: 500;3350      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3351      margin-bottom: 12px;3352      overflow: hidden;3353      text-overflow: ellipsis;3354      white-space: nowrap;3355    }3356    .avail-cross {3357      font-size: 11px;3358      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3359      line-height: 1.45;3360      margin-bottom: 12px;3361      padding: 8px;3362      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3363      border-radius: 6px;3364    }3365    .avail-btn {3366      display: block;3367      width: 100%;3368      padding: 8px 0;3369      border-radius: 7px;3370      border: none;3371      cursor: pointer;3372      font-size: 12px;3373      font-family: Inter, sans-serif;3374      font-weight: 500;3375      transition: opacity 100ms;3376      margin-bottom: 6px;3377      text-align: center;3378    }3379    .avail-btn:last-child { margin-bottom: 0; }3380    .avail-btn--accent { background: ${accentHex}; color: #fff; }3381    .avail-btn--accent:hover { opacity: 0.88; }3382    .avail-btn--ghost {3383      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3384      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3385    }3386    .avail-btn--ghost:hover { opacity: 0.75; }3387  `;3388  shadow.appendChild(style);33893390  const wrap = document.createElement("div");3391  wrap.className = "avail-wrap";3392  shadow.appendChild(wrap);33933394  const avail = document.createElement("div");3395  avail.className = "avail";3396  wrap.appendChild(avail);33973398  const closeBtn = document.createElement("button");3399  closeBtn.className = "avail-close";3400  closeBtn.type = "button";3401  closeBtn.setAttribute("aria-label", "Dismiss");3402  closeBtn.textContent = "✕";3403  avail.appendChild(closeBtn);34043405  const header = document.createElement("div");3406  header.className = "avail-header";3407  const icon = document.createElement("span");3408  icon.innerHTML = peachIconSvg();3409  const domainEl = document.createElement("span");3410  domainEl.className = "avail-domain";3411  domainEl.textContent = domain;3412  header.append(icon, domainEl);3413  avail.appendChild(header);34143415  const label = document.createElement("div");3416  label.className = "avail-label";3417  label.textContent = "PASSKEY";3418  avail.appendChild(label);34193420  const user = document.createElement("div");3421  user.className = "avail-user";3422  user.textContent = args.userName;3423  avail.appendChild(user);34243425  if (crossBrowser) {3426    const cross = document.createElement("div");3427    cross.className = "avail-cross";3428    cross.textContent =3429      args.fromBrowser === "chrome"3430        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3431        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3432    avail.appendChild(cross);3433  }34343435  const signInBtn = document.createElement("button");3436  signInBtn.className = "avail-btn avail-btn--accent";3437  signInBtn.type = "button";3438  signInBtn.textContent = "Sign in with passkey";3439  avail.appendChild(signInBtn);34403441  const passwordBtn = document.createElement("button");3442  passwordBtn.className = "avail-btn avail-btn--ghost";3443  passwordBtn.type = "button";3444  passwordBtn.textContent = "Use password instead";3445  avail.appendChild(passwordBtn);34463447  function dismiss() {3448    wrap.classList.add("is-exiting");3449    setTimeout(() => host.remove(), 130);3450  }34513452  signInBtn.addEventListener("click", () => {3453    // On Chrome: the user clicking the page's own Sign-in button is what3454    //   triggers webAuthenticationProxy → existing background flow handles it.3455    //   Our button just dismisses since the page itself drives auth.3456    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3457    //   and surface the entry for manual reference (popup view).3458    dismiss();3459    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3460  });3461  passwordBtn.addEventListener("click", dismiss);3462  closeBtn.addEventListener("click", dismiss);34633464  document.body.appendChild(host);3465}34663467/**3468 * State 7 — card silver platter. Single-card focused fill view rendered3469 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3470 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3471 * so card and login flows render identically. Multi-card list view is a3472 * follow-up; today this picks the first card.3473 */3474export function showCardSelector(3475  anchorEl: HTMLInputElement,3476  cards: CardSelectorEntry[],3477  options: CardSelectorOptions3478): () => void {3479  if (cards.length === 0) return () => {};3480  const card = cards[0]!;34813482  const host = document.createElement("div");3483  host.style.cssText = "position: absolute; z-index: 2147483647;";3484  host.style.setProperty("--peach-accent", accentHex);3485  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3486  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3487  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3488  const shadow = host.attachShadow({ mode: "closed" });34893490  const style = shadow.appendChild(document.createElement("style"));3491  style.textContent = SELECTOR_STYLES;34923493  const rect = anchorEl.getBoundingClientRect();3494  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3495  host.style.left = `${rect.left + window.scrollX}px`;3496  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;34973498  const container = shadow.appendChild(document.createElement("div"));3499  container.className = "peach-inline-popup";3500  container.setAttribute("data-theme", popupTheme);35013502  // Domain header — eyebrow communicates the card context, not the site3503  const domHdr = document.createElement("div");3504  domHdr.className = "domain-header";3505  const eyebrow = document.createElement("div");3506  eyebrow.className = "domain-eyebrow";3507  eyebrow.textContent = "Pay with Peach";3508  const domName = document.createElement("div");3509  domName.className = "domain-name";3510  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3511  domHdr.append(eyebrow, domName);3512  container.appendChild(domHdr);35133514  const platter = document.createElement("div");3515  platter.className = "card-platter";35163517  if (card.network && card.network !== "unknown") {3518    const net = document.createElement("div");3519    net.className = "cp-network";3520    net.textContent = card.network;3521    platter.appendChild(net);3522  }35233524  const nick = document.createElement("div");3525  nick.className = "cp-nickname";3526  nick.textContent = card.title;3527  platter.appendChild(nick);35283529  if (card.last4) {3530    const l4 = document.createElement("div");3531    l4.className = "cp-last4";3532    l4.textContent = `•••• ${card.last4}`;3533    platter.appendChild(l4);3534  }35353536  const meta = document.createElement("div");3537  meta.className = "cp-meta";3538  if (card.cardholderName) {3539    const name = document.createElement("span");3540    name.textContent = card.cardholderName;3541    meta.appendChild(name);3542  }3543  if (card.expMonth && card.expYear) {3544    if (card.cardholderName) {3545      const sep = document.createElement("span");3546      sep.className = "cp-meta-sep";3547      sep.textContent = "·";3548      meta.appendChild(sep);3549    }3550    const exp = document.createElement("span");3551    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3552    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3553    meta.appendChild(exp);3554  }3555  if (meta.childElementCount > 0) platter.appendChild(meta);35563557  const fillWrap = document.createElement("div");3558  fillWrap.className = "cp-fill-wrap";3559  const fillBtn = document.createElement("button");3560  fillBtn.className = "sp-fill-btn";3561  fillBtn.type = "button";3562  fillBtn.textContent = "Fill card details";3563  fillBtn.addEventListener("click", async () => {3564    if (fillBtn.disabled) return;3565    fillBtn.disabled = true;3566    fillBtn.classList.add("filled");3567    fillBtn.innerHTML = checkSvgStr();3568    const resp = await chrome.runtime.sendMessage({3569      type: "GET_ENTRY_FOR_FILL",3570      payload: { id: card.id },3571    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3572    if (resp?.ok && resp.data) options.onFill(resp.data);3573    setTimeout(() => dismiss(), 400);3574  });3575  fillWrap.appendChild(fillBtn);3576  platter.appendChild(fillWrap);35773578  // Secondary actions — copy number, copy CVC, dismiss3579  const actions = document.createElement("div");3580  actions.className = "sp-actions";35813582  function flashBtn(b: HTMLButtonElement) {3583    b.classList.add("flashed");3584    setTimeout(() => b.classList.remove("flashed"), 700);3585  }35863587  // M3/QUA-005: clipboard + background COPY both failed — show user.3588  function flashCopyError(b: HTMLButtonElement) {3589    const original = b.textContent ?? "";3590    b.textContent = "Blocked";3591    b.classList.add("flashed");3592    setTimeout(() => {3593      b.classList.remove("flashed");3594      if (b.isConnected) b.textContent = original;3595    }, 1200);3596  }35973598  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3599    const resp = await chrome.runtime.sendMessage({3600      type: "GET_ENTRY_FOR_FILL",3601      payload: { id: card.id },3602    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3603    return resp?.ok && resp.data ? resp.data : null;3604  }36053606  const copyNum = document.createElement("button");3607  copyNum.className = "sp-action-btn";3608  copyNum.type = "button";3609  copyNum.title = "Copy card number";3610  copyNum.textContent = "Copy number";3611  copyNum.addEventListener("click", async (e) => {3612    e.stopPropagation();3613    const full = await fetchFullCard();3614    if (!full?.cardNumber) return;3615    let alreadyWritten = false;3616    try {3617      await navigator.clipboard.writeText(full.cardNumber);3618      alreadyWritten = true;3619    } catch (err) {3620      console.warn("[Peach] clipboard write denied:", err);3621    }3622    const resp = await chrome.runtime.sendMessage({3623      type: "COPY",3624      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3625    }).catch(() => null) as { ok?: boolean } | null;3626    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3627    else flashCopyError(copyNum);3628  });3629  actions.appendChild(copyNum);36303631  const copyCvc = document.createElement("button");3632  copyCvc.className = "sp-action-btn";3633  copyCvc.type = "button";3634  copyCvc.title = "Copy CVC";3635  copyCvc.textContent = "Copy CVC";3636  copyCvc.addEventListener("click", async (e) => {3637    e.stopPropagation();3638    const full = await fetchFullCard();3639    if (!full?.cvc) return;3640    let alreadyWritten = false;3641    try {3642      await navigator.clipboard.writeText(full.cvc);3643      alreadyWritten = true;3644    } catch (err) {3645      console.warn("[Peach] clipboard write denied:", err);3646    }3647    const resp = await chrome.runtime.sendMessage({3648      type: "COPY",3649      payload: { text: full.cvc, label: "CVC", alreadyWritten },3650    }).catch(() => null) as { ok?: boolean } | null;3651    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3652    else flashCopyError(copyCvc);3653  });3654  actions.appendChild(copyCvc);36553656  const closeBtn = document.createElement("button");3657  closeBtn.className = "sp-action-btn";3658  closeBtn.type = "button";3659  closeBtn.title = "Dismiss";3660  closeBtn.textContent = "✕";3661  closeBtn.addEventListener("click", (e) => {3662    e.stopPropagation();3663    dismiss(true);3664  });3665  actions.appendChild(closeBtn);36663667  platter.appendChild(actions);3668  container.appendChild(platter);36693670  document.body.appendChild(host);3671  function updatePosition() {3672    const r = anchorEl.getBoundingClientRect();3673    host.style.top = `${r.bottom + window.scrollY + 5}px`;3674    host.style.left = `${r.left + window.scrollX}px`;3675  }3676  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);36773678  function onKeyDown(e: KeyboardEvent) {3679    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3680  }3681  document.addEventListener("keydown", onKeyDown);36823683  let exitScheduled = false;3684  function dismiss(userAction = false) {3685    if (exitScheduled) return;3686    exitScheduled = true;3687    stopObserving();3688    document.removeEventListener("click", outsideClick, { capture: true });3689    document.removeEventListener("keydown", onKeyDown);3690    if (userAction) options.onDismiss?.();3691    container.classList.add("is-exiting");3692    setTimeout(() => host.remove(), 130);3693  }36943695  function outsideClick(ev: MouseEvent) {3696    const path = ev.composedPath();3697    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3698  }3699  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);37003701  return dismiss;3702}