inject.ts

149.2 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    // Hides the list and removes the document-level click watcher.1788    function hideList() {1789      list.style.display = "none";1790      document.removeEventListener("mousedown", onDocMousedown, { capture: true });1791    }17921793    // Dismiss list on any mousedown that originates outside the popup's shadow1794    // DOM. This is the ONLY close trigger for the list — blur is intentionally1795    // NOT used, because modal focus traps fire blur without a mousedown (they1796    // call element.focus() programmatically in response to focusin/focusout),1797    // which caused the list to vanish before the user could pick from it.1798    function onDocMousedown(e: MouseEvent) {1799      if (e.composedPath().includes(host)) return;1800      hideList();1801    }18021803    function pick(value: string) {1804      inp.value = value;1805      hideList();1806      suppressNextFocus = true;1807      inp.focus();1808      // If a focus trap intercepts inp.focus() and redirects to anchorEl before1809      // inp ever fires its focus event, suppressNextFocus would strand the user.1810      // Clear after a short window so subsequent clicks still work.1811      setTimeout(() => { suppressNextFocus = false; }, 120);1812    }18131814    function render() {1815      const q = inp.value.toLowerCase();1816      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1817      rows.innerHTML = "";1818      if (!filtered.length) { hideList(); return; }1819      for (const s of filtered) {1820        const row = rows.appendChild(document.createElement("button"));1821        row.type = "button"; row.className = "identity-suggest-row";1822        const val = row.appendChild(document.createElement("span"));1823        val.className = "identity-suggest-val"; val.textContent = s.value;1824        const meta = row.appendChild(document.createElement("span"));1825        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1826        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1827        row.addEventListener("keydown", (e) => {1828          if (e.key === "ArrowDown") {1829            e.preventDefault();1830            (row.nextElementSibling as HTMLElement | null)?.focus();1831          } else if (e.key === "ArrowUp") {1832            e.preventDefault();1833            const prev = row.previousElementSibling as HTMLElement | null;1834            if (prev) prev.focus();1835            else inp.focus();1836          } else if (e.key === "Enter" || e.key === " ") {1837            e.preventDefault();1838            pick(s.value);1839          } else if (e.key === "Escape") {1840            e.preventDefault();1841            hideList();1842            suppressNextFocus = true;1843            inp.focus();1844          }1845        });1846        // Row blur only fires during keyboard navigation (arrow keys / Tab).1847        // Focus traps don't produce row blur events since rows aren't focused1848        // when the trap fires; this handler is therefore trap-safe.1849        row.addEventListener("blur", (e) => {1850          const rt = (e as FocusEvent).relatedTarget as Node | null;1851          if (rt && (rt === inp || list.contains(rt))) return;1852          setTimeout(() => { hideList(); }, 150);1853        });1854      }1855      list.style.display = "";1856      // Register the close-on-outside-click watcher each time the list shows.1857      // addEventListener deduplicates identical (fn, options) pairs, so1858      // re-rendering on input events does not stack up listeners.1859      document.addEventListener("mousedown", onDocMousedown, { capture: true });1860    }18611862    inp.addEventListener("focus", () => {1863      if (suppressNextFocus) { suppressNextFocus = false; return; }1864      render();1865    });1866    inp.addEventListener("input", render);1867    inp.addEventListener("keydown", (e) => {1868      if (list.style.display === "none") return;1869      if (e.key === "ArrowDown" && !collapsed) {1870        e.preventDefault();1871        (rows.firstElementChild as HTMLElement | null)?.focus();1872      } else if (e.key === "Escape") {1873        e.preventDefault();1874        hideList();1875      } else if (e.key === "Tab") {1876        // Tab moves focus away intentionally — close the list.1877        hideList();1878      }1879    });1880    // No blur handler on inp. Blur fires for ANY focus movement including1881    // programmatic focus() calls from modal focus traps, which caused the list1882    // to close before the user could interact. The document mousedown listener1883    // (registered in render()) handles intentional click-outside dismissal,1884    // and the keydown handler above covers keyboard Tab/Escape.18851886    // Ensure the watcher is removed if the main popup is dismissed while the1887    // list is visible.1888    cleanupHooks.push(hideList);1889  }18901891  async function showCreateForm() {1892    currentMode = "create";1893    container.innerHTML = "";18941895    // Guard: the service worker may lock the vault between when the selector1896    // opens and when the user clicks "New entry". Show the inline unlock form1897    // instead of silently failing on save.1898    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1899    if (!statusRes?.unlocked) {1900      renderLocked();1901      return;1902    }19031904    // Detect page password policy once for this form — reused on every1905    // regenerate click so the user always gets a compliant password.1906    const sitePolicy = detectPasswordPolicy();19071908    // Fetch identities on-demand — they're passed in signup context but not1909    // in login/search context where the user still clicks "New entry".1910    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1911    if (!formIdentities.length) {1912      try {1913        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1914        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1915      } catch { /* silent fallback */ }1916    }19171918    const wrap = document.createElement("div");1919    wrap.className = "create-form-wrap";19201921    // Header1922    const head = document.createElement("div"); head.className = "create-head";1923    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1924    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>`;1925    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1926    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1927    head.append(backBtn, lbl);19281929    // Body1930    const body = document.createElement("div"); body.className = "create-body";19311932    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1933      const g = document.createElement("div"); g.className = "f-group";1934      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1935      const inp = document.createElement("input"); inp.className = "f-input";1936      g.append(l, inp); return { g, inp };1937    }19381939    // Title1940    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1941    body.appendChild(tg.g);19421943    // URL1944    const ug = fGroup("website");1945    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1946    if (loginSubdomain) {1947      const h = document.createElement("div"); h.className = "url-hint";1948      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1949    }1950    body.appendChild(ug.g);19511952    // Username — pre-fill from anchor if it doesn't look like an email1953    const xg = fGroup("username");1954    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1955    xg.inp.placeholder = "johndoe";1956    xg.inp.setAttribute("autocomplete", "off");1957    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1958    body.appendChild(xg.g);19591960    // Email — pre-fill from anchor if it looks like an email1961    const eg = fGroup("email");1962    (eg.inp as HTMLInputElement).type = "email";1963    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1964    eg.inp.placeholder = "[email protected]";1965    eg.inp.setAttribute("autocomplete", "off");1966    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1967    body.appendChild(eg.g);19681969    // Password — full smart generator with charset pills + length slider +1970    // policy hint. Mirrors the main UI's compact generator so users get the1971    // same controls inline as in the popup.1972    const pg = fGroup("password");1973    pg.inp.remove(); // smartGen provides its own display — no separate input needed1974    let currentPassword = prePassword || "";1975    const smartGen = createSmartGenerator({1976      policy: sitePolicy,1977      initialPassword: prePassword || undefined,1978      onChange: (pw) => { currentPassword = pw; },1979    });1980    pg.g.appendChild(smartGen.root);1981    body.appendChild(pg.g);19821983    // Save1984    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1985    saveBtn.textContent = "Save entry";1986    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1987    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1988    saveBtn.addEventListener("click", async () => {1989      const title = tg.inp.value.trim();1990      const pw = currentPassword.trim();1991      const username = xg.inp.value.trim();1992      const email = eg.inp.value.trim();1993      if (!title) {1994        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1995        showFormError("Entry needs a title");1996        return;1997      }1998      if (!pw) {1999        showFormError("Entry needs a password — tap regen to make one");2000        return;2001      }2002      errEl.style.display = "none";2003      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2004      try {2005        const res = await chrome.runtime.sendMessage({2006          type: "ADD_ENTRY",2007          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2008        });2009        if ((res as { ok?: boolean }).ok) {2010          // Fill the detected form. onFillFields uses whichever identity the2011          // page anchored on — the vault captures both username and email.2012          options.onFillFields?.(username || email, pw);2013          showSuccess(title);2014        } else {2015          const errMsg = (res as { error?: string }).error === "vault locked"2016            ? "Vault locked — open Peach to save"2017            : "Could not save entry";2018          showFormError(errMsg);2019          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2020        }2021      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }2022    });2023    body.appendChild(saveBtn);2024    body.appendChild(errEl);20252026    wrap.append(head, body);2027    container.appendChild(wrap);2028    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2029  }20302031  function showSuccess(title: string) {2032    currentMode = "success";2033    container.innerHTML = "";2034    const wrap = document.createElement("div"); wrap.className = "success-wrap";2035    const ring = document.createElement("div"); ring.className = "success-ring";2036    ring.innerHTML = checkSvgStr();2037    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2038    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2039    wrap.append(ring, t, s);2040    container.appendChild(wrap);2041    setTimeout(() => dismiss(), 1600);2042  }20432044  function flashActionBtn(btn: HTMLButtonElement) {2045    btn.classList.add("flashed");2046    setTimeout(() => btn.classList.remove("flashed"), 700);2047  }20482049  // M3/QUA-005: when both the direct clipboard write and the background COPY2050  // fallback fail, briefly show the user that the copy did not happen.2051  function flashCopyError(btn: HTMLButtonElement) {2052    const original = btn.textContent ?? "";2053    btn.textContent = "Blocked";2054    btn.classList.add("flashed");2055    setTimeout(() => {2056      btn.classList.remove("flashed");2057      if (btn.isConnected) btn.textContent = original;2058    }, 1200);2059  }20602061  function renderSilverPlatter(entry: SelectorEntry) {2062    container.innerHTML = "";2063    searchInput = null;2064    focusedIndex = -1;2065    currentMode = "silver-platter";2066    silverPlatterOrigin = entry;20672068    const domHdr = document.createElement("div");2069    domHdr.className = "domain-header";2070    const headText = document.createElement("div");2071    headText.className = "domain-header-text";2072    const eyebrow = document.createElement("div");2073    eyebrow.className = "domain-eyebrow";2074    eyebrow.textContent = "Saved for this site";2075    const domName = document.createElement("div");2076    domName.className = "domain-name";2077    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2078    headText.append(eyebrow, domName);2079    domHdr.appendChild(headText);2080    if (!options.isSignup) {2081      const actions = document.createElement("div");2082      actions.className = "domain-header-actions";20832084      // Search shortcut — same idea as type-to-search below, but visible so2085      // the user can discover that another entry is reachable from a2086      // single-match platter. Sits to the left of the create button.2087      const searchBtn = document.createElement("button");2088      searchBtn.className = "domain-search-btn";2089      searchBtn.type = "button";2090      searchBtn.setAttribute("aria-label", "Search for a different entry");2091      searchBtn.title = "Search for a different entry";2092      searchBtn.innerHTML = searchSvgStr();2093      searchBtn.addEventListener("click", (e) => {2094        e.stopPropagation();2095        query = "";2096        renderList();2097      });2098      actions.appendChild(searchBtn);20992100      const addBtn = document.createElement("button");2101      addBtn.className = "domain-add-btn";2102      addBtn.type = "button";2103      addBtn.setAttribute("aria-label", "Create new entry");2104      addBtn.title = "Create new entry";2105      addBtn.textContent = "+";2106      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2107      actions.appendChild(addBtn);21082109      domHdr.appendChild(actions);2110    }2111    container.appendChild(domHdr);21122113    const platter = document.createElement("div");2114    platter.className = "silver-platter";21152116    const titleEl = document.createElement("div");2117    titleEl.className = "sp-title";2118    titleEl.textContent = entry.title;2119    platter.appendChild(titleEl);21202121    if (entry.email) {2122      const emailEl = document.createElement("div");2123      emailEl.className = "sp-identity-row";2124      const emailLbl = document.createElement("span");2125      emailLbl.className = "sp-identity-label";2126      emailLbl.textContent = "email";2127      const emailVal = document.createElement("span");2128      emailVal.className = "sp-username";2129      emailVal.textContent = entry.email;2130      emailEl.append(emailLbl, emailVal);2131      platter.appendChild(emailEl);2132    }21332134    if (entry.username) {2135      const userEl = document.createElement("div");2136      userEl.className = "sp-identity-row";2137      const userLbl = document.createElement("span");2138      userLbl.className = "sp-identity-label";2139      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2140      const userVal = document.createElement("span");2141      userVal.className = "sp-username";2142      userVal.textContent = entry.username;2143      userEl.append(userLbl, userVal);2144      platter.appendChild(userEl);2145    }21462147    const fillBtn = document.createElement("button");2148    fillBtn.className = "sp-fill-btn";2149    fillBtn.type = "button";2150    fillBtn.textContent = "Fill credentials";2151    fillBtn.addEventListener("click", () => {2152      if (fillBtn.disabled) return;2153      fillBtn.disabled = true;2154      fillBtn.classList.add("filled");2155      fillBtn.innerHTML = checkSvgStr();2156      // Fire the fill, then exit via the standard exit animation. The fill2157      // itself is async (handled in index.ts) — by 400ms the form is filled2158      // and the popup begins its exit. Total dwell from click to host2159      // removal: 400ms + 130ms (exit animation) = 530ms.2160      onSelect(entry.id);2161      setTimeout(() => dismiss(), 400);2162    });2163    platter.appendChild(fillBtn);21642165    const actionsGroup = document.createElement("div");2166    actionsGroup.className = "sp-actions-group";2167    const actionsLabel = document.createElement("div");2168    actionsLabel.className = "sp-actions-label";2169    actionsLabel.textContent = "Copy";2170    actionsGroup.appendChild(actionsLabel);21712172    const actions = document.createElement("div");2173    actions.className = "sp-actions";2174    actionsGroup.appendChild(actions);21752176    if (entry.email) {2177      const copyEmail = document.createElement("button");2178      copyEmail.className = "sp-action-btn";2179      copyEmail.type = "button";2180      copyEmail.title = "Copy email";2181      copyEmail.textContent = "Email";2182      copyEmail.addEventListener("click", async (e) => {2183        e.stopPropagation();2184        let alreadyWritten = false;2185        try {2186          await navigator.clipboard.writeText(entry.email!);2187          alreadyWritten = true;2188        } catch (err) {2189          console.warn("[Peach] clipboard write denied:", err);2190        }2191        const resp = await chrome.runtime.sendMessage({2192          type: "COPY",2193          payload: { text: entry.email, label: "Email", alreadyWritten },2194        }).catch(() => null) as { ok?: boolean } | null;2195        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2196        else flashCopyError(copyEmail);2197      });2198      actions.appendChild(copyEmail);2199    }22002201    const copyU = document.createElement("button");2202    copyU.className = "sp-action-btn";2203    copyU.type = "button";2204    const usernameIsEmail = entry.username?.includes("@") ?? false;2205    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2206    copyU.textContent = usernameIsEmail ? "Email" : "Username";2207    copyU.disabled = !entry.username;2208    copyU.addEventListener("click", async (e) => {2209      e.stopPropagation();2210      if (!entry.username) return;2211      let alreadyWritten = false;2212      try {2213        await navigator.clipboard.writeText(entry.username);2214        alreadyWritten = true;2215      } catch (err) {2216        console.warn("[Peach] clipboard write denied:", err);2217      }2218      const resp = await chrome.runtime.sendMessage({2219        type: "COPY",2220        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2221      }).catch(() => null) as { ok?: boolean } | null;2222      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2223      else flashCopyError(copyU);2224    });2225    actions.appendChild(copyU);22262227    const copyP = document.createElement("button");2228    copyP.className = "sp-action-btn";2229    copyP.type = "button";2230    copyP.title = "Copy password";2231    copyP.textContent = "Password";2232    copyP.addEventListener("click", async (e) => {2233      e.stopPropagation();2234      const resp = await chrome.runtime.sendMessage({2235        type: "GET_ENTRY_FOR_FILL",2236        payload: { id: entry.id },2237      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2238      if (!resp?.ok || !resp.data?.password) return;2239      let alreadyWritten = false;2240      try {2241        await navigator.clipboard.writeText(resp.data.password);2242        alreadyWritten = true;2243      } catch (err) {2244        console.warn("[Peach] clipboard write denied:", err);2245      }2246      const copyResp = await chrome.runtime.sendMessage({2247        type: "COPY",2248        payload: { text: resp.data.password, label: "Password", alreadyWritten },2249      }).catch(() => null) as { ok?: boolean } | null;2250      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2251      else flashCopyError(copyP);2252    });2253    actions.appendChild(copyP);22542255    let trayEl: HTMLDivElement | null = null;2256    let trayInterval: ReturnType<typeof setInterval> | null = null;22572258    function closeTray() {2259      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2260      trayEl?.remove();2261      trayEl = null;2262    }2263    // Register so dismiss() will close the tray and clear the interval2264    // even if the user dismisses without explicitly closing the tray.2265    cleanupHooks.push(closeTray);22662267    async function openTOTPTray() {2268      // Fetch the current TOTP code from the background. The raw base32 seed2269      // never enters the content script (SEV-3-C): we receive the live 6-digit2270      // code plus the seconds remaining, count down locally, and re-fetch a2271      // fresh code only when the 30s window rolls over.2272      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2273        const r = await chrome.runtime.sendMessage({2274          type: "GET_ENTRY_FOR_FILL",2275          payload: { id: entry.id },2276        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2277        if (!r?.ok || !r.data?.totpCode) return null;2278        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2279      }2280      let current = await fetchCode();2281      if (!current) return;22822283      trayEl = document.createElement("div");2284      trayEl.className = "sp-tray";22852286      const label = document.createElement("span");2287      label.className = "sp-tray-label";2288      label.textContent = "2FA";2289      trayEl.appendChild(label);22902291      const codeEl = document.createElement("div");2292      codeEl.className = "sp-totp-code";2293      trayEl.appendChild(codeEl);22942295      const ringNs = "http://www.w3.org/2000/svg";2296      const ring = document.createElementNS(ringNs, "svg");2297      ring.setAttribute("class", "sp-totp-ring");2298      ring.setAttribute("viewBox", "0 0 24 24");2299      const trackC = document.createElementNS(ringNs, "circle");2300      trackC.setAttribute("class", "ring-track");2301      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2302      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2303      const fillC = document.createElementNS(ringNs, "circle");2304      fillC.setAttribute("class", "ring-fill");2305      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2306      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2307      fillC.setAttribute("stroke-linecap", "round");2308      fillC.setAttribute("stroke-dasharray", "62.83");2309      ring.append(trackC, fillC);2310      trayEl.appendChild(ring);23112312      const copyBtn = document.createElement("button");2313      copyBtn.className = "sp-totp-copy";2314      copyBtn.type = "button";2315      copyBtn.textContent = "Copy";2316      trayEl.appendChild(copyBtn);23172318      function render() {2319        const { code, remaining } = current!;2320        // Group as "847 291" — easier to read than "847291"2321        codeEl.textContent = code.length === 62322          ? `${code.slice(0, 3)} ${code.slice(3)}`2323          : code;2324        // Ring fills counter-clockwise as time elapses: dashoffset goes from2325        // 0 (full ring) to 62.83 (empty) over the 30s window.2326        const fraction = (30 - remaining) / 30;2327        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2328      }2329      render();2330      trayInterval = setInterval(async () => {2331        if (!current) return;2332        current = { code: current.code, remaining: current.remaining - 1 };2333        // Window rolled over — pull a fresh code from the background.2334        if (current.remaining <= 0) {2335          const next = await fetchCode();2336          current = next ?? { code: current.code, remaining: 30 };2337        }2338        render();2339      }, 1000);23402341      copyBtn.addEventListener("click", async (e) => {2342        e.stopPropagation();2343        const code = current?.code;2344        if (!code) return;2345        let alreadyWritten = false;2346        try {2347          await navigator.clipboard.writeText(code);2348          alreadyWritten = true;2349        } catch (err) {2350          console.warn("[Peach] clipboard write denied:", err);2351        }2352        const resp = await chrome.runtime.sendMessage({2353          type: "COPY",2354          payload: { text: code, label: "TOTP", alreadyWritten },2355        }).catch(() => null) as { ok?: boolean } | null;2356        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2357        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2358      });23592360      platter.appendChild(trayEl);2361    }23622363    const editBtn = document.createElement("button");2364    editBtn.className = "sp-action-btn sp-action-edit";2365    editBtn.type = "button";2366    editBtn.title = "Edit entry";2367    editBtn.textContent = "Edit";2368    editBtn.addEventListener("click", (e) => {2369      e.stopPropagation();2370      closeTray();2371      void renderInlineEdit(entry);2372    });2373    actions.appendChild(editBtn);23742375    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2376    // "···" toggle was zero-savings (the toggle button took the same space2377    // the "2FA" label needed) and made the code one extra click away.2378    if (entry.hasTotp) void openTOTPTray();23792380    platter.appendChild(actionsGroup);2381    container.appendChild(platter);2382  }23832384  /**2385   * Inline-popup edit mode. Swaps the silver platter for an editable form2386   * over the same shadow-DOM surface so the user never leaves the page.2387   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2388   * with the new fields. Cancel returns without writing.2389   */2390  async function renderInlineEdit(summary: SelectorEntry) {2391    container.innerHTML = "";2392    const wrap = document.createElement("div");2393    wrap.className = "create-form-wrap";23942395    const head = document.createElement("div");2396    head.className = "create-head";2397    const back = document.createElement("button");2398    back.className = "back-btn";2399    back.type = "button";2400    back.title = "Cancel";2401    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>`;2402    back.addEventListener("click", () => renderSilverPlatter(summary));2403    head.appendChild(back);2404    const headLbl = document.createElement("div");2405    headLbl.className = "create-label";2406    headLbl.textContent = "Edit entry";2407    head.appendChild(headLbl);2408    wrap.appendChild(head);24092410    const body = document.createElement("div");2411    body.className = "create-body";24122413    // Loading shimmer while we fetch the full entry2414    const loading = document.createElement("div");2415    loading.className = "empty-hint";2416    loading.textContent = "loading…";2417    body.appendChild(loading);2418    wrap.appendChild(body);2419    container.appendChild(wrap);24202421    const [res, idRes] = await Promise.all([2422      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2423      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2424      chrome.runtime.sendMessage({2425        type: "GET_ENTRY_FOR_EDIT",2426        payload: { id: summary.id },2427      }).catch(() => null),2428      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2429    ]);2430    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2431    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];24322433    if (!entryRes || !entryRes.ok || !entryRes.data) {2434      loading.textContent = "couldn't load this entry. try again from the popup.";2435      return;2436    }2437    body.innerHTML = "";24382439    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2440      const group = document.createElement("div");2441      group.className = "f-group";2442      const lbl = document.createElement("div");2443      lbl.className = "f-label";2444      lbl.textContent = label;2445      const input = document.createElement("input");2446      input.className = "f-input";2447      input.type = type;2448      input.value = value;2449      input.autocomplete = "off";2450      group.append(lbl, input);2451      body.appendChild(group);2452      return { g: group, inp: input };2453    }24542455    const titleInput = field("title", entryRes.data.title ?? "").inp;2456    const urlInput = field("url", entryRes.data.url ?? "").inp;2457    urlInput.classList.add("url-f");2458    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2459    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2460    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2461    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2462    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");24632464    // Password row with reveal toggle + generator2465    const pwGroup = document.createElement("div");2466    pwGroup.className = "f-group";2467    const pwLbl = document.createElement("div");2468    pwLbl.className = "f-label";2469    pwLbl.textContent = "password";2470    const pwRow = document.createElement("div");2471    pwRow.className = "f-row";2472    const pwInput = document.createElement("input");2473    pwInput.className = "f-input";2474    pwInput.type = "password";2475    pwInput.value = entryRes.data.password ?? "";2476    pwInput.autocomplete = "new-password";2477    const revealBtn = document.createElement("button");2478    revealBtn.className = "gen-btn";2479    revealBtn.type = "button";2480    revealBtn.textContent = "show";2481    revealBtn.addEventListener("click", () => {2482      const reveal = pwInput.type === "password";2483      pwInput.type = reveal ? "text" : "password";2484      revealBtn.textContent = reveal ? "hide" : "show";2485    });2486    pwRow.append(pwInput, revealBtn);2487    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2488    editSmartGen.root.style.display = "none";2489    let editGenVisible = false;2490    const genToggleBtn = document.createElement("button");2491    genToggleBtn.className = "gen-toggle-link";2492    genToggleBtn.type = "button";2493    genToggleBtn.textContent = "⚙ generate";2494    genToggleBtn.addEventListener("click", () => {2495      editGenVisible = !editGenVisible;2496      pwRow.style.display = editGenVisible ? "none" : "";2497      editSmartGen.root.style.display = editGenVisible ? "" : "none";2498      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2499    });2500    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2501    body.appendChild(pwGroup);25022503    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;25042505    // Notes2506    const notesGroup = document.createElement("div");2507    notesGroup.className = "f-group";2508    const notesLbl = document.createElement("div");2509    notesLbl.className = "f-label";2510    notesLbl.textContent = "notes";2511    const notesInput = document.createElement("textarea");2512    notesInput.className = "f-input";2513    notesInput.rows = 3;2514    notesInput.value = entryRes.data.notes ?? "";2515    notesInput.style.fontFamily = "Inter, sans-serif";2516    notesInput.style.resize = "vertical";2517    notesGroup.append(notesLbl, notesInput);2518    body.appendChild(notesGroup);25192520    // Save / Cancel row2521    const actionsRow = document.createElement("div");2522    actionsRow.className = "f-row";2523    const saveBtn = document.createElement("button");2524    saveBtn.className = "save-btn";2525    saveBtn.type = "button";2526    saveBtn.textContent = "Save changes";2527    saveBtn.style.flex = "1";2528    const cancelBtn = document.createElement("button");2529    cancelBtn.className = "gen-btn";2530    cancelBtn.type = "button";2531    cancelBtn.textContent = "cancel";2532    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2533    actionsRow.append(saveBtn, cancelBtn);2534    body.appendChild(actionsRow);25352536    saveBtn.addEventListener("click", async () => {2537      saveBtn.disabled = true;2538      const originalLabel = saveBtn.textContent;2539      saveBtn.textContent = "Saving…";2540      const patch: Record<string, unknown> = {2541        title: titleInput.value.trim(),2542        url: urlInput.value.trim(),2543        username: usernameInput.value.trim(),2544        email: emailInput.value.trim() || undefined,2545        password: pwInput.value,2546        totp: totpInput.value.trim(),2547        notes: notesInput.value,2548      };2549      const updateRes = (await chrome.runtime.sendMessage({2550        type: "UPDATE_ENTRY",2551        payload: { id: summary.id, patch },2552      }).catch(() => null)) as { ok: boolean; error?: string } | null;2553      if (!updateRes?.ok) {2554        saveBtn.disabled = false;2555        saveBtn.textContent = originalLabel;2556        const err = document.createElement("div");2557        err.className = "empty-hint";2558        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2559        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2560        body.appendChild(err);2561        setTimeout(() => err.remove(), 3000);2562        return;2563      }2564      // Refresh the platter with updated summary fields2565      const refreshed: SelectorEntry = {2566        id: summary.id,2567        title: patch.title as string,2568        username: patch.username as string,2569        email: patch.email as string | undefined,2570        url: patch.url as string,2571        hasTotp: Boolean(patch.totp),2572        hasPasskey: summary.hasPasskey,2573      };2574      renderSilverPlatter(refreshed);2575    });25762577    queueMicrotask(() => titleInput.focus());2578  }25792580  function renderLocked() {2581    container.innerHTML = "";25822583    // Domain header (same as list view)2584    const domHdr = document.createElement("div");2585    domHdr.className = "domain-header";2586    const eyebrow = document.createElement("div");2587    eyebrow.className = "domain-eyebrow";2588    eyebrow.textContent = "vault locked";2589    const domName = document.createElement("div");2590    domName.className = "domain-name";2591    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2592    domHdr.append(eyebrow, domName);2593    container.appendChild(domHdr);25942595    const wrap = document.createElement("div");2596    wrap.className = "locked-wrap";25972598    // Icon + label row2599    const head = document.createElement("div"); head.className = "locked-head";2600    const icon = document.createElement("div"); icon.className = "locked-icon";2601    icon.innerHTML = keySvgStr();2602    const title = document.createElement("div"); title.className = "locked-title";2603    title.textContent = "unlock to autofill";2604    head.append(icon, title);26052606    // The master password is NEVER collected in page-hosted DOM. A malicious2607    // page can observe keystrokes on the shared DOM event stream (a capture-2608    // phase listener registered before Peach injects sees every key before any2609    // stopImmediatePropagation), which would leak the vault's root secret2610    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2611    // where keystrokes are isolated from the page. After the user unlocks2612    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2613    // automatically (see content/index.ts), so the flow resumes on its own.2614    const sub = document.createElement("div");2615    sub.className = "locked-sub";2616    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";26172618    const openBtn = document.createElement("button");2619    openBtn.className = "locked-btn";2620    openBtn.type = "button";2621    openBtn.textContent = "Open Peach to unlock";2622    openBtn.addEventListener("click", () => {2623      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2624      openBtn.textContent = "opening Peach…";2625      openBtn.disabled = true;2626      // openPopup() can't always open programmatically (browser/version/gesture2627      // limits); reset so the user can retry or click the toolbar icon.2628      setTimeout(() => {2629        if (openBtn.isConnected) {2630          openBtn.textContent = "Open Peach to unlock";2631          openBtn.disabled = false;2632        }2633      }, 2500);2634    });26352636    wrap.append(head, sub, openBtn);2637    container.appendChild(wrap);2638  }26392640  function handleKeyDown(e: KeyboardEvent) {2641    if (options.locked) {2642      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2643      return;2644    }2645    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2646      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2647      return;2648    }2649    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2650    const count = allEntryEls.length;2651    if (document.activeElement === searchInput) {2652      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2653      if (count === 0) return;2654      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2655    }2656    if (count === 0) return;2657    switch (e.key) {2658      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2659      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2660      case "Enter": {2661        if (focusedIndex >= 0) {2662          const el = allEntryEls[focusedIndex] as HTMLElement;2663          const id = el.dataset.id;2664          if (id) { onSelect(id); dismiss(); }2665          else if (el.classList.contains("is-new") || !id) {2666            // "New entry" row (last item, no data-id)2667            showCreateForm();2668          }2669        }2670        break;2671      }2672      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2673    }2674  }26752676  document.addEventListener("keydown", handleKeyDown);26772678  // Type-to-search from the silver platter. A printable single-character2679  // keystroke (no modifier) seeds the search query and switches into the2680  // list view, so the user can pivot to a different entry without first2681  // clicking the search icon. Capture phase so the anchor input does not2682  // receive the character before we hijack it.2683  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2684    if (currentMode !== "silver-platter") return;2685    if (e.ctrlKey || e.metaKey || e.altKey) return;2686    if (e.key.length !== 1) return;2687    e.preventDefault();2688    e.stopImmediatePropagation();2689    query = e.key;2690    renderList();2691  };2692  document.addEventListener("keydown", silverPlatterTypeHandler, true);2693  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));26942695  (modalAncestor ?? document.body).appendChild(host);26962697  function updatePosition() {2698    const r = anchorEl.getBoundingClientRect();2699    host.style.top = `${r.bottom + (modalAncestor ? 0 : window.scrollY) + 5}px`;2700    host.style.left = `${r.left + (modalAncestor ? 0 : window.scrollX)}px`;2701    host.style.width = `${popupWidth}px`;2702  }2703  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27042705  if (options.locked) {2706    renderLocked();2707  } else if (options.isSignup && options.savedIdentities) {2708    // State 10: identity helper — signup form detected, show derived2709    // identity list (emails then usernames) instead of vault entry list.2710    renderIdentityHelper();2711  } else if (entries.length === 1 && !options.isSignup) {2712    // Silver platter (State 1): single domain match → focused fill view.2713    // Multi-match goes through renderList instead.2714    renderSilverPlatter(entries[0]!);2715  } else {2716    renderList();2717  }27182719  let exitScheduled = false;2720  function dismiss(userAction = false) {2721    // Idempotent: dismiss() can be called from multiple paths (Escape,2722    // outside click, entry select, fill success, host page nav). The exit2723    // animation must only play once and host.remove() must run exactly once.2724    if (exitScheduled) return;2725    exitScheduled = true;2726    // Detach listeners synchronously so nothing can re-trigger during the2727    // 130ms exit window (a focusin firing here would race against the2728    // dismiss-lock work in Pass 2).2729    stopObserving();2730    document.removeEventListener("click", outsideClick, { capture: true });2731    document.removeEventListener("keydown", handleKeyDown);2732    for (const cleanup of cleanupHooks) {2733      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2734    }2735    if (userAction) options.onDismiss?.();2736    container.classList.add("is-exiting");2737    setTimeout(() => host.remove(), 130);2738  }27392740  function outsideClick(ev: MouseEvent) {2741    const path = ev.composedPath();2742    // Never dismiss when clicking the anchor field itself — that click is2743    // what triggered the selector to open, and the user may click the field2744    // again to re-focus it without intending to close the selector.2745    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2746  }2747  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2748  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);27492750  return dismiss;2751}27522753export function showTOTPSelector(2754  anchorEl: HTMLInputElement,2755  entries: SelectorEntry[],2756  onFill: (id: string) => void,2757  options: { domain?: string; onDismiss?: () => void } = {}2758): () => void {2759  const host = document.createElement("div");2760  host.style.cssText = "position: absolute; z-index: 2147483647;";2761  host.style.setProperty("--peach-accent", accentHex);2762  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2763  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2764  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2765  const shadow = host.attachShadow({ mode: "closed" });27662767  const style = shadow.appendChild(document.createElement("style"));2768  style.textContent = SELECTOR_STYLES;27692770  const rect = anchorEl.getBoundingClientRect();2771  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2772  host.style.left = `${rect.left + window.scrollX}px`;2773  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2774  host.style.width = `${popupWidth}px`;27752776  const container = shadow.appendChild(document.createElement("div"));2777  container.className = "peach-inline-popup";2778  container.setAttribute("data-theme", popupTheme);27792780  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2781  const current = entries.filter((entry) => entry.hasTotp);2782  let focusedIndex = current.length === 1 ? 0 : -1;27832784  function updatePosition() {2785    const r = anchorEl.getBoundingClientRect();2786    host.style.top = `${r.bottom + window.scrollY + 5}px`;2787    host.style.left = `${r.left + window.scrollX}px`;2788    host.style.width = `${popupWidth}px`;2789  }27902791  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27922793  function choose(entry: SelectorEntry) {2794    onFill(entry.id);2795    dismiss();2796  }27972798  function render() {2799    container.innerHTML = "";28002801    const domHdr = document.createElement("div");2802    domHdr.className = "domain-header";2803    const headText = document.createElement("div");2804    headText.className = "domain-header-text";2805    const eyebrow = document.createElement("div");2806    eyebrow.className = "domain-eyebrow";2807    eyebrow.textContent = "2FA code";2808    const domName = document.createElement("div");2809    domName.className = "domain-name";2810    domName.textContent = domain;2811    headText.append(eyebrow, domName);2812    domHdr.appendChild(headText);2813    container.appendChild(domHdr);28142815    if (current.length === 1) {2816      const entry = current[0]!;2817      const platter = document.createElement("div");2818      platter.className = "silver-platter";28192820      const title = document.createElement("div");2821      title.className = "sp-title";2822      title.textContent = entry.title;2823      platter.appendChild(title);28242825      const sub = document.createElement("div");2826      sub.className = "sp-username";2827      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2828      platter.appendChild(sub);28292830      const fill = document.createElement("button");2831      fill.className = "sp-fill-btn";2832      fill.type = "button";2833      fill.textContent = "Fill 2FA code";2834      fill.addEventListener("click", () => choose(entry));2835      platter.appendChild(fill);28362837      container.appendChild(platter);2838      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2839      return;2840    }28412842    const results = document.createElement("div");2843    results.className = "results";2844    container.appendChild(results);28452846    for (let i = 0; i < current.length; i++) {2847      const entry = current[i]!;2848      const row = document.createElement("div");2849      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2850      row.dataset.index = String(i);2851      row.setAttribute("tabindex", "-1");28522853      const icon = document.createElement("div");2854      icon.className = "entry-icon";2855      icon.innerHTML = keySvgStr();2856      row.appendChild(icon);2857      const info = document.createElement("div");2858      info.className = "entry-info";2859      const title = document.createElement("div");2860      title.className = "entry-title";2861      title.textContent = entry.title;2862      const sub = document.createElement("div");2863      sub.className = "entry-sub";2864      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2865      info.append(title, sub);2866      row.appendChild(info);28672868      const badge = document.createElement("span");2869      badge.className = "totp-badge";2870      badge.textContent = "Fill";2871      row.appendChild(badge);2872      row.addEventListener("click", () => choose(entry));2873      results.appendChild(row);2874    }2875  }28762877  function setFocused(index: number) {2878    focusedIndex = index;2879    container.querySelectorAll(".entry").forEach((el, i) => {2880      el.classList.toggle("focused", i === focusedIndex);2881      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2882    });2883  }28842885  function handleKeyDown(e: KeyboardEvent) {2886    if (e.key === "Escape" || e.key === "Tab") {2887      e.preventDefault();2888      dismiss(true);2889      return;2890    }2891    if (current.length === 0) return;2892    if (e.key === "Enter") {2893      e.preventDefault();2894      choose(current[Math.max(0, focusedIndex)]!);2895      return;2896    }2897    if (current.length === 1) return;2898    if (e.key === "ArrowDown") {2899      e.preventDefault();2900      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2901    } else if (e.key === "ArrowUp") {2902      e.preventDefault();2903      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2904    }2905  }29062907  let exitScheduled = false;2908  function dismiss(userAction = false) {2909    if (exitScheduled) return;2910    exitScheduled = true;2911    stopObserving();2912    document.removeEventListener("click", outsideClick, { capture: true });2913    document.removeEventListener("keydown", handleKeyDown);2914    if (userAction) options.onDismiss?.();2915    container.classList.add("is-exiting");2916    setTimeout(() => host.remove(), 130);2917  }29182919  function outsideClick(ev: MouseEvent) {2920    const path = ev.composedPath();2921    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2922  }29232924  document.addEventListener("keydown", handleKeyDown);2925  document.body.appendChild(host);2926  render();2927  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);29282929  return dismiss;2930}29312932export interface CardSelectorEntry {2933  id: string;2934  title: string;2935  cardholderName?: string;2936  last4?: string;2937  expMonth?: string;2938  expYear?: string;2939  network?: import("../shared/types").CardNetwork;2940}29412942interface CardSelectorOptions {2943  domain?: string;2944  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2945  onFill: (entry: import("../shared/types").VaultEntry) => void;2946  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2947  onDismiss?: () => void;2948}29492950/**2951 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2952 * passkey create or get. Renders as a fixed-position floating popup (no2953 * field anchor needed — passkeys don't require a focused input). Uses the2954 * same theme tokens and entrance animation as all other inline popup states.2955 */2956export function showPasskeyProGate(): void {2957  const domain = location.hostname.replace(/^www\./, "");29582959  const host = document.createElement("div");2960  host.setAttribute("data-peach-passkey-gate", "1");2961  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2962  const shadow = host.attachShadow({ mode: "closed" });29632964  const style = document.createElement("style");2965  style.textContent = `2966    :host { all: initial; }2967    .gate-wrap {2968      position: fixed;2969      top: 50%;2970      left: 50%;2971      transform: translate(-50%, -50%);2972      width: 280px;2973      pointer-events: auto;2974      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2975    }2976    @keyframes g-in {2977      from { opacity:0; transform: translate(-50%,-52%); }2978      to   { opacity:1; transform: translate(-50%,-50%); }2979    }2980    .gate-wrap.is-exiting {2981      animation: g-out 130ms ease-in forwards;2982    }2983    @keyframes g-out {2984      to { opacity:0; transform: translate(-50%,-52%); }2985    }2986    .gate {2987      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2988      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2989      border-radius: 12px;2990      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2991      padding: 16px;2992      font-family: Inter, sans-serif;2993    }2994    .gate-header {2995      display: flex;2996      align-items: center;2997      gap: 7px;2998      margin-bottom: 12px;2999      padding-bottom: 10px;3000      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3001    }3002    .gate-domain {3003      font-size: 12px;3004      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3005      font-family: "IBM Plex Mono", monospace;3006      overflow: hidden;3007      text-overflow: ellipsis;3008      white-space: nowrap;3009    }3010    .gate-title {3011      font-size: 14px;3012      font-weight: 500;3013      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3014      margin-bottom: 6px;3015    }3016    .gate-subtitle {3017      font-size: 12px;3018      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3019      line-height: 1.5;3020      margin-bottom: 14px;3021    }3022    .gate-btn {3023      display: block;3024      width: 100%;3025      padding: 9px 0;3026      border-radius: 8px;3027      border: none;3028      cursor: pointer;3029      font-size: 13px;3030      font-family: Inter, sans-serif;3031      font-weight: 500;3032      transition: opacity 100ms;3033      margin-bottom: 7px;3034      text-align: center;3035    }3036    .gate-btn:last-child { margin-bottom: 0; }3037    .gate-btn--accent {3038      background: ${accentHex};3039      color: #fff;3040    }3041    .gate-btn--accent:hover { opacity: 0.88; }3042    .gate-btn--ghost {3043      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3044      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3045    }3046    .gate-btn--ghost:hover { opacity: 0.75; }3047    .backdrop {3048      position: fixed;3049      inset: 0;3050      pointer-events: auto;3051    }3052  `;3053  shadow.appendChild(style);30543055  const backdrop = document.createElement("div");3056  backdrop.className = "backdrop";3057  shadow.appendChild(backdrop);30583059  const wrap = document.createElement("div");3060  wrap.className = "gate-wrap";3061  shadow.appendChild(wrap);30623063  const gate = document.createElement("div");3064  gate.className = "gate";3065  wrap.appendChild(gate);30663067  // Header: peach icon + domain3068  const header = document.createElement("div");3069  header.className = "gate-header";3070  const icon = document.createElement("span");3071  icon.innerHTML = peachIconSvg();3072  const domainEl = document.createElement("span");3073  domainEl.className = "gate-domain";3074  domainEl.textContent = domain;3075  header.append(icon, domainEl);3076  gate.appendChild(header);30773078  const title = document.createElement("div");3079  title.className = "gate-title";3080  title.textContent = "Passkeys are part of Peach Pro.";3081  gate.appendChild(title);30823083  const subtitle = document.createElement("div");3084  subtitle.className = "gate-subtitle";3085  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3086  gate.appendChild(subtitle);30873088  const upgradeBtn = document.createElement("button");3089  upgradeBtn.className = "gate-btn gate-btn--accent";3090  upgradeBtn.type = "button";3091  upgradeBtn.textContent = "Upgrade to Pro";3092  gate.appendChild(upgradeBtn);30933094  const laterBtn = document.createElement("button");3095  laterBtn.className = "gate-btn gate-btn--ghost";3096  laterBtn.type = "button";3097  laterBtn.textContent = "Not right now";3098  gate.appendChild(laterBtn);30993100  function dismiss() {3101    wrap.classList.add("is-exiting");3102    setTimeout(() => host.remove(), 130);3103  }31043105  upgradeBtn.addEventListener("click", () => {3106    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3107    dismiss();3108  });3109  laterBtn.addEventListener("click", dismiss);3110  backdrop.addEventListener("click", dismiss);31113112  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3113    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3114  });31153116  document.body.appendChild(host);3117}31183119/**3120 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3121 * detector sees the page invoke navigator.credentials.create(); content/index.ts3122 * checks vault + decline state then calls this. "Save passkey to Peach"3123 * initiates the popup-context credential flow; "Not now" records a 30-day3124 * decline for the domain so we don't re-show on every page reload.3125 */3126export function showPasskeyRegistrationOffer(args: {3127  rpId: string;3128  rpName?: string;3129  userName?: string;3130  userDisplayName?: string;3131}): void {3132  const domain = location.hostname.replace(/^www\./, "");3133  const displayName = args.rpName || domain;31343135  const host = document.createElement("div");3136  host.setAttribute("data-peach-passkey-offer", "1");3137  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3138  const shadow = host.attachShadow({ mode: "closed" });31393140  const style = document.createElement("style");3141  style.textContent = `3142    :host { all: initial; }3143    .offer-wrap {3144      position: fixed;3145      top: 16px;3146      right: 16px;3147      width: 320px;3148      pointer-events: auto;3149      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3150    }3151    @keyframes o-in {3152      from { opacity: 0; transform: translateY(-6px); }3153      to   { opacity: 1; transform: translateY(0); }3154    }3155    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3156    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3157    .offer {3158      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3159      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3160      border-radius: 12px;3161      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3162      padding: 14px 14px 12px;3163      font-family: Inter, sans-serif;3164      position: relative;3165    }3166    .offer-close {3167      position: absolute;3168      top: 8px;3169      right: 8px;3170      width: 18px;3171      height: 18px;3172      border: none;3173      background: transparent;3174      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3175      cursor: pointer;3176      font-size: 14px;3177      line-height: 1;3178      padding: 0;3179    }3180    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3181    .offer-header {3182      display: flex;3183      align-items: center;3184      gap: 7px;3185      margin-bottom: 8px;3186      padding-bottom: 8px;3187      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3188    }3189    .offer-domain {3190      font-size: 12px;3191      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3192      font-family: "IBM Plex Mono", monospace;3193      overflow: hidden;3194      text-overflow: ellipsis;3195      white-space: nowrap;3196    }3197    .offer-title {3198      font-size: 13px;3199      font-weight: 500;3200      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3201      margin-bottom: 4px;3202    }3203    .offer-subtitle {3204      font-size: 11px;3205      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3206      line-height: 1.45;3207      margin-bottom: 12px;3208    }3209    .offer-btn {3210      display: block;3211      width: 100%;3212      padding: 8px 0;3213      border-radius: 7px;3214      border: none;3215      cursor: pointer;3216      font-size: 12px;3217      font-family: Inter, sans-serif;3218      font-weight: 500;3219      transition: opacity 100ms;3220      margin-bottom: 6px;3221      text-align: center;3222    }3223    .offer-btn:last-child { margin-bottom: 0; }3224    .offer-btn--accent { background: ${accentHex}; color: #fff; }3225    .offer-btn--accent:hover { opacity: 0.88; }3226    .offer-btn--ghost {3227      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3228      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3229    }3230    .offer-btn--ghost:hover { opacity: 0.75; }3231  `;3232  shadow.appendChild(style);32333234  const wrap = document.createElement("div");3235  wrap.className = "offer-wrap";3236  shadow.appendChild(wrap);32373238  const offer = document.createElement("div");3239  offer.className = "offer";3240  wrap.appendChild(offer);32413242  const closeBtn = document.createElement("button");3243  closeBtn.className = "offer-close";3244  closeBtn.type = "button";3245  closeBtn.setAttribute("aria-label", "Dismiss");3246  closeBtn.textContent = "✕";3247  offer.appendChild(closeBtn);32483249  const header = document.createElement("div");3250  header.className = "offer-header";3251  const icon = document.createElement("span");3252  icon.innerHTML = peachIconSvg();3253  const domainEl = document.createElement("span");3254  domainEl.className = "offer-domain";3255  domainEl.textContent = domain;3256  header.append(icon, domainEl);3257  offer.appendChild(header);32583259  const title = document.createElement("div");3260  title.className = "offer-title";3261  title.textContent = "This site supports passkeys.";3262  offer.appendChild(title);32633264  const subtitle = document.createElement("div");3265  subtitle.className = "offer-subtitle";3266  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3267  offer.appendChild(subtitle);32683269  const saveBtn = document.createElement("button");3270  saveBtn.className = "offer-btn offer-btn--accent";3271  saveBtn.type = "button";3272  saveBtn.textContent = "Save passkey to Peach";3273  offer.appendChild(saveBtn);32743275  const laterBtn = document.createElement("button");3276  laterBtn.className = "offer-btn offer-btn--ghost";3277  laterBtn.type = "button";3278  laterBtn.textContent = "Not now";3279  offer.appendChild(laterBtn);32803281  function dismiss(decline: boolean) {3282    if (decline) {3283      chrome.runtime.sendMessage({3284        type: "PASSKEY_OFFER_DECLINE",3285        payload: { domain },3286      }).catch(() => {});3287    }3288    wrap.classList.add("is-exiting");3289    setTimeout(() => host.remove(), 130);3290  }32913292  saveBtn.addEventListener("click", () => {3293    chrome.runtime.sendMessage({3294      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3295      payload: {3296        rpId: args.rpId,3297        rpName: args.rpName ?? displayName,3298        userName: args.userName ?? "user",3299        userDisplayName: args.userDisplayName,3300      },3301    }).catch(() => {});3302    dismiss(false);3303  });3304  laterBtn.addEventListener("click", () => dismiss(true));3305  closeBtn.addEventListener("click", () => dismiss(true));33063307  document.body.appendChild(host);3308}33093310/**3311 * State 11 — passkey available indicator. Shown when the user lands on a3312 * domain for which they already have a stored passkey. Tells them where to3313 * find it (the entry already shows in the vault list); the "Sign in with3314 * passkey" button opens the popup so they can use the platform authenticator3315 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3316 * the actual sign-in transparently, so this banner is informational only.3317 */3318export function showPasskeyAvailable(args: {3319  rpId: string;3320  userName: string;3321  fromBrowser?: "chrome" | "firefox";3322  currentBrowser?: "chrome" | "firefox" | "unknown";3323}): void {3324  const domain = location.hostname.replace(/^www\./, "");3325  const crossBrowser =3326    args.fromBrowser &&3327    args.currentBrowser &&3328    args.currentBrowser !== "unknown" &&3329    args.fromBrowser !== args.currentBrowser;33303331  const host = document.createElement("div");3332  host.setAttribute("data-peach-passkey-available", "1");3333  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3334  const shadow = host.attachShadow({ mode: "closed" });33353336  const style = document.createElement("style");3337  style.textContent = `3338    :host { all: initial; }3339    .avail-wrap {3340      position: fixed;3341      top: 16px;3342      right: 16px;3343      width: 320px;3344      pointer-events: auto;3345      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3346    }3347    @keyframes a-in {3348      from { opacity: 0; transform: translateY(-6px); }3349      to   { opacity: 1; transform: translateY(0); }3350    }3351    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3352    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3353    .avail {3354      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3355      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3356      border-radius: 12px;3357      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3358      padding: 14px 14px 12px;3359      font-family: Inter, sans-serif;3360      position: relative;3361    }3362    .avail-close {3363      position: absolute;3364      top: 8px;3365      right: 8px;3366      width: 18px;3367      height: 18px;3368      border: none;3369      background: transparent;3370      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3371      cursor: pointer;3372      font-size: 14px;3373      line-height: 1;3374      padding: 0;3375    }3376    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3377    .avail-header {3378      display: flex;3379      align-items: center;3380      gap: 7px;3381      margin-bottom: 8px;3382      padding-bottom: 8px;3383      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3384    }3385    .avail-domain {3386      font-size: 12px;3387      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3388      font-family: "IBM Plex Mono", monospace;3389    }3390    .avail-label {3391      font-size: 9px;3392      letter-spacing: 0.16em;3393      text-transform: uppercase;3394      color: ${accentHex};3395      margin-bottom: 4px;3396    }3397    .avail-user {3398      font-size: 13px;3399      font-weight: 500;3400      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3401      margin-bottom: 12px;3402      overflow: hidden;3403      text-overflow: ellipsis;3404      white-space: nowrap;3405    }3406    .avail-cross {3407      font-size: 11px;3408      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3409      line-height: 1.45;3410      margin-bottom: 12px;3411      padding: 8px;3412      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3413      border-radius: 6px;3414    }3415    .avail-btn {3416      display: block;3417      width: 100%;3418      padding: 8px 0;3419      border-radius: 7px;3420      border: none;3421      cursor: pointer;3422      font-size: 12px;3423      font-family: Inter, sans-serif;3424      font-weight: 500;3425      transition: opacity 100ms;3426      margin-bottom: 6px;3427      text-align: center;3428    }3429    .avail-btn:last-child { margin-bottom: 0; }3430    .avail-btn--accent { background: ${accentHex}; color: #fff; }3431    .avail-btn--accent:hover { opacity: 0.88; }3432    .avail-btn--ghost {3433      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3434      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3435    }3436    .avail-btn--ghost:hover { opacity: 0.75; }3437  `;3438  shadow.appendChild(style);34393440  const wrap = document.createElement("div");3441  wrap.className = "avail-wrap";3442  shadow.appendChild(wrap);34433444  const avail = document.createElement("div");3445  avail.className = "avail";3446  wrap.appendChild(avail);34473448  const closeBtn = document.createElement("button");3449  closeBtn.className = "avail-close";3450  closeBtn.type = "button";3451  closeBtn.setAttribute("aria-label", "Dismiss");3452  closeBtn.textContent = "✕";3453  avail.appendChild(closeBtn);34543455  const header = document.createElement("div");3456  header.className = "avail-header";3457  const icon = document.createElement("span");3458  icon.innerHTML = peachIconSvg();3459  const domainEl = document.createElement("span");3460  domainEl.className = "avail-domain";3461  domainEl.textContent = domain;3462  header.append(icon, domainEl);3463  avail.appendChild(header);34643465  const label = document.createElement("div");3466  label.className = "avail-label";3467  label.textContent = "PASSKEY";3468  avail.appendChild(label);34693470  const user = document.createElement("div");3471  user.className = "avail-user";3472  user.textContent = args.userName;3473  avail.appendChild(user);34743475  if (crossBrowser) {3476    const cross = document.createElement("div");3477    cross.className = "avail-cross";3478    cross.textContent =3479      args.fromBrowser === "chrome"3480        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3481        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3482    avail.appendChild(cross);3483  }34843485  const signInBtn = document.createElement("button");3486  signInBtn.className = "avail-btn avail-btn--accent";3487  signInBtn.type = "button";3488  signInBtn.textContent = "Sign in with passkey";3489  avail.appendChild(signInBtn);34903491  const passwordBtn = document.createElement("button");3492  passwordBtn.className = "avail-btn avail-btn--ghost";3493  passwordBtn.type = "button";3494  passwordBtn.textContent = "Use password instead";3495  avail.appendChild(passwordBtn);34963497  function dismiss() {3498    wrap.classList.add("is-exiting");3499    setTimeout(() => host.remove(), 130);3500  }35013502  signInBtn.addEventListener("click", () => {3503    // On Chrome: the user clicking the page's own Sign-in button is what3504    //   triggers webAuthenticationProxy → existing background flow handles it.3505    //   Our button just dismisses since the page itself drives auth.3506    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3507    //   and surface the entry for manual reference (popup view).3508    dismiss();3509    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3510  });3511  passwordBtn.addEventListener("click", dismiss);3512  closeBtn.addEventListener("click", dismiss);35133514  document.body.appendChild(host);3515}35163517/**3518 * State 7 — card silver platter. Single-card focused fill view rendered3519 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3520 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3521 * so card and login flows render identically. Multi-card list view is a3522 * follow-up; today this picks the first card.3523 */3524export function showCardSelector(3525  anchorEl: HTMLInputElement,3526  cards: CardSelectorEntry[],3527  options: CardSelectorOptions3528): () => void {3529  if (cards.length === 0) return () => {};3530  const card = cards[0]!;35313532  const host = document.createElement("div");3533  host.style.cssText = "position: absolute; z-index: 2147483647;";3534  host.style.setProperty("--peach-accent", accentHex);3535  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3536  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3537  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3538  const shadow = host.attachShadow({ mode: "closed" });35393540  const style = shadow.appendChild(document.createElement("style"));3541  style.textContent = SELECTOR_STYLES;35423543  const rect = anchorEl.getBoundingClientRect();3544  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3545  host.style.left = `${rect.left + window.scrollX}px`;3546  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;35473548  const container = shadow.appendChild(document.createElement("div"));3549  container.className = "peach-inline-popup";3550  container.setAttribute("data-theme", popupTheme);35513552  // Domain header — eyebrow communicates the card context, not the site3553  const domHdr = document.createElement("div");3554  domHdr.className = "domain-header";3555  const eyebrow = document.createElement("div");3556  eyebrow.className = "domain-eyebrow";3557  eyebrow.textContent = "Pay with Peach";3558  const domName = document.createElement("div");3559  domName.className = "domain-name";3560  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3561  domHdr.append(eyebrow, domName);3562  container.appendChild(domHdr);35633564  const platter = document.createElement("div");3565  platter.className = "card-platter";35663567  if (card.network && card.network !== "unknown") {3568    const net = document.createElement("div");3569    net.className = "cp-network";3570    net.textContent = card.network;3571    platter.appendChild(net);3572  }35733574  const nick = document.createElement("div");3575  nick.className = "cp-nickname";3576  nick.textContent = card.title;3577  platter.appendChild(nick);35783579  if (card.last4) {3580    const l4 = document.createElement("div");3581    l4.className = "cp-last4";3582    l4.textContent = `•••• ${card.last4}`;3583    platter.appendChild(l4);3584  }35853586  const meta = document.createElement("div");3587  meta.className = "cp-meta";3588  if (card.cardholderName) {3589    const name = document.createElement("span");3590    name.textContent = card.cardholderName;3591    meta.appendChild(name);3592  }3593  if (card.expMonth && card.expYear) {3594    if (card.cardholderName) {3595      const sep = document.createElement("span");3596      sep.className = "cp-meta-sep";3597      sep.textContent = "·";3598      meta.appendChild(sep);3599    }3600    const exp = document.createElement("span");3601    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3602    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3603    meta.appendChild(exp);3604  }3605  if (meta.childElementCount > 0) platter.appendChild(meta);36063607  const fillWrap = document.createElement("div");3608  fillWrap.className = "cp-fill-wrap";3609  const fillBtn = document.createElement("button");3610  fillBtn.className = "sp-fill-btn";3611  fillBtn.type = "button";3612  fillBtn.textContent = "Fill card details";3613  fillBtn.addEventListener("click", async () => {3614    if (fillBtn.disabled) return;3615    fillBtn.disabled = true;3616    fillBtn.classList.add("filled");3617    fillBtn.innerHTML = checkSvgStr();3618    const resp = await chrome.runtime.sendMessage({3619      type: "GET_ENTRY_FOR_FILL",3620      payload: { id: card.id },3621    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3622    if (resp?.ok && resp.data) options.onFill(resp.data);3623    setTimeout(() => dismiss(), 400);3624  });3625  fillWrap.appendChild(fillBtn);3626  platter.appendChild(fillWrap);36273628  // Secondary actions — copy number, copy CVC, dismiss3629  const actions = document.createElement("div");3630  actions.className = "sp-actions";36313632  function flashBtn(b: HTMLButtonElement) {3633    b.classList.add("flashed");3634    setTimeout(() => b.classList.remove("flashed"), 700);3635  }36363637  // M3/QUA-005: clipboard + background COPY both failed — show user.3638  function flashCopyError(b: HTMLButtonElement) {3639    const original = b.textContent ?? "";3640    b.textContent = "Blocked";3641    b.classList.add("flashed");3642    setTimeout(() => {3643      b.classList.remove("flashed");3644      if (b.isConnected) b.textContent = original;3645    }, 1200);3646  }36473648  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3649    const resp = await chrome.runtime.sendMessage({3650      type: "GET_ENTRY_FOR_FILL",3651      payload: { id: card.id },3652    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3653    return resp?.ok && resp.data ? resp.data : null;3654  }36553656  const copyNum = document.createElement("button");3657  copyNum.className = "sp-action-btn";3658  copyNum.type = "button";3659  copyNum.title = "Copy card number";3660  copyNum.textContent = "Copy number";3661  copyNum.addEventListener("click", async (e) => {3662    e.stopPropagation();3663    const full = await fetchFullCard();3664    if (!full?.cardNumber) return;3665    let alreadyWritten = false;3666    try {3667      await navigator.clipboard.writeText(full.cardNumber);3668      alreadyWritten = true;3669    } catch (err) {3670      console.warn("[Peach] clipboard write denied:", err);3671    }3672    const resp = await chrome.runtime.sendMessage({3673      type: "COPY",3674      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3675    }).catch(() => null) as { ok?: boolean } | null;3676    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3677    else flashCopyError(copyNum);3678  });3679  actions.appendChild(copyNum);36803681  const copyCvc = document.createElement("button");3682  copyCvc.className = "sp-action-btn";3683  copyCvc.type = "button";3684  copyCvc.title = "Copy CVC";3685  copyCvc.textContent = "Copy CVC";3686  copyCvc.addEventListener("click", async (e) => {3687    e.stopPropagation();3688    const full = await fetchFullCard();3689    if (!full?.cvc) return;3690    let alreadyWritten = false;3691    try {3692      await navigator.clipboard.writeText(full.cvc);3693      alreadyWritten = true;3694    } catch (err) {3695      console.warn("[Peach] clipboard write denied:", err);3696    }3697    const resp = await chrome.runtime.sendMessage({3698      type: "COPY",3699      payload: { text: full.cvc, label: "CVC", alreadyWritten },3700    }).catch(() => null) as { ok?: boolean } | null;3701    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3702    else flashCopyError(copyCvc);3703  });3704  actions.appendChild(copyCvc);37053706  const closeBtn = document.createElement("button");3707  closeBtn.className = "sp-action-btn";3708  closeBtn.type = "button";3709  closeBtn.title = "Dismiss";3710  closeBtn.textContent = "✕";3711  closeBtn.addEventListener("click", (e) => {3712    e.stopPropagation();3713    dismiss(true);3714  });3715  actions.appendChild(closeBtn);37163717  platter.appendChild(actions);3718  container.appendChild(platter);37193720  document.body.appendChild(host);3721  function updatePosition() {3722    const r = anchorEl.getBoundingClientRect();3723    host.style.top = `${r.bottom + window.scrollY + 5}px`;3724    host.style.left = `${r.left + window.scrollX}px`;3725  }3726  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);37273728  function onKeyDown(e: KeyboardEvent) {3729    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3730  }3731  document.addEventListener("keydown", onKeyDown);37323733  let exitScheduled = false;3734  function dismiss(userAction = false) {3735    if (exitScheduled) return;3736    exitScheduled = true;3737    stopObserving();3738    document.removeEventListener("click", outsideClick, { capture: true });3739    document.removeEventListener("keydown", onKeyDown);3740    if (userAction) options.onDismiss?.();3741    container.classList.add("is-exiting");3742    setTimeout(() => host.remove(), 130);3743  }37443745  function outsideClick(ev: MouseEvent) {3746    const path = ev.composedPath();3747    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3748  }3749  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);37503751  return dismiss;3752}