inject.ts

147.4 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 the modal's JS focus trap fires1257  // when Peach's internal inputs gain focus (they are outside the modal's DOM subtree),1258  // immediately blurring them and closing the identity suggest list.1259  // Fix: detect the containing form or modal 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 regardless of the container's CSS context —1262  // overflow:hidden and most transforms do not affect fixed children.1263  //1264  // Detection priority:1265  //   1. <form> ancestor — always inside any focus-trap container wrapping the form1266  //   2. ARIA modal (dialog / aria-modal / role=dialog)1267  //   3. position:fixed ancestor — catches modals that omit ARIA attributes1268  const modalAncestor = (1269    anchorEl.closest<HTMLElement>('form') ??1270    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1271    (() => {1272      let cur: HTMLElement | null = anchorEl.parentElement;1273      while (cur && cur !== document.body) {1274        if (window.getComputedStyle(cur).position === 'fixed') return cur;1275        cur = cur.parentElement;1276      }1277      return null;1278    })()1279  );1280  host.style.cssText = `position: ${modalAncestor ? "fixed" : "absolute"}; z-index: 2147483647;`;1281  host.style.setProperty("--peach-accent", accentHex);1282  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1283  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1284  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1285  const shadow = host.attachShadow({ mode: "closed" });12861287  const style = shadow.appendChild(document.createElement("style"));1288  style.textContent = SELECTOR_STYLES;12891290  const rect = anchorEl.getBoundingClientRect();1291  // Fixed positioning uses viewport-relative coords; absolute uses document-relative.1292  host.style.top = `${rect.bottom + (modalAncestor ? 0 : window.scrollY) + 5}px`;1293  host.style.left = `${rect.left + (modalAncestor ? 0 : window.scrollX)}px`;1294  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1295  // wide single-input fields (e.g. centered email input on signup pages).1296  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1297  // expand the host after the initial measurement.1298  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1299  host.style.width = `${popupWidth}px`;13001301  const container = shadow.appendChild(document.createElement("div"));1302  container.className = "peach-inline-popup";1303  container.setAttribute("data-theme", popupTheme);13041305  const searchableEntries = options.searchableEntries ?? [];1306  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();13071308  let query = "";1309  let focusedIndex = -1;1310  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1311  let searchInput: HTMLInputElement | null = null;1312  // Tracks the silver-platter entry the user pivoted away from, so the1313  // search/list header can offer a one-click way back to it. null when the1314  // popup never showed a single-match platter (e.g. multi-match list view).1315  let silverPlatterOrigin: SelectorEntry | null = null;1316  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1317  // setInterval. Add to this list — don't fan out the dismiss function.1318  const cleanupHooks: Array<() => void> = [];13191320  // Smooth height transitions whenever content changes height.1321  // ResizeObserver fires on natural height changes; we freeze the old height,1322  // then animate to the new one so the surface never jumps.1323  {1324    let prevH = 0;1325    let blocked = false;1326    const heightRo = new ResizeObserver(([entry]) => {1327      if (blocked) return;1328      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1329      if (prevH > 0 && Math.abs(h - prevH) > 1) {1330        blocked = true;1331        container.style.height = `${prevH}px`;1332        requestAnimationFrame(() => requestAnimationFrame(() => {1333          container.style.height = `${h}px`;1334          prevH = h;1335          const onEnd = (e: TransitionEvent) => {1336            if (e.propertyName !== "height") return;1337            container.style.height = "";1338            blocked = false;1339            container.removeEventListener("transitionend", onEnd);1340          };1341          container.addEventListener("transitionend", onEnd);1342        }));1343      } else {1344        prevH = h;1345      }1346    });1347    heightRo.observe(container);1348    cleanupHooks.push(() => heightRo.disconnect());1349  }13501351  // Pre-capture the anchor field value for username prefill1352  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1353  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1354  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13551356  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1357    const seen = new Set<string>();1358    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1359  }13601361  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1362    const q = value.trim().toLowerCase();1363    const deduped = uniqueEntries(source);1364    if (!q) return deduped.slice(0, 8);1365    return deduped.filter(e =>1366      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1367    ).slice(0, 12);1368  }13691370  function activeEntries(): SelectorEntry[] {1371    // When user is typing a search, filter across all known entries (domain matches + vault)1372    if (query.trim()) {1373      const merged = uniqueEntries([...entries, ...searchableEntries]);1374      return filterEntries(merged, query);1375    }1376    // Default: show domain matches; fall back to vault search when no matches1377    if (entries.length > 0) return entries;1378    return filterEntries(searchableEntries, "").slice(0, 8);1379  }13801381  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1382    const icon = document.createElement("div");1383    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1384    if (isNew) {1385      icon.innerHTML = plusSvgStr();1386    } else {1387      // Use the generic key glyph for all entries in the page-injected selector.1388      // Avoids disclosing vault domains to any third party and avoids needing1389      // to expose the browser favicon API to page context via web_accessible_resources.1390      void url;1391      icon.innerHTML = keySvgStr();1392    }1393    return icon;1394  }13951396  function renderIdentityHelper() {1397    container.innerHTML = "";1398    const identities = options.savedIdentities ?? [];13991400    // Header: "NEW ACCOUNT" + domain name1401    const hdr = container.appendChild(document.createElement("div"));1402    hdr.className = "domain-header";1403    const eyebrow = hdr.appendChild(document.createElement("div"));1404    eyebrow.className = "domain-eyebrow";1405    eyebrow.textContent = "NEW ACCOUNT";1406    const domName = hdr.appendChild(document.createElement("div"));1407    domName.className = "domain-name";1408    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14091410    // Identity rows1411    const list = container.appendChild(document.createElement("div"));1412    list.className = "identity-list";1413    for (const id of identities) {1414      const row = list.appendChild(document.createElement("div"));1415      row.className = "peach-identity-row";1416      row.setAttribute("tabindex", "-1");1417      const val = row.appendChild(document.createElement("div"));1418      val.className = "peach-identity-value";1419      val.textContent = id.value;1420      const meta = row.appendChild(document.createElement("div"));1421      meta.className = "peach-identity-meta";1422      meta.textContent = `used ${id.useCount}×`;1423      row.addEventListener("click", () => {1424        options.onFillFields?.(id.value, "");1425        renderGenerator(id.value);1426      });1427    }14281429    // Divider before "Use a different email…"1430    if (identities.length > 0) {1431      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1432    }14331434    // "Use a different email…" expandable row1435    const altRow = container.appendChild(document.createElement("div"));1436    altRow.className = "identity-alt-row";1437    altRow.textContent = "+ Use a different email…";14381439    const altInputWrap = container.appendChild(document.createElement("div"));1440    altInputWrap.className = "identity-alt-input-wrap";1441    const altInput = altInputWrap.appendChild(document.createElement("input"));1442    altInput.className = "identity-alt-input";1443    altInput.type = "email";1444    altInput.placeholder = "[email protected]";1445    altInput.setAttribute("autocomplete", "off");1446    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1447    altConfirm.className = "identity-alt-confirm";1448    altConfirm.type = "button";1449    altConfirm.textContent = "✓";14501451    function fillCustomEmail() {1452      const v = altInput.value.trim();1453      if (!v) return;1454      options.onFillFields?.(v, "");1455      renderGenerator(v);1456    }14571458    altRow.addEventListener("click", () => {1459      altRow.style.display = "none";1460      altInputWrap.classList.add("open");1461      altInput.focus();1462    });1463    altConfirm.addEventListener("click", fillCustomEmail);1464    altInput.addEventListener("keydown", (e) => {1465      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1466    });14671468    // Escape hatch: user already has a vault entry for this site but it1469    // wasn't detected (different domain, old entry, etc.). Tapping this1470    // switches to the full searchable list so they can find and fill it;1471    // selecting an entry there will trigger the remember-site toast if1472    // the domain isn't already associated.1473    if ((options.searchableEntries?.length ?? 0) > 0) {1474      const escapeRow = container.appendChild(document.createElement("div"));1475      escapeRow.className = "identity-escape-row";1476      escapeRow.textContent = "I already have an account →";1477      escapeRow.setAttribute("tabindex", "0");1478      escapeRow.addEventListener("click", () => renderList());1479      escapeRow.addEventListener("keydown", (e) => {1480        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1481      });1482    }1483  }14841485  function renderGenerator(filledEmail: string) {1486    container.innerHTML = "";1487    const sitePolicy = detectPasswordPolicy();14881489    const wrap = container.appendChild(document.createElement("div"));1490    wrap.className = "gen-view";14911492    // Header: domain + NEW ACCOUNT1493    const hdrRow = wrap.appendChild(document.createElement("div"));1494    hdrRow.className = "domain-header";1495    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1496    eyebrow2.className = "domain-eyebrow";1497    eyebrow2.textContent = "NEW ACCOUNT";1498    const domName2 = hdrRow.appendChild(document.createElement("div"));1499    domName2.className = "domain-name";1500    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");15011502    // Confirmed email row1503    const conf = wrap.appendChild(document.createElement("div"));1504    conf.className = "gen-confirmed";1505    const confCheck = conf.appendChild(document.createElement("span"));1506    confCheck.className = "gen-confirmed-check";1507    confCheck.textContent = "✓";1508    const confVal = conf.appendChild(document.createElement("div"));1509    confVal.className = "gen-confirmed-val";1510    confVal.textContent = filledEmail;15111512    const lbl = wrap.appendChild(document.createElement("div"));1513    lbl.className = "gen-label";1514    lbl.textContent = "Generate a password";15151516    let currentPw = "";1517    const smartGen = createSmartGenerator({1518      policy: sitePolicy,1519      onChange: (pw) => { currentPw = pw; },1520    });1521    wrap.appendChild(smartGen.root);15221523    const fillBtn = wrap.appendChild(document.createElement("button"));1524    fillBtn.className = "gen-fill-btn";1525    fillBtn.type = "button";1526    fillBtn.textContent = "Copy & fill";1527    fillBtn.addEventListener("click", () => {1528      if (!currentPw) return;1529      options.onFillFields?.("", currentPw);1530      renderSaveOffer(filledEmail, currentPw);1531    });1532  }15331534  function renderSaveOffer(filledEmail: string, filledPassword: string) {1535    container.innerHTML = "";1536    const domain = options.domain ?? location.hostname.replace(/^www\./, "");15371538    const wrap = container.appendChild(document.createElement("div"));1539    wrap.className = "save-offer";15401541    const title = wrap.appendChild(document.createElement("div"));1542    title.className = "save-offer-title";1543    title.textContent = "Save this login to Peach?";15441545    function detailRow(label: string, value: string) {1546      const row = wrap.appendChild(document.createElement("div"));1547      row.className = "save-offer-row";1548      const lbl = row.appendChild(document.createElement("div"));1549      lbl.className = "save-offer-lbl";1550      lbl.textContent = label;1551      const val = row.appendChild(document.createElement("div"));1552      val.className = "save-offer-val";1553      val.textContent = value;1554    }15551556    detailRow("site", domain);1557    detailRow("email", filledEmail);1558    detailRow("password", "••••••••••••••••");15591560    const btns = wrap.appendChild(document.createElement("div"));1561    btns.className = "save-offer-btns";15621563    const saveBtn = btns.appendChild(document.createElement("button"));1564    saveBtn.className = "save-offer-save";1565    saveBtn.type = "button";1566    saveBtn.textContent = "Save";1567    saveBtn.addEventListener("click", async () => {1568      saveBtn.disabled = true;1569      saveBtn.textContent = "Saving…";1570      try {1571        const res = await chrome.runtime.sendMessage({1572          type: "ADD_ENTRY",1573          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1574        });1575        if ((res as { ok?: boolean }).ok) {1576          showSuccess(sTitle);1577        } else {1578          saveBtn.disabled = false;1579          saveBtn.textContent = "Save";1580        }1581      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1582    });15831584    const skipBtn = btns.appendChild(document.createElement("button"));1585    skipBtn.className = "save-offer-skip";1586    skipBtn.type = "button";1587    skipBtn.textContent = "Not now";1588    skipBtn.addEventListener("click", () => { dismiss(true); });1589  }15901591  function renderList() {1592    container.innerHTML = "";1593    focusedIndex = -1;1594    searchInput = null;1595    currentMode = "list";15961597    const current = activeEntries();15981599    // Domain header (always show) — eyebrow + domain on the left,1600    // a "+" shortcut to the create form on the right so the user is never1601    // trapped in the search list when they want to make a new entry.1602    const domHdr = document.createElement("div");1603    domHdr.className = "domain-header";1604    const headText = document.createElement("div");1605    headText.className = "domain-header-text";1606    const eyebrow = document.createElement("div");1607    eyebrow.className = "domain-eyebrow";1608    eyebrow.textContent = options.isSignup1609      ? "Sign up as"1610      : entries.length > 0 ? "Saved for this site" : "No saved login";1611    const domName = document.createElement("div");1612    domName.className = "domain-name";1613    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1614    headText.append(eyebrow, domName);1615    domHdr.appendChild(headText);16161617    if (!options.isSignup) {1618      const actions = document.createElement("div");1619      actions.className = "domain-header-actions";16201621      // Back arrow takes the place of the silver-platter's search icon when1622      // the user has pivoted away from a single-match platter — gives them1623      // a one-click way back to the original recommendation.1624      if (silverPlatterOrigin) {1625        const backBtn = document.createElement("button");1626        backBtn.className = "domain-search-btn";1627        backBtn.type = "button";1628        backBtn.setAttribute("aria-label", "Back to suggested entry");1629        backBtn.title = "Back to suggested entry";1630        backBtn.innerHTML = backSvgStr();1631        backBtn.addEventListener("click", (e) => {1632          e.stopPropagation();1633          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);1634        });1635        actions.appendChild(backBtn);1636      }16371638      const addBtn = document.createElement("button");1639      addBtn.className = "domain-add-btn";1640      addBtn.type = "button";1641      addBtn.setAttribute("aria-label", "Create new entry");1642      addBtn.title = "Create new entry";1643      addBtn.textContent = "+";1644      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1645      actions.appendChild(addBtn);16461647      domHdr.appendChild(actions);1648    }16491650    container.appendChild(domHdr);16511652    // Search — always show so user can find entries beyond the domain matches1653    const sw = document.createElement("div"); sw.className = "search-wrap";1654    searchInput = document.createElement("input");1655    searchInput.className = "search";1656    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1657    searchInput.value = query;1658    searchInput.addEventListener("input", () => {1659      query = searchInput?.value ?? "";1660      renderList();1661      searchInput?.focus();1662      searchInput?.setSelectionRange(query.length, query.length);1663    });1664    sw.appendChild(searchInput);1665    container.appendChild(sw);16661667    // Results1668    const results = document.createElement("div");1669    results.className = "results";1670    container.appendChild(results);16711672    if (current.length === 0 && entries.length > 0) {1673      // Show a hint but don't render empty entries1674    }16751676    for (let i = 0; i < current.length; i++) {1677      const e = current[i]!;1678      const entryEl = document.createElement("div");1679      entryEl.className = "entry";1680      entryEl.dataset.id = e.id;1681      entryEl.dataset.index = String(i);1682      entryEl.setAttribute("tabindex", "-1");16831684      entryEl.appendChild(makeEntryIcon(e.url));16851686      const info = document.createElement("div"); info.className = "entry-info";1687      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1688      const subEl = document.createElement("div"); subEl.className = "entry-sub";1689      const domain = e.url ? getDomainFromUrl(e.url) : "";1690      subEl.textContent = domain || e.username || "";1691      info.append(titleEl, subEl);1692      entryEl.appendChild(info);16931694      if (e.hasTotp) {1695        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1696        entryEl.appendChild(badge);1697      }1698      if (e.hasPasskey) {1699        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1700        entryEl.appendChild(badge);1701      }17021703      entryEl.addEventListener("click", () => {1704        if (options.isSignup && options.onFillFields) {1705          // Signup mode: clicking a saved identity fills the username field1706          options.onFillFields(e.username ?? "", "");1707          dismiss();1708        } else {1709          onSelect(e.id);1710          dismiss();1711        }1712      });1713      results.appendChild(entryEl);1714    }17151716    // Divider before "New entry"1717    if (current.length > 0) {1718      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1719    }17201721    // "New entry" row — always present1722    const newEl = document.createElement("div");1723    newEl.className = "entry";1724    newEl.setAttribute("tabindex", "-1");1725    newEl.appendChild(makeEntryIcon(undefined, true));17261727    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1728    const newTitle = document.createElement("div");1729    newTitle.className = "entry-title is-new";1730    newTitle.textContent = `New entry for ${sTitle}`;1731    const newSub = document.createElement("div");1732    newSub.className = "entry-sub";1733    newSub.textContent = sOrigin;1734    newInfo.append(newTitle, newSub);1735    newEl.appendChild(newInfo);1736    newEl.addEventListener("click", showCreateForm);1737    results.appendChild(newEl);17381739    // Focus search if present1740    if (searchInput) {1741      requestAnimationFrame(() => {1742        searchInput?.focus();1743        // Seed query (from type-to-search or domain-search-btn) lands at the1744        // end so the next keystroke extends it, not overwrites.1745        searchInput?.setSelectionRange(query.length, query.length);1746      });1747    }1748  }17491750  function setFocused(idx: number) {1751    const all = container.querySelectorAll<HTMLElement>(".entry");1752    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1753    focusedIndex = idx;1754    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1755  }17561757  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1758    const typed = identities.filter(s => s.type === fieldType);1759    if (!typed.length) return;1760    let collapsed = false;1761    let suppressNextFocus = false;17621763    const list = g.appendChild(document.createElement("div"));1764    list.className = "identity-suggest-list";1765    list.style.display = "none";17661767    // Collapse toggle — sits alone now that filter pills are gone1768    const collapseRow = list.appendChild(document.createElement("div"));1769    collapseRow.className = "identity-filter-row";1770    collapseRow.style.justifyContent = "flex-end";1771    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1772    collapseBtn.type = "button";1773    collapseBtn.className = "identity-collapse-btn";1774    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>`;1775    collapseBtn.addEventListener("mousedown", (e) => {1776      e.preventDefault();1777      collapsed = !collapsed;1778      collapseBtn.classList.toggle("is-collapsed", collapsed);1779      rowsWrapper.classList.toggle("is-collapsed", collapsed);1780    });17811782    const rowsWrapper = list.appendChild(document.createElement("div"));1783    rowsWrapper.className = "identity-rows";1784    const rows = rowsWrapper.appendChild(document.createElement("div"));1785    rows.className = "identity-rows-inner";17861787    function pick(value: string) {1788      inp.value = value;1789      list.style.display = "none";1790      suppressNextFocus = true;1791      inp.focus();1792    }17931794    function render() {1795      const q = inp.value.toLowerCase();1796      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1797      rows.innerHTML = "";1798      if (!filtered.length) { list.style.display = "none"; return; }1799      for (const s of filtered) {1800        const row = rows.appendChild(document.createElement("button"));1801        row.type = "button"; row.className = "identity-suggest-row";1802        const val = row.appendChild(document.createElement("span"));1803        val.className = "identity-suggest-val"; val.textContent = s.value;1804        const meta = row.appendChild(document.createElement("span"));1805        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1806        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1807        row.addEventListener("keydown", (e) => {1808          if (e.key === "ArrowDown") {1809            e.preventDefault();1810            (row.nextElementSibling as HTMLElement | null)?.focus();1811          } else if (e.key === "ArrowUp") {1812            e.preventDefault();1813            const prev = row.previousElementSibling as HTMLElement | null;1814            if (prev) prev.focus();1815            else inp.focus();1816          } else if (e.key === "Enter" || e.key === " ") {1817            e.preventDefault();1818            pick(s.value);1819          } else if (e.key === "Escape") {1820            e.preventDefault();1821            list.style.display = "none";1822            suppressNextFocus = true;1823            inp.focus();1824          }1825        });1826        row.addEventListener("blur", (e) => {1827          const rt = (e as FocusEvent).relatedTarget as Node | null;1828          if (rt && (rt === inp || list.contains(rt))) return;1829          setTimeout(() => { list.style.display = "none"; }, 150);1830        });1831      }1832      list.style.display = "";1833    }18341835    inp.addEventListener("focus", () => {1836      if (suppressNextFocus) { suppressNextFocus = false; return; }1837      render();1838    });1839    inp.addEventListener("input", render);1840    inp.addEventListener("keydown", (e) => {1841      if (list.style.display === "none") return;1842      if (e.key === "ArrowDown" && !collapsed) {1843        e.preventDefault();1844        (rows.firstElementChild as HTMLElement | null)?.focus();1845      } else if (e.key === "Escape") {1846        e.preventDefault();1847        list.style.display = "none";1848      }1849    });1850    inp.addEventListener("blur", (e) => {1851      const rt = (e as FocusEvent).relatedTarget as Node | null;1852      if (rt && list.contains(rt)) return;1853      setTimeout(() => { list.style.display = "none"; }, 150);1854    });1855  }18561857  async function showCreateForm() {1858    currentMode = "create";1859    container.innerHTML = "";18601861    // Guard: the service worker may lock the vault between when the selector1862    // opens and when the user clicks "New entry". Show the inline unlock form1863    // instead of silently failing on save.1864    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1865    if (!statusRes?.unlocked) {1866      renderLocked();1867      return;1868    }18691870    // Detect page password policy once for this form — reused on every1871    // regenerate click so the user always gets a compliant password.1872    const sitePolicy = detectPasswordPolicy();18731874    // Fetch identities on-demand — they're passed in signup context but not1875    // in login/search context where the user still clicks "New entry".1876    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1877    if (!formIdentities.length) {1878      try {1879        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1880        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1881      } catch { /* silent fallback */ }1882    }18831884    const wrap = document.createElement("div");1885    wrap.className = "create-form-wrap";18861887    // Header1888    const head = document.createElement("div"); head.className = "create-head";1889    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1890    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>`;1891    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1892    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1893    head.append(backBtn, lbl);18941895    // Body1896    const body = document.createElement("div"); body.className = "create-body";18971898    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1899      const g = document.createElement("div"); g.className = "f-group";1900      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1901      const inp = document.createElement("input"); inp.className = "f-input";1902      g.append(l, inp); return { g, inp };1903    }19041905    // Title1906    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1907    body.appendChild(tg.g);19081909    // URL1910    const ug = fGroup("website");1911    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1912    if (loginSubdomain) {1913      const h = document.createElement("div"); h.className = "url-hint";1914      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1915    }1916    body.appendChild(ug.g);19171918    // Username — pre-fill from anchor if it doesn't look like an email1919    const xg = fGroup("username");1920    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1921    xg.inp.placeholder = "johndoe";1922    xg.inp.setAttribute("autocomplete", "off");1923    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1924    body.appendChild(xg.g);19251926    // Email — pre-fill from anchor if it looks like an email1927    const eg = fGroup("email");1928    (eg.inp as HTMLInputElement).type = "email";1929    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1930    eg.inp.placeholder = "[email protected]";1931    eg.inp.setAttribute("autocomplete", "off");1932    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1933    body.appendChild(eg.g);19341935    // Password — full smart generator with charset pills + length slider +1936    // policy hint. Mirrors the main UI's compact generator so users get the1937    // same controls inline as in the popup.1938    const pg = fGroup("password");1939    pg.inp.remove(); // smartGen provides its own display — no separate input needed1940    let currentPassword = prePassword || "";1941    const smartGen = createSmartGenerator({1942      policy: sitePolicy,1943      initialPassword: prePassword || undefined,1944      onChange: (pw) => { currentPassword = pw; },1945    });1946    pg.g.appendChild(smartGen.root);1947    body.appendChild(pg.g);19481949    // Save1950    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1951    saveBtn.textContent = "Save entry";1952    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1953    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1954    saveBtn.addEventListener("click", async () => {1955      const title = tg.inp.value.trim();1956      const pw = currentPassword.trim();1957      const username = xg.inp.value.trim();1958      const email = eg.inp.value.trim();1959      if (!title) {1960        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1961        showFormError("Entry needs a title");1962        return;1963      }1964      if (!pw) {1965        showFormError("Entry needs a password — tap regen to make one");1966        return;1967      }1968      errEl.style.display = "none";1969      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1970      try {1971        const res = await chrome.runtime.sendMessage({1972          type: "ADD_ENTRY",1973          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1974        });1975        if ((res as { ok?: boolean }).ok) {1976          // Fill the detected form. onFillFields uses whichever identity the1977          // page anchored on — the vault captures both username and email.1978          options.onFillFields?.(username || email, pw);1979          showSuccess(title);1980        } else {1981          const errMsg = (res as { error?: string }).error === "vault locked"1982            ? "Vault locked — open Peach to save"1983            : "Could not save entry";1984          showFormError(errMsg);1985          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1986        }1987      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1988    });1989    body.appendChild(saveBtn);1990    body.appendChild(errEl);19911992    wrap.append(head, body);1993    container.appendChild(wrap);1994    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1995  }19961997  function showSuccess(title: string) {1998    currentMode = "success";1999    container.innerHTML = "";2000    const wrap = document.createElement("div"); wrap.className = "success-wrap";2001    const ring = document.createElement("div"); ring.className = "success-ring";2002    ring.innerHTML = checkSvgStr();2003    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2004    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2005    wrap.append(ring, t, s);2006    container.appendChild(wrap);2007    setTimeout(() => dismiss(), 1600);2008  }20092010  function flashActionBtn(btn: HTMLButtonElement) {2011    btn.classList.add("flashed");2012    setTimeout(() => btn.classList.remove("flashed"), 700);2013  }20142015  // M3/QUA-005: when both the direct clipboard write and the background COPY2016  // fallback fail, briefly show the user that the copy did not happen.2017  function flashCopyError(btn: HTMLButtonElement) {2018    const original = btn.textContent ?? "";2019    btn.textContent = "Blocked";2020    btn.classList.add("flashed");2021    setTimeout(() => {2022      btn.classList.remove("flashed");2023      if (btn.isConnected) btn.textContent = original;2024    }, 1200);2025  }20262027  function renderSilverPlatter(entry: SelectorEntry) {2028    container.innerHTML = "";2029    searchInput = null;2030    focusedIndex = -1;2031    currentMode = "silver-platter";2032    silverPlatterOrigin = entry;20332034    const domHdr = document.createElement("div");2035    domHdr.className = "domain-header";2036    const headText = document.createElement("div");2037    headText.className = "domain-header-text";2038    const eyebrow = document.createElement("div");2039    eyebrow.className = "domain-eyebrow";2040    eyebrow.textContent = "Saved for this site";2041    const domName = document.createElement("div");2042    domName.className = "domain-name";2043    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2044    headText.append(eyebrow, domName);2045    domHdr.appendChild(headText);2046    if (!options.isSignup) {2047      const actions = document.createElement("div");2048      actions.className = "domain-header-actions";20492050      // Search shortcut — same idea as type-to-search below, but visible so2051      // the user can discover that another entry is reachable from a2052      // single-match platter. Sits to the left of the create button.2053      const searchBtn = document.createElement("button");2054      searchBtn.className = "domain-search-btn";2055      searchBtn.type = "button";2056      searchBtn.setAttribute("aria-label", "Search for a different entry");2057      searchBtn.title = "Search for a different entry";2058      searchBtn.innerHTML = searchSvgStr();2059      searchBtn.addEventListener("click", (e) => {2060        e.stopPropagation();2061        query = "";2062        renderList();2063      });2064      actions.appendChild(searchBtn);20652066      const addBtn = document.createElement("button");2067      addBtn.className = "domain-add-btn";2068      addBtn.type = "button";2069      addBtn.setAttribute("aria-label", "Create new entry");2070      addBtn.title = "Create new entry";2071      addBtn.textContent = "+";2072      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2073      actions.appendChild(addBtn);20742075      domHdr.appendChild(actions);2076    }2077    container.appendChild(domHdr);20782079    const platter = document.createElement("div");2080    platter.className = "silver-platter";20812082    const titleEl = document.createElement("div");2083    titleEl.className = "sp-title";2084    titleEl.textContent = entry.title;2085    platter.appendChild(titleEl);20862087    if (entry.email) {2088      const emailEl = document.createElement("div");2089      emailEl.className = "sp-identity-row";2090      const emailLbl = document.createElement("span");2091      emailLbl.className = "sp-identity-label";2092      emailLbl.textContent = "email";2093      const emailVal = document.createElement("span");2094      emailVal.className = "sp-username";2095      emailVal.textContent = entry.email;2096      emailEl.append(emailLbl, emailVal);2097      platter.appendChild(emailEl);2098    }20992100    if (entry.username) {2101      const userEl = document.createElement("div");2102      userEl.className = "sp-identity-row";2103      const userLbl = document.createElement("span");2104      userLbl.className = "sp-identity-label";2105      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2106      const userVal = document.createElement("span");2107      userVal.className = "sp-username";2108      userVal.textContent = entry.username;2109      userEl.append(userLbl, userVal);2110      platter.appendChild(userEl);2111    }21122113    const fillBtn = document.createElement("button");2114    fillBtn.className = "sp-fill-btn";2115    fillBtn.type = "button";2116    fillBtn.textContent = "Fill credentials";2117    fillBtn.addEventListener("click", () => {2118      if (fillBtn.disabled) return;2119      fillBtn.disabled = true;2120      fillBtn.classList.add("filled");2121      fillBtn.innerHTML = checkSvgStr();2122      // Fire the fill, then exit via the standard exit animation. The fill2123      // itself is async (handled in index.ts) — by 400ms the form is filled2124      // and the popup begins its exit. Total dwell from click to host2125      // removal: 400ms + 130ms (exit animation) = 530ms.2126      onSelect(entry.id);2127      setTimeout(() => dismiss(), 400);2128    });2129    platter.appendChild(fillBtn);21302131    const actionsGroup = document.createElement("div");2132    actionsGroup.className = "sp-actions-group";2133    const actionsLabel = document.createElement("div");2134    actionsLabel.className = "sp-actions-label";2135    actionsLabel.textContent = "Copy";2136    actionsGroup.appendChild(actionsLabel);21372138    const actions = document.createElement("div");2139    actions.className = "sp-actions";2140    actionsGroup.appendChild(actions);21412142    if (entry.email) {2143      const copyEmail = document.createElement("button");2144      copyEmail.className = "sp-action-btn";2145      copyEmail.type = "button";2146      copyEmail.title = "Copy email";2147      copyEmail.textContent = "Email";2148      copyEmail.addEventListener("click", async (e) => {2149        e.stopPropagation();2150        let alreadyWritten = false;2151        try {2152          await navigator.clipboard.writeText(entry.email!);2153          alreadyWritten = true;2154        } catch (err) {2155          console.warn("[Peach] clipboard write denied:", err);2156        }2157        const resp = await chrome.runtime.sendMessage({2158          type: "COPY",2159          payload: { text: entry.email, label: "Email", alreadyWritten },2160        }).catch(() => null) as { ok?: boolean } | null;2161        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2162        else flashCopyError(copyEmail);2163      });2164      actions.appendChild(copyEmail);2165    }21662167    const copyU = document.createElement("button");2168    copyU.className = "sp-action-btn";2169    copyU.type = "button";2170    const usernameIsEmail = entry.username?.includes("@") ?? false;2171    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2172    copyU.textContent = usernameIsEmail ? "Email" : "Username";2173    copyU.disabled = !entry.username;2174    copyU.addEventListener("click", async (e) => {2175      e.stopPropagation();2176      if (!entry.username) return;2177      let alreadyWritten = false;2178      try {2179        await navigator.clipboard.writeText(entry.username);2180        alreadyWritten = true;2181      } catch (err) {2182        console.warn("[Peach] clipboard write denied:", err);2183      }2184      const resp = await chrome.runtime.sendMessage({2185        type: "COPY",2186        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2187      }).catch(() => null) as { ok?: boolean } | null;2188      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2189      else flashCopyError(copyU);2190    });2191    actions.appendChild(copyU);21922193    const copyP = document.createElement("button");2194    copyP.className = "sp-action-btn";2195    copyP.type = "button";2196    copyP.title = "Copy password";2197    copyP.textContent = "Password";2198    copyP.addEventListener("click", async (e) => {2199      e.stopPropagation();2200      const resp = await chrome.runtime.sendMessage({2201        type: "GET_ENTRY_FOR_FILL",2202        payload: { id: entry.id },2203      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2204      if (!resp?.ok || !resp.data?.password) return;2205      let alreadyWritten = false;2206      try {2207        await navigator.clipboard.writeText(resp.data.password);2208        alreadyWritten = true;2209      } catch (err) {2210        console.warn("[Peach] clipboard write denied:", err);2211      }2212      const copyResp = await chrome.runtime.sendMessage({2213        type: "COPY",2214        payload: { text: resp.data.password, label: "Password", alreadyWritten },2215      }).catch(() => null) as { ok?: boolean } | null;2216      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2217      else flashCopyError(copyP);2218    });2219    actions.appendChild(copyP);22202221    let trayEl: HTMLDivElement | null = null;2222    let trayInterval: ReturnType<typeof setInterval> | null = null;22232224    function closeTray() {2225      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2226      trayEl?.remove();2227      trayEl = null;2228    }2229    // Register so dismiss() will close the tray and clear the interval2230    // even if the user dismisses without explicitly closing the tray.2231    cleanupHooks.push(closeTray);22322233    async function openTOTPTray() {2234      // Fetch the current TOTP code from the background. The raw base32 seed2235      // never enters the content script (SEV-3-C): we receive the live 6-digit2236      // code plus the seconds remaining, count down locally, and re-fetch a2237      // fresh code only when the 30s window rolls over.2238      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2239        const r = await chrome.runtime.sendMessage({2240          type: "GET_ENTRY_FOR_FILL",2241          payload: { id: entry.id },2242        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2243        if (!r?.ok || !r.data?.totpCode) return null;2244        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2245      }2246      let current = await fetchCode();2247      if (!current) return;22482249      trayEl = document.createElement("div");2250      trayEl.className = "sp-tray";22512252      const label = document.createElement("span");2253      label.className = "sp-tray-label";2254      label.textContent = "2FA";2255      trayEl.appendChild(label);22562257      const codeEl = document.createElement("div");2258      codeEl.className = "sp-totp-code";2259      trayEl.appendChild(codeEl);22602261      const ringNs = "http://www.w3.org/2000/svg";2262      const ring = document.createElementNS(ringNs, "svg");2263      ring.setAttribute("class", "sp-totp-ring");2264      ring.setAttribute("viewBox", "0 0 24 24");2265      const trackC = document.createElementNS(ringNs, "circle");2266      trackC.setAttribute("class", "ring-track");2267      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2268      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2269      const fillC = document.createElementNS(ringNs, "circle");2270      fillC.setAttribute("class", "ring-fill");2271      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2272      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2273      fillC.setAttribute("stroke-linecap", "round");2274      fillC.setAttribute("stroke-dasharray", "62.83");2275      ring.append(trackC, fillC);2276      trayEl.appendChild(ring);22772278      const copyBtn = document.createElement("button");2279      copyBtn.className = "sp-totp-copy";2280      copyBtn.type = "button";2281      copyBtn.textContent = "Copy";2282      trayEl.appendChild(copyBtn);22832284      function render() {2285        const { code, remaining } = current!;2286        // Group as "847 291" — easier to read than "847291"2287        codeEl.textContent = code.length === 62288          ? `${code.slice(0, 3)} ${code.slice(3)}`2289          : code;2290        // Ring fills counter-clockwise as time elapses: dashoffset goes from2291        // 0 (full ring) to 62.83 (empty) over the 30s window.2292        const fraction = (30 - remaining) / 30;2293        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2294      }2295      render();2296      trayInterval = setInterval(async () => {2297        if (!current) return;2298        current = { code: current.code, remaining: current.remaining - 1 };2299        // Window rolled over — pull a fresh code from the background.2300        if (current.remaining <= 0) {2301          const next = await fetchCode();2302          current = next ?? { code: current.code, remaining: 30 };2303        }2304        render();2305      }, 1000);23062307      copyBtn.addEventListener("click", async (e) => {2308        e.stopPropagation();2309        const code = current?.code;2310        if (!code) return;2311        let alreadyWritten = false;2312        try {2313          await navigator.clipboard.writeText(code);2314          alreadyWritten = true;2315        } catch (err) {2316          console.warn("[Peach] clipboard write denied:", err);2317        }2318        const resp = await chrome.runtime.sendMessage({2319          type: "COPY",2320          payload: { text: code, label: "TOTP", alreadyWritten },2321        }).catch(() => null) as { ok?: boolean } | null;2322        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2323        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2324      });23252326      platter.appendChild(trayEl);2327    }23282329    const editBtn = document.createElement("button");2330    editBtn.className = "sp-action-btn sp-action-edit";2331    editBtn.type = "button";2332    editBtn.title = "Edit entry";2333    editBtn.textContent = "Edit";2334    editBtn.addEventListener("click", (e) => {2335      e.stopPropagation();2336      closeTray();2337      void renderInlineEdit(entry);2338    });2339    actions.appendChild(editBtn);23402341    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2342    // "···" toggle was zero-savings (the toggle button took the same space2343    // the "2FA" label needed) and made the code one extra click away.2344    if (entry.hasTotp) void openTOTPTray();23452346    platter.appendChild(actionsGroup);2347    container.appendChild(platter);2348  }23492350  /**2351   * Inline-popup edit mode. Swaps the silver platter for an editable form2352   * over the same shadow-DOM surface so the user never leaves the page.2353   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2354   * with the new fields. Cancel returns without writing.2355   */2356  async function renderInlineEdit(summary: SelectorEntry) {2357    container.innerHTML = "";2358    const wrap = document.createElement("div");2359    wrap.className = "create-form-wrap";23602361    const head = document.createElement("div");2362    head.className = "create-head";2363    const back = document.createElement("button");2364    back.className = "back-btn";2365    back.type = "button";2366    back.title = "Cancel";2367    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>`;2368    back.addEventListener("click", () => renderSilverPlatter(summary));2369    head.appendChild(back);2370    const headLbl = document.createElement("div");2371    headLbl.className = "create-label";2372    headLbl.textContent = "Edit entry";2373    head.appendChild(headLbl);2374    wrap.appendChild(head);23752376    const body = document.createElement("div");2377    body.className = "create-body";23782379    // Loading shimmer while we fetch the full entry2380    const loading = document.createElement("div");2381    loading.className = "empty-hint";2382    loading.textContent = "loading…";2383    body.appendChild(loading);2384    wrap.appendChild(body);2385    container.appendChild(wrap);23862387    const [res, idRes] = await Promise.all([2388      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2389      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2390      chrome.runtime.sendMessage({2391        type: "GET_ENTRY_FOR_EDIT",2392        payload: { id: summary.id },2393      }).catch(() => null),2394      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2395    ]);2396    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2397    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];23982399    if (!entryRes || !entryRes.ok || !entryRes.data) {2400      loading.textContent = "couldn't load this entry. try again from the popup.";2401      return;2402    }2403    body.innerHTML = "";24042405    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2406      const group = document.createElement("div");2407      group.className = "f-group";2408      const lbl = document.createElement("div");2409      lbl.className = "f-label";2410      lbl.textContent = label;2411      const input = document.createElement("input");2412      input.className = "f-input";2413      input.type = type;2414      input.value = value;2415      input.autocomplete = "off";2416      group.append(lbl, input);2417      body.appendChild(group);2418      return { g: group, inp: input };2419    }24202421    const titleInput = field("title", entryRes.data.title ?? "").inp;2422    const urlInput = field("url", entryRes.data.url ?? "").inp;2423    urlInput.classList.add("url-f");2424    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2425    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2426    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2427    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2428    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");24292430    // Password row with reveal toggle + generator2431    const pwGroup = document.createElement("div");2432    pwGroup.className = "f-group";2433    const pwLbl = document.createElement("div");2434    pwLbl.className = "f-label";2435    pwLbl.textContent = "password";2436    const pwRow = document.createElement("div");2437    pwRow.className = "f-row";2438    const pwInput = document.createElement("input");2439    pwInput.className = "f-input";2440    pwInput.type = "password";2441    pwInput.value = entryRes.data.password ?? "";2442    pwInput.autocomplete = "new-password";2443    const revealBtn = document.createElement("button");2444    revealBtn.className = "gen-btn";2445    revealBtn.type = "button";2446    revealBtn.textContent = "show";2447    revealBtn.addEventListener("click", () => {2448      const reveal = pwInput.type === "password";2449      pwInput.type = reveal ? "text" : "password";2450      revealBtn.textContent = reveal ? "hide" : "show";2451    });2452    pwRow.append(pwInput, revealBtn);2453    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2454    editSmartGen.root.style.display = "none";2455    let editGenVisible = false;2456    const genToggleBtn = document.createElement("button");2457    genToggleBtn.className = "gen-toggle-link";2458    genToggleBtn.type = "button";2459    genToggleBtn.textContent = "⚙ generate";2460    genToggleBtn.addEventListener("click", () => {2461      editGenVisible = !editGenVisible;2462      pwRow.style.display = editGenVisible ? "none" : "";2463      editSmartGen.root.style.display = editGenVisible ? "" : "none";2464      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2465    });2466    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2467    body.appendChild(pwGroup);24682469    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;24702471    // Notes2472    const notesGroup = document.createElement("div");2473    notesGroup.className = "f-group";2474    const notesLbl = document.createElement("div");2475    notesLbl.className = "f-label";2476    notesLbl.textContent = "notes";2477    const notesInput = document.createElement("textarea");2478    notesInput.className = "f-input";2479    notesInput.rows = 3;2480    notesInput.value = entryRes.data.notes ?? "";2481    notesInput.style.fontFamily = "Inter, sans-serif";2482    notesInput.style.resize = "vertical";2483    notesGroup.append(notesLbl, notesInput);2484    body.appendChild(notesGroup);24852486    // Save / Cancel row2487    const actionsRow = document.createElement("div");2488    actionsRow.className = "f-row";2489    const saveBtn = document.createElement("button");2490    saveBtn.className = "save-btn";2491    saveBtn.type = "button";2492    saveBtn.textContent = "Save changes";2493    saveBtn.style.flex = "1";2494    const cancelBtn = document.createElement("button");2495    cancelBtn.className = "gen-btn";2496    cancelBtn.type = "button";2497    cancelBtn.textContent = "cancel";2498    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2499    actionsRow.append(saveBtn, cancelBtn);2500    body.appendChild(actionsRow);25012502    saveBtn.addEventListener("click", async () => {2503      saveBtn.disabled = true;2504      const originalLabel = saveBtn.textContent;2505      saveBtn.textContent = "Saving…";2506      const patch: Record<string, unknown> = {2507        title: titleInput.value.trim(),2508        url: urlInput.value.trim(),2509        username: usernameInput.value.trim(),2510        email: emailInput.value.trim() || undefined,2511        password: pwInput.value,2512        totp: totpInput.value.trim(),2513        notes: notesInput.value,2514      };2515      const updateRes = (await chrome.runtime.sendMessage({2516        type: "UPDATE_ENTRY",2517        payload: { id: summary.id, patch },2518      }).catch(() => null)) as { ok: boolean; error?: string } | null;2519      if (!updateRes?.ok) {2520        saveBtn.disabled = false;2521        saveBtn.textContent = originalLabel;2522        const err = document.createElement("div");2523        err.className = "empty-hint";2524        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2525        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2526        body.appendChild(err);2527        setTimeout(() => err.remove(), 3000);2528        return;2529      }2530      // Refresh the platter with updated summary fields2531      const refreshed: SelectorEntry = {2532        id: summary.id,2533        title: patch.title as string,2534        username: patch.username as string,2535        email: patch.email as string | undefined,2536        url: patch.url as string,2537        hasTotp: Boolean(patch.totp),2538        hasPasskey: summary.hasPasskey,2539      };2540      renderSilverPlatter(refreshed);2541    });25422543    queueMicrotask(() => titleInput.focus());2544  }25452546  function renderLocked() {2547    container.innerHTML = "";25482549    // Domain header (same as list view)2550    const domHdr = document.createElement("div");2551    domHdr.className = "domain-header";2552    const eyebrow = document.createElement("div");2553    eyebrow.className = "domain-eyebrow";2554    eyebrow.textContent = "vault locked";2555    const domName = document.createElement("div");2556    domName.className = "domain-name";2557    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2558    domHdr.append(eyebrow, domName);2559    container.appendChild(domHdr);25602561    const wrap = document.createElement("div");2562    wrap.className = "locked-wrap";25632564    // Icon + label row2565    const head = document.createElement("div"); head.className = "locked-head";2566    const icon = document.createElement("div"); icon.className = "locked-icon";2567    icon.innerHTML = keySvgStr();2568    const title = document.createElement("div"); title.className = "locked-title";2569    title.textContent = "unlock to autofill";2570    head.append(icon, title);25712572    // The master password is NEVER collected in page-hosted DOM. A malicious2573    // page can observe keystrokes on the shared DOM event stream (a capture-2574    // phase listener registered before Peach injects sees every key before any2575    // stopImmediatePropagation), which would leak the vault's root secret2576    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2577    // where keystrokes are isolated from the page. After the user unlocks2578    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2579    // automatically (see content/index.ts), so the flow resumes on its own.2580    const sub = document.createElement("div");2581    sub.className = "locked-sub";2582    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";25832584    const openBtn = document.createElement("button");2585    openBtn.className = "locked-btn";2586    openBtn.type = "button";2587    openBtn.textContent = "Open Peach to unlock";2588    openBtn.addEventListener("click", () => {2589      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2590      openBtn.textContent = "opening Peach…";2591      openBtn.disabled = true;2592      // openPopup() can't always open programmatically (browser/version/gesture2593      // limits); reset so the user can retry or click the toolbar icon.2594      setTimeout(() => {2595        if (openBtn.isConnected) {2596          openBtn.textContent = "Open Peach to unlock";2597          openBtn.disabled = false;2598        }2599      }, 2500);2600    });26012602    wrap.append(head, sub, openBtn);2603    container.appendChild(wrap);2604  }26052606  function handleKeyDown(e: KeyboardEvent) {2607    if (options.locked) {2608      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2609      return;2610    }2611    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2612      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2613      return;2614    }2615    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2616    const count = allEntryEls.length;2617    if (document.activeElement === searchInput) {2618      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2619      if (count === 0) return;2620      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2621    }2622    if (count === 0) return;2623    switch (e.key) {2624      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2625      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2626      case "Enter": {2627        if (focusedIndex >= 0) {2628          const el = allEntryEls[focusedIndex] as HTMLElement;2629          const id = el.dataset.id;2630          if (id) { onSelect(id); dismiss(); }2631          else if (el.classList.contains("is-new") || !id) {2632            // "New entry" row (last item, no data-id)2633            showCreateForm();2634          }2635        }2636        break;2637      }2638      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2639    }2640  }26412642  document.addEventListener("keydown", handleKeyDown);26432644  // Type-to-search from the silver platter. A printable single-character2645  // keystroke (no modifier) seeds the search query and switches into the2646  // list view, so the user can pivot to a different entry without first2647  // clicking the search icon. Capture phase so the anchor input does not2648  // receive the character before we hijack it.2649  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2650    if (currentMode !== "silver-platter") return;2651    if (e.ctrlKey || e.metaKey || e.altKey) return;2652    if (e.key.length !== 1) return;2653    e.preventDefault();2654    e.stopImmediatePropagation();2655    query = e.key;2656    renderList();2657  };2658  document.addEventListener("keydown", silverPlatterTypeHandler, true);2659  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));26602661  (modalAncestor ?? document.body).appendChild(host);26622663  function updatePosition() {2664    const r = anchorEl.getBoundingClientRect();2665    host.style.top = `${r.bottom + (modalAncestor ? 0 : window.scrollY) + 5}px`;2666    host.style.left = `${r.left + (modalAncestor ? 0 : window.scrollX)}px`;2667    host.style.width = `${popupWidth}px`;2668  }2669  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26702671  if (options.locked) {2672    renderLocked();2673  } else if (options.isSignup && options.savedIdentities) {2674    // State 10: identity helper — signup form detected, show derived2675    // identity list (emails then usernames) instead of vault entry list.2676    renderIdentityHelper();2677  } else if (entries.length === 1 && !options.isSignup) {2678    // Silver platter (State 1): single domain match → focused fill view.2679    // Multi-match goes through renderList instead.2680    renderSilverPlatter(entries[0]!);2681  } else {2682    renderList();2683  }26842685  let exitScheduled = false;2686  function dismiss(userAction = false) {2687    // Idempotent: dismiss() can be called from multiple paths (Escape,2688    // outside click, entry select, fill success, host page nav). The exit2689    // animation must only play once and host.remove() must run exactly once.2690    if (exitScheduled) return;2691    exitScheduled = true;2692    // Detach listeners synchronously so nothing can re-trigger during the2693    // 130ms exit window (a focusin firing here would race against the2694    // dismiss-lock work in Pass 2).2695    stopObserving();2696    document.removeEventListener("click", outsideClick, { capture: true });2697    document.removeEventListener("keydown", handleKeyDown);2698    for (const cleanup of cleanupHooks) {2699      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2700    }2701    if (userAction) options.onDismiss?.();2702    container.classList.add("is-exiting");2703    setTimeout(() => host.remove(), 130);2704  }27052706  function outsideClick(ev: MouseEvent) {2707    const path = ev.composedPath();2708    // Never dismiss when clicking the anchor field itself — that click is2709    // what triggered the selector to open, and the user may click the field2710    // again to re-focus it without intending to close the selector.2711    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2712  }2713  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2714  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);27152716  return dismiss;2717}27182719export function showTOTPSelector(2720  anchorEl: HTMLInputElement,2721  entries: SelectorEntry[],2722  onFill: (id: string) => void,2723  options: { domain?: string; onDismiss?: () => void } = {}2724): () => void {2725  const host = document.createElement("div");2726  host.style.cssText = "position: absolute; z-index: 2147483647;";2727  host.style.setProperty("--peach-accent", accentHex);2728  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2729  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2730  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2731  const shadow = host.attachShadow({ mode: "closed" });27322733  const style = shadow.appendChild(document.createElement("style"));2734  style.textContent = SELECTOR_STYLES;27352736  const rect = anchorEl.getBoundingClientRect();2737  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2738  host.style.left = `${rect.left + window.scrollX}px`;2739  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2740  host.style.width = `${popupWidth}px`;27412742  const container = shadow.appendChild(document.createElement("div"));2743  container.className = "peach-inline-popup";2744  container.setAttribute("data-theme", popupTheme);27452746  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2747  const current = entries.filter((entry) => entry.hasTotp);2748  let focusedIndex = current.length === 1 ? 0 : -1;27492750  function updatePosition() {2751    const r = anchorEl.getBoundingClientRect();2752    host.style.top = `${r.bottom + window.scrollY + 5}px`;2753    host.style.left = `${r.left + window.scrollX}px`;2754    host.style.width = `${popupWidth}px`;2755  }27562757  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27582759  function choose(entry: SelectorEntry) {2760    onFill(entry.id);2761    dismiss();2762  }27632764  function render() {2765    container.innerHTML = "";27662767    const domHdr = document.createElement("div");2768    domHdr.className = "domain-header";2769    const headText = document.createElement("div");2770    headText.className = "domain-header-text";2771    const eyebrow = document.createElement("div");2772    eyebrow.className = "domain-eyebrow";2773    eyebrow.textContent = "2FA code";2774    const domName = document.createElement("div");2775    domName.className = "domain-name";2776    domName.textContent = domain;2777    headText.append(eyebrow, domName);2778    domHdr.appendChild(headText);2779    container.appendChild(domHdr);27802781    if (current.length === 1) {2782      const entry = current[0]!;2783      const platter = document.createElement("div");2784      platter.className = "silver-platter";27852786      const title = document.createElement("div");2787      title.className = "sp-title";2788      title.textContent = entry.title;2789      platter.appendChild(title);27902791      const sub = document.createElement("div");2792      sub.className = "sp-username";2793      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2794      platter.appendChild(sub);27952796      const fill = document.createElement("button");2797      fill.className = "sp-fill-btn";2798      fill.type = "button";2799      fill.textContent = "Fill 2FA code";2800      fill.addEventListener("click", () => choose(entry));2801      platter.appendChild(fill);28022803      container.appendChild(platter);2804      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2805      return;2806    }28072808    const results = document.createElement("div");2809    results.className = "results";2810    container.appendChild(results);28112812    for (let i = 0; i < current.length; i++) {2813      const entry = current[i]!;2814      const row = document.createElement("div");2815      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2816      row.dataset.index = String(i);2817      row.setAttribute("tabindex", "-1");28182819      const icon = document.createElement("div");2820      icon.className = "entry-icon";2821      icon.innerHTML = keySvgStr();2822      row.appendChild(icon);2823      const info = document.createElement("div");2824      info.className = "entry-info";2825      const title = document.createElement("div");2826      title.className = "entry-title";2827      title.textContent = entry.title;2828      const sub = document.createElement("div");2829      sub.className = "entry-sub";2830      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2831      info.append(title, sub);2832      row.appendChild(info);28332834      const badge = document.createElement("span");2835      badge.className = "totp-badge";2836      badge.textContent = "Fill";2837      row.appendChild(badge);2838      row.addEventListener("click", () => choose(entry));2839      results.appendChild(row);2840    }2841  }28422843  function setFocused(index: number) {2844    focusedIndex = index;2845    container.querySelectorAll(".entry").forEach((el, i) => {2846      el.classList.toggle("focused", i === focusedIndex);2847      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2848    });2849  }28502851  function handleKeyDown(e: KeyboardEvent) {2852    if (e.key === "Escape" || e.key === "Tab") {2853      e.preventDefault();2854      dismiss(true);2855      return;2856    }2857    if (current.length === 0) return;2858    if (e.key === "Enter") {2859      e.preventDefault();2860      choose(current[Math.max(0, focusedIndex)]!);2861      return;2862    }2863    if (current.length === 1) return;2864    if (e.key === "ArrowDown") {2865      e.preventDefault();2866      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2867    } else if (e.key === "ArrowUp") {2868      e.preventDefault();2869      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2870    }2871  }28722873  let exitScheduled = false;2874  function dismiss(userAction = false) {2875    if (exitScheduled) return;2876    exitScheduled = true;2877    stopObserving();2878    document.removeEventListener("click", outsideClick, { capture: true });2879    document.removeEventListener("keydown", handleKeyDown);2880    if (userAction) options.onDismiss?.();2881    container.classList.add("is-exiting");2882    setTimeout(() => host.remove(), 130);2883  }28842885  function outsideClick(ev: MouseEvent) {2886    const path = ev.composedPath();2887    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2888  }28892890  document.addEventListener("keydown", handleKeyDown);2891  document.body.appendChild(host);2892  render();2893  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);28942895  return dismiss;2896}28972898export interface CardSelectorEntry {2899  id: string;2900  title: string;2901  cardholderName?: string;2902  last4?: string;2903  expMonth?: string;2904  expYear?: string;2905  network?: import("../shared/types").CardNetwork;2906}29072908interface CardSelectorOptions {2909  domain?: string;2910  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2911  onFill: (entry: import("../shared/types").VaultEntry) => void;2912  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2913  onDismiss?: () => void;2914}29152916/**2917 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2918 * passkey create or get. Renders as a fixed-position floating popup (no2919 * field anchor needed — passkeys don't require a focused input). Uses the2920 * same theme tokens and entrance animation as all other inline popup states.2921 */2922export function showPasskeyProGate(): void {2923  const domain = location.hostname.replace(/^www\./, "");29242925  const host = document.createElement("div");2926  host.setAttribute("data-peach-passkey-gate", "1");2927  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2928  const shadow = host.attachShadow({ mode: "closed" });29292930  const style = document.createElement("style");2931  style.textContent = `2932    :host { all: initial; }2933    .gate-wrap {2934      position: fixed;2935      top: 50%;2936      left: 50%;2937      transform: translate(-50%, -50%);2938      width: 280px;2939      pointer-events: auto;2940      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2941    }2942    @keyframes g-in {2943      from { opacity:0; transform: translate(-50%,-52%); }2944      to   { opacity:1; transform: translate(-50%,-50%); }2945    }2946    .gate-wrap.is-exiting {2947      animation: g-out 130ms ease-in forwards;2948    }2949    @keyframes g-out {2950      to { opacity:0; transform: translate(-50%,-52%); }2951    }2952    .gate {2953      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2954      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2955      border-radius: 12px;2956      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2957      padding: 16px;2958      font-family: Inter, sans-serif;2959    }2960    .gate-header {2961      display: flex;2962      align-items: center;2963      gap: 7px;2964      margin-bottom: 12px;2965      padding-bottom: 10px;2966      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2967    }2968    .gate-domain {2969      font-size: 12px;2970      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2971      font-family: "IBM Plex Mono", monospace;2972      overflow: hidden;2973      text-overflow: ellipsis;2974      white-space: nowrap;2975    }2976    .gate-title {2977      font-size: 14px;2978      font-weight: 500;2979      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2980      margin-bottom: 6px;2981    }2982    .gate-subtitle {2983      font-size: 12px;2984      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2985      line-height: 1.5;2986      margin-bottom: 14px;2987    }2988    .gate-btn {2989      display: block;2990      width: 100%;2991      padding: 9px 0;2992      border-radius: 8px;2993      border: none;2994      cursor: pointer;2995      font-size: 13px;2996      font-family: Inter, sans-serif;2997      font-weight: 500;2998      transition: opacity 100ms;2999      margin-bottom: 7px;3000      text-align: center;3001    }3002    .gate-btn:last-child { margin-bottom: 0; }3003    .gate-btn--accent {3004      background: ${accentHex};3005      color: #fff;3006    }3007    .gate-btn--accent:hover { opacity: 0.88; }3008    .gate-btn--ghost {3009      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3010      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3011    }3012    .gate-btn--ghost:hover { opacity: 0.75; }3013    .backdrop {3014      position: fixed;3015      inset: 0;3016      pointer-events: auto;3017    }3018  `;3019  shadow.appendChild(style);30203021  const backdrop = document.createElement("div");3022  backdrop.className = "backdrop";3023  shadow.appendChild(backdrop);30243025  const wrap = document.createElement("div");3026  wrap.className = "gate-wrap";3027  shadow.appendChild(wrap);30283029  const gate = document.createElement("div");3030  gate.className = "gate";3031  wrap.appendChild(gate);30323033  // Header: peach icon + domain3034  const header = document.createElement("div");3035  header.className = "gate-header";3036  const icon = document.createElement("span");3037  icon.innerHTML = peachIconSvg();3038  const domainEl = document.createElement("span");3039  domainEl.className = "gate-domain";3040  domainEl.textContent = domain;3041  header.append(icon, domainEl);3042  gate.appendChild(header);30433044  const title = document.createElement("div");3045  title.className = "gate-title";3046  title.textContent = "Passkeys are part of Peach Pro.";3047  gate.appendChild(title);30483049  const subtitle = document.createElement("div");3050  subtitle.className = "gate-subtitle";3051  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3052  gate.appendChild(subtitle);30533054  const upgradeBtn = document.createElement("button");3055  upgradeBtn.className = "gate-btn gate-btn--accent";3056  upgradeBtn.type = "button";3057  upgradeBtn.textContent = "Upgrade to Pro";3058  gate.appendChild(upgradeBtn);30593060  const laterBtn = document.createElement("button");3061  laterBtn.className = "gate-btn gate-btn--ghost";3062  laterBtn.type = "button";3063  laterBtn.textContent = "Not right now";3064  gate.appendChild(laterBtn);30653066  function dismiss() {3067    wrap.classList.add("is-exiting");3068    setTimeout(() => host.remove(), 130);3069  }30703071  upgradeBtn.addEventListener("click", () => {3072    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3073    dismiss();3074  });3075  laterBtn.addEventListener("click", dismiss);3076  backdrop.addEventListener("click", dismiss);30773078  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3079    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3080  });30813082  document.body.appendChild(host);3083}30843085/**3086 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3087 * detector sees the page invoke navigator.credentials.create(); content/index.ts3088 * checks vault + decline state then calls this. "Save passkey to Peach"3089 * initiates the popup-context credential flow; "Not now" records a 30-day3090 * decline for the domain so we don't re-show on every page reload.3091 */3092export function showPasskeyRegistrationOffer(args: {3093  rpId: string;3094  rpName?: string;3095  userName?: string;3096  userDisplayName?: string;3097}): void {3098  const domain = location.hostname.replace(/^www\./, "");3099  const displayName = args.rpName || domain;31003101  const host = document.createElement("div");3102  host.setAttribute("data-peach-passkey-offer", "1");3103  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3104  const shadow = host.attachShadow({ mode: "closed" });31053106  const style = document.createElement("style");3107  style.textContent = `3108    :host { all: initial; }3109    .offer-wrap {3110      position: fixed;3111      top: 16px;3112      right: 16px;3113      width: 320px;3114      pointer-events: auto;3115      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3116    }3117    @keyframes o-in {3118      from { opacity: 0; transform: translateY(-6px); }3119      to   { opacity: 1; transform: translateY(0); }3120    }3121    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3122    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3123    .offer {3124      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3125      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3126      border-radius: 12px;3127      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3128      padding: 14px 14px 12px;3129      font-family: Inter, sans-serif;3130      position: relative;3131    }3132    .offer-close {3133      position: absolute;3134      top: 8px;3135      right: 8px;3136      width: 18px;3137      height: 18px;3138      border: none;3139      background: transparent;3140      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3141      cursor: pointer;3142      font-size: 14px;3143      line-height: 1;3144      padding: 0;3145    }3146    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3147    .offer-header {3148      display: flex;3149      align-items: center;3150      gap: 7px;3151      margin-bottom: 8px;3152      padding-bottom: 8px;3153      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3154    }3155    .offer-domain {3156      font-size: 12px;3157      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3158      font-family: "IBM Plex Mono", monospace;3159      overflow: hidden;3160      text-overflow: ellipsis;3161      white-space: nowrap;3162    }3163    .offer-title {3164      font-size: 13px;3165      font-weight: 500;3166      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3167      margin-bottom: 4px;3168    }3169    .offer-subtitle {3170      font-size: 11px;3171      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3172      line-height: 1.45;3173      margin-bottom: 12px;3174    }3175    .offer-btn {3176      display: block;3177      width: 100%;3178      padding: 8px 0;3179      border-radius: 7px;3180      border: none;3181      cursor: pointer;3182      font-size: 12px;3183      font-family: Inter, sans-serif;3184      font-weight: 500;3185      transition: opacity 100ms;3186      margin-bottom: 6px;3187      text-align: center;3188    }3189    .offer-btn:last-child { margin-bottom: 0; }3190    .offer-btn--accent { background: ${accentHex}; color: #fff; }3191    .offer-btn--accent:hover { opacity: 0.88; }3192    .offer-btn--ghost {3193      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3194      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3195    }3196    .offer-btn--ghost:hover { opacity: 0.75; }3197  `;3198  shadow.appendChild(style);31993200  const wrap = document.createElement("div");3201  wrap.className = "offer-wrap";3202  shadow.appendChild(wrap);32033204  const offer = document.createElement("div");3205  offer.className = "offer";3206  wrap.appendChild(offer);32073208  const closeBtn = document.createElement("button");3209  closeBtn.className = "offer-close";3210  closeBtn.type = "button";3211  closeBtn.setAttribute("aria-label", "Dismiss");3212  closeBtn.textContent = "✕";3213  offer.appendChild(closeBtn);32143215  const header = document.createElement("div");3216  header.className = "offer-header";3217  const icon = document.createElement("span");3218  icon.innerHTML = peachIconSvg();3219  const domainEl = document.createElement("span");3220  domainEl.className = "offer-domain";3221  domainEl.textContent = domain;3222  header.append(icon, domainEl);3223  offer.appendChild(header);32243225  const title = document.createElement("div");3226  title.className = "offer-title";3227  title.textContent = "This site supports passkeys.";3228  offer.appendChild(title);32293230  const subtitle = document.createElement("div");3231  subtitle.className = "offer-subtitle";3232  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3233  offer.appendChild(subtitle);32343235  const saveBtn = document.createElement("button");3236  saveBtn.className = "offer-btn offer-btn--accent";3237  saveBtn.type = "button";3238  saveBtn.textContent = "Save passkey to Peach";3239  offer.appendChild(saveBtn);32403241  const laterBtn = document.createElement("button");3242  laterBtn.className = "offer-btn offer-btn--ghost";3243  laterBtn.type = "button";3244  laterBtn.textContent = "Not now";3245  offer.appendChild(laterBtn);32463247  function dismiss(decline: boolean) {3248    if (decline) {3249      chrome.runtime.sendMessage({3250        type: "PASSKEY_OFFER_DECLINE",3251        payload: { domain },3252      }).catch(() => {});3253    }3254    wrap.classList.add("is-exiting");3255    setTimeout(() => host.remove(), 130);3256  }32573258  saveBtn.addEventListener("click", () => {3259    chrome.runtime.sendMessage({3260      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3261      payload: {3262        rpId: args.rpId,3263        rpName: args.rpName ?? displayName,3264        userName: args.userName ?? "user",3265        userDisplayName: args.userDisplayName,3266      },3267    }).catch(() => {});3268    dismiss(false);3269  });3270  laterBtn.addEventListener("click", () => dismiss(true));3271  closeBtn.addEventListener("click", () => dismiss(true));32723273  document.body.appendChild(host);3274}32753276/**3277 * State 11 — passkey available indicator. Shown when the user lands on a3278 * domain for which they already have a stored passkey. Tells them where to3279 * find it (the entry already shows in the vault list); the "Sign in with3280 * passkey" button opens the popup so they can use the platform authenticator3281 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3282 * the actual sign-in transparently, so this banner is informational only.3283 */3284export function showPasskeyAvailable(args: {3285  rpId: string;3286  userName: string;3287  fromBrowser?: "chrome" | "firefox";3288  currentBrowser?: "chrome" | "firefox" | "unknown";3289}): void {3290  const domain = location.hostname.replace(/^www\./, "");3291  const crossBrowser =3292    args.fromBrowser &&3293    args.currentBrowser &&3294    args.currentBrowser !== "unknown" &&3295    args.fromBrowser !== args.currentBrowser;32963297  const host = document.createElement("div");3298  host.setAttribute("data-peach-passkey-available", "1");3299  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3300  const shadow = host.attachShadow({ mode: "closed" });33013302  const style = document.createElement("style");3303  style.textContent = `3304    :host { all: initial; }3305    .avail-wrap {3306      position: fixed;3307      top: 16px;3308      right: 16px;3309      width: 320px;3310      pointer-events: auto;3311      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3312    }3313    @keyframes a-in {3314      from { opacity: 0; transform: translateY(-6px); }3315      to   { opacity: 1; transform: translateY(0); }3316    }3317    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3318    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3319    .avail {3320      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3321      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3322      border-radius: 12px;3323      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3324      padding: 14px 14px 12px;3325      font-family: Inter, sans-serif;3326      position: relative;3327    }3328    .avail-close {3329      position: absolute;3330      top: 8px;3331      right: 8px;3332      width: 18px;3333      height: 18px;3334      border: none;3335      background: transparent;3336      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3337      cursor: pointer;3338      font-size: 14px;3339      line-height: 1;3340      padding: 0;3341    }3342    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3343    .avail-header {3344      display: flex;3345      align-items: center;3346      gap: 7px;3347      margin-bottom: 8px;3348      padding-bottom: 8px;3349      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3350    }3351    .avail-domain {3352      font-size: 12px;3353      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3354      font-family: "IBM Plex Mono", monospace;3355    }3356    .avail-label {3357      font-size: 9px;3358      letter-spacing: 0.16em;3359      text-transform: uppercase;3360      color: ${accentHex};3361      margin-bottom: 4px;3362    }3363    .avail-user {3364      font-size: 13px;3365      font-weight: 500;3366      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3367      margin-bottom: 12px;3368      overflow: hidden;3369      text-overflow: ellipsis;3370      white-space: nowrap;3371    }3372    .avail-cross {3373      font-size: 11px;3374      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3375      line-height: 1.45;3376      margin-bottom: 12px;3377      padding: 8px;3378      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3379      border-radius: 6px;3380    }3381    .avail-btn {3382      display: block;3383      width: 100%;3384      padding: 8px 0;3385      border-radius: 7px;3386      border: none;3387      cursor: pointer;3388      font-size: 12px;3389      font-family: Inter, sans-serif;3390      font-weight: 500;3391      transition: opacity 100ms;3392      margin-bottom: 6px;3393      text-align: center;3394    }3395    .avail-btn:last-child { margin-bottom: 0; }3396    .avail-btn--accent { background: ${accentHex}; color: #fff; }3397    .avail-btn--accent:hover { opacity: 0.88; }3398    .avail-btn--ghost {3399      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3400      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3401    }3402    .avail-btn--ghost:hover { opacity: 0.75; }3403  `;3404  shadow.appendChild(style);34053406  const wrap = document.createElement("div");3407  wrap.className = "avail-wrap";3408  shadow.appendChild(wrap);34093410  const avail = document.createElement("div");3411  avail.className = "avail";3412  wrap.appendChild(avail);34133414  const closeBtn = document.createElement("button");3415  closeBtn.className = "avail-close";3416  closeBtn.type = "button";3417  closeBtn.setAttribute("aria-label", "Dismiss");3418  closeBtn.textContent = "✕";3419  avail.appendChild(closeBtn);34203421  const header = document.createElement("div");3422  header.className = "avail-header";3423  const icon = document.createElement("span");3424  icon.innerHTML = peachIconSvg();3425  const domainEl = document.createElement("span");3426  domainEl.className = "avail-domain";3427  domainEl.textContent = domain;3428  header.append(icon, domainEl);3429  avail.appendChild(header);34303431  const label = document.createElement("div");3432  label.className = "avail-label";3433  label.textContent = "PASSKEY";3434  avail.appendChild(label);34353436  const user = document.createElement("div");3437  user.className = "avail-user";3438  user.textContent = args.userName;3439  avail.appendChild(user);34403441  if (crossBrowser) {3442    const cross = document.createElement("div");3443    cross.className = "avail-cross";3444    cross.textContent =3445      args.fromBrowser === "chrome"3446        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3447        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3448    avail.appendChild(cross);3449  }34503451  const signInBtn = document.createElement("button");3452  signInBtn.className = "avail-btn avail-btn--accent";3453  signInBtn.type = "button";3454  signInBtn.textContent = "Sign in with passkey";3455  avail.appendChild(signInBtn);34563457  const passwordBtn = document.createElement("button");3458  passwordBtn.className = "avail-btn avail-btn--ghost";3459  passwordBtn.type = "button";3460  passwordBtn.textContent = "Use password instead";3461  avail.appendChild(passwordBtn);34623463  function dismiss() {3464    wrap.classList.add("is-exiting");3465    setTimeout(() => host.remove(), 130);3466  }34673468  signInBtn.addEventListener("click", () => {3469    // On Chrome: the user clicking the page's own Sign-in button is what3470    //   triggers webAuthenticationProxy → existing background flow handles it.3471    //   Our button just dismisses since the page itself drives auth.3472    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3473    //   and surface the entry for manual reference (popup view).3474    dismiss();3475    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3476  });3477  passwordBtn.addEventListener("click", dismiss);3478  closeBtn.addEventListener("click", dismiss);34793480  document.body.appendChild(host);3481}34823483/**3484 * State 7 — card silver platter. Single-card focused fill view rendered3485 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3486 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3487 * so card and login flows render identically. Multi-card list view is a3488 * follow-up; today this picks the first card.3489 */3490export function showCardSelector(3491  anchorEl: HTMLInputElement,3492  cards: CardSelectorEntry[],3493  options: CardSelectorOptions3494): () => void {3495  if (cards.length === 0) return () => {};3496  const card = cards[0]!;34973498  const host = document.createElement("div");3499  host.style.cssText = "position: absolute; z-index: 2147483647;";3500  host.style.setProperty("--peach-accent", accentHex);3501  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3502  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3503  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3504  const shadow = host.attachShadow({ mode: "closed" });35053506  const style = shadow.appendChild(document.createElement("style"));3507  style.textContent = SELECTOR_STYLES;35083509  const rect = anchorEl.getBoundingClientRect();3510  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3511  host.style.left = `${rect.left + window.scrollX}px`;3512  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;35133514  const container = shadow.appendChild(document.createElement("div"));3515  container.className = "peach-inline-popup";3516  container.setAttribute("data-theme", popupTheme);35173518  // Domain header — eyebrow communicates the card context, not the site3519  const domHdr = document.createElement("div");3520  domHdr.className = "domain-header";3521  const eyebrow = document.createElement("div");3522  eyebrow.className = "domain-eyebrow";3523  eyebrow.textContent = "Pay with Peach";3524  const domName = document.createElement("div");3525  domName.className = "domain-name";3526  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3527  domHdr.append(eyebrow, domName);3528  container.appendChild(domHdr);35293530  const platter = document.createElement("div");3531  platter.className = "card-platter";35323533  if (card.network && card.network !== "unknown") {3534    const net = document.createElement("div");3535    net.className = "cp-network";3536    net.textContent = card.network;3537    platter.appendChild(net);3538  }35393540  const nick = document.createElement("div");3541  nick.className = "cp-nickname";3542  nick.textContent = card.title;3543  platter.appendChild(nick);35443545  if (card.last4) {3546    const l4 = document.createElement("div");3547    l4.className = "cp-last4";3548    l4.textContent = `•••• ${card.last4}`;3549    platter.appendChild(l4);3550  }35513552  const meta = document.createElement("div");3553  meta.className = "cp-meta";3554  if (card.cardholderName) {3555    const name = document.createElement("span");3556    name.textContent = card.cardholderName;3557    meta.appendChild(name);3558  }3559  if (card.expMonth && card.expYear) {3560    if (card.cardholderName) {3561      const sep = document.createElement("span");3562      sep.className = "cp-meta-sep";3563      sep.textContent = "·";3564      meta.appendChild(sep);3565    }3566    const exp = document.createElement("span");3567    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3568    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3569    meta.appendChild(exp);3570  }3571  if (meta.childElementCount > 0) platter.appendChild(meta);35723573  const fillWrap = document.createElement("div");3574  fillWrap.className = "cp-fill-wrap";3575  const fillBtn = document.createElement("button");3576  fillBtn.className = "sp-fill-btn";3577  fillBtn.type = "button";3578  fillBtn.textContent = "Fill card details";3579  fillBtn.addEventListener("click", async () => {3580    if (fillBtn.disabled) return;3581    fillBtn.disabled = true;3582    fillBtn.classList.add("filled");3583    fillBtn.innerHTML = checkSvgStr();3584    const resp = await chrome.runtime.sendMessage({3585      type: "GET_ENTRY_FOR_FILL",3586      payload: { id: card.id },3587    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3588    if (resp?.ok && resp.data) options.onFill(resp.data);3589    setTimeout(() => dismiss(), 400);3590  });3591  fillWrap.appendChild(fillBtn);3592  platter.appendChild(fillWrap);35933594  // Secondary actions — copy number, copy CVC, dismiss3595  const actions = document.createElement("div");3596  actions.className = "sp-actions";35973598  function flashBtn(b: HTMLButtonElement) {3599    b.classList.add("flashed");3600    setTimeout(() => b.classList.remove("flashed"), 700);3601  }36023603  // M3/QUA-005: clipboard + background COPY both failed — show user.3604  function flashCopyError(b: HTMLButtonElement) {3605    const original = b.textContent ?? "";3606    b.textContent = "Blocked";3607    b.classList.add("flashed");3608    setTimeout(() => {3609      b.classList.remove("flashed");3610      if (b.isConnected) b.textContent = original;3611    }, 1200);3612  }36133614  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3615    const resp = await chrome.runtime.sendMessage({3616      type: "GET_ENTRY_FOR_FILL",3617      payload: { id: card.id },3618    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3619    return resp?.ok && resp.data ? resp.data : null;3620  }36213622  const copyNum = document.createElement("button");3623  copyNum.className = "sp-action-btn";3624  copyNum.type = "button";3625  copyNum.title = "Copy card number";3626  copyNum.textContent = "Copy number";3627  copyNum.addEventListener("click", async (e) => {3628    e.stopPropagation();3629    const full = await fetchFullCard();3630    if (!full?.cardNumber) return;3631    let alreadyWritten = false;3632    try {3633      await navigator.clipboard.writeText(full.cardNumber);3634      alreadyWritten = true;3635    } catch (err) {3636      console.warn("[Peach] clipboard write denied:", err);3637    }3638    const resp = await chrome.runtime.sendMessage({3639      type: "COPY",3640      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3641    }).catch(() => null) as { ok?: boolean } | null;3642    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3643    else flashCopyError(copyNum);3644  });3645  actions.appendChild(copyNum);36463647  const copyCvc = document.createElement("button");3648  copyCvc.className = "sp-action-btn";3649  copyCvc.type = "button";3650  copyCvc.title = "Copy CVC";3651  copyCvc.textContent = "Copy CVC";3652  copyCvc.addEventListener("click", async (e) => {3653    e.stopPropagation();3654    const full = await fetchFullCard();3655    if (!full?.cvc) return;3656    let alreadyWritten = false;3657    try {3658      await navigator.clipboard.writeText(full.cvc);3659      alreadyWritten = true;3660    } catch (err) {3661      console.warn("[Peach] clipboard write denied:", err);3662    }3663    const resp = await chrome.runtime.sendMessage({3664      type: "COPY",3665      payload: { text: full.cvc, label: "CVC", alreadyWritten },3666    }).catch(() => null) as { ok?: boolean } | null;3667    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3668    else flashCopyError(copyCvc);3669  });3670  actions.appendChild(copyCvc);36713672  const closeBtn = document.createElement("button");3673  closeBtn.className = "sp-action-btn";3674  closeBtn.type = "button";3675  closeBtn.title = "Dismiss";3676  closeBtn.textContent = "✕";3677  closeBtn.addEventListener("click", (e) => {3678    e.stopPropagation();3679    dismiss(true);3680  });3681  actions.appendChild(closeBtn);36823683  platter.appendChild(actions);3684  container.appendChild(platter);36853686  document.body.appendChild(host);3687  function updatePosition() {3688    const r = anchorEl.getBoundingClientRect();3689    host.style.top = `${r.bottom + window.scrollY + 5}px`;3690    host.style.left = `${r.left + window.scrollX}px`;3691  }3692  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);36933694  function onKeyDown(e: KeyboardEvent) {3695    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3696  }3697  document.addEventListener("keydown", onKeyDown);36983699  let exitScheduled = false;3700  function dismiss(userAction = false) {3701    if (exitScheduled) return;3702    exitScheduled = true;3703    stopObserving();3704    document.removeEventListener("click", outsideClick, { capture: true });3705    document.removeEventListener("keydown", onKeyDown);3706    if (userAction) options.onDismiss?.();3707    container.classList.add("is-exiting");3708    setTimeout(() => host.remove(), 130);3709  }37103711  function outsideClick(ev: MouseEvent) {3712    const path = ev.composedPath();3713    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3714  }3715  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);37163717  return dismiss;3718}