inject.ts

149.5 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 err = (res as { error?: string })?.error;2016          const errMsg = err === "vault_locked"2017            ? "Vault locked — open Peach to save"2018            : err === "STORAGE_QUOTA_EXCEEDED"2019              ? "Out of storage — open Peach → Settings to free space"2020              : err2021                ? `Could not save: ${err}`2022                : "Could not save entry";2023          showFormError(errMsg);2024          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2025        }2026      } catch (e) {2027        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2028        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2029      }2030    });2031    body.appendChild(saveBtn);2032    body.appendChild(errEl);20332034    wrap.append(head, body);2035    container.appendChild(wrap);2036    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2037  }20382039  function showSuccess(title: string) {2040    currentMode = "success";2041    container.innerHTML = "";2042    const wrap = document.createElement("div"); wrap.className = "success-wrap";2043    const ring = document.createElement("div"); ring.className = "success-ring";2044    ring.innerHTML = checkSvgStr();2045    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2046    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2047    wrap.append(ring, t, s);2048    container.appendChild(wrap);2049    setTimeout(() => dismiss(), 1600);2050  }20512052  function flashActionBtn(btn: HTMLButtonElement) {2053    btn.classList.add("flashed");2054    setTimeout(() => btn.classList.remove("flashed"), 700);2055  }20562057  // M3/QUA-005: when both the direct clipboard write and the background COPY2058  // fallback fail, briefly show the user that the copy did not happen.2059  function flashCopyError(btn: HTMLButtonElement) {2060    const original = btn.textContent ?? "";2061    btn.textContent = "Blocked";2062    btn.classList.add("flashed");2063    setTimeout(() => {2064      btn.classList.remove("flashed");2065      if (btn.isConnected) btn.textContent = original;2066    }, 1200);2067  }20682069  function renderSilverPlatter(entry: SelectorEntry) {2070    container.innerHTML = "";2071    searchInput = null;2072    focusedIndex = -1;2073    currentMode = "silver-platter";2074    silverPlatterOrigin = entry;20752076    const domHdr = document.createElement("div");2077    domHdr.className = "domain-header";2078    const headText = document.createElement("div");2079    headText.className = "domain-header-text";2080    const eyebrow = document.createElement("div");2081    eyebrow.className = "domain-eyebrow";2082    eyebrow.textContent = "Saved for this site";2083    const domName = document.createElement("div");2084    domName.className = "domain-name";2085    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2086    headText.append(eyebrow, domName);2087    domHdr.appendChild(headText);2088    if (!options.isSignup) {2089      const actions = document.createElement("div");2090      actions.className = "domain-header-actions";20912092      // Search shortcut — same idea as type-to-search below, but visible so2093      // the user can discover that another entry is reachable from a2094      // single-match platter. Sits to the left of the create button.2095      const searchBtn = document.createElement("button");2096      searchBtn.className = "domain-search-btn";2097      searchBtn.type = "button";2098      searchBtn.setAttribute("aria-label", "Search for a different entry");2099      searchBtn.title = "Search for a different entry";2100      searchBtn.innerHTML = searchSvgStr();2101      searchBtn.addEventListener("click", (e) => {2102        e.stopPropagation();2103        query = "";2104        renderList();2105      });2106      actions.appendChild(searchBtn);21072108      const addBtn = document.createElement("button");2109      addBtn.className = "domain-add-btn";2110      addBtn.type = "button";2111      addBtn.setAttribute("aria-label", "Create new entry");2112      addBtn.title = "Create new entry";2113      addBtn.textContent = "+";2114      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2115      actions.appendChild(addBtn);21162117      domHdr.appendChild(actions);2118    }2119    container.appendChild(domHdr);21202121    const platter = document.createElement("div");2122    platter.className = "silver-platter";21232124    const titleEl = document.createElement("div");2125    titleEl.className = "sp-title";2126    titleEl.textContent = entry.title;2127    platter.appendChild(titleEl);21282129    if (entry.email) {2130      const emailEl = document.createElement("div");2131      emailEl.className = "sp-identity-row";2132      const emailLbl = document.createElement("span");2133      emailLbl.className = "sp-identity-label";2134      emailLbl.textContent = "email";2135      const emailVal = document.createElement("span");2136      emailVal.className = "sp-username";2137      emailVal.textContent = entry.email;2138      emailEl.append(emailLbl, emailVal);2139      platter.appendChild(emailEl);2140    }21412142    if (entry.username) {2143      const userEl = document.createElement("div");2144      userEl.className = "sp-identity-row";2145      const userLbl = document.createElement("span");2146      userLbl.className = "sp-identity-label";2147      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2148      const userVal = document.createElement("span");2149      userVal.className = "sp-username";2150      userVal.textContent = entry.username;2151      userEl.append(userLbl, userVal);2152      platter.appendChild(userEl);2153    }21542155    const fillBtn = document.createElement("button");2156    fillBtn.className = "sp-fill-btn";2157    fillBtn.type = "button";2158    fillBtn.textContent = "Fill credentials";2159    fillBtn.addEventListener("click", () => {2160      if (fillBtn.disabled) return;2161      fillBtn.disabled = true;2162      fillBtn.classList.add("filled");2163      fillBtn.innerHTML = checkSvgStr();2164      // Fire the fill, then exit via the standard exit animation. The fill2165      // itself is async (handled in index.ts) — by 400ms the form is filled2166      // and the popup begins its exit. Total dwell from click to host2167      // removal: 400ms + 130ms (exit animation) = 530ms.2168      onSelect(entry.id);2169      setTimeout(() => dismiss(), 400);2170    });2171    platter.appendChild(fillBtn);21722173    const actionsGroup = document.createElement("div");2174    actionsGroup.className = "sp-actions-group";2175    const actionsLabel = document.createElement("div");2176    actionsLabel.className = "sp-actions-label";2177    actionsLabel.textContent = "Copy";2178    actionsGroup.appendChild(actionsLabel);21792180    const actions = document.createElement("div");2181    actions.className = "sp-actions";2182    actionsGroup.appendChild(actions);21832184    if (entry.email) {2185      const copyEmail = document.createElement("button");2186      copyEmail.className = "sp-action-btn";2187      copyEmail.type = "button";2188      copyEmail.title = "Copy email";2189      copyEmail.textContent = "Email";2190      copyEmail.addEventListener("click", async (e) => {2191        e.stopPropagation();2192        let alreadyWritten = false;2193        try {2194          await navigator.clipboard.writeText(entry.email!);2195          alreadyWritten = true;2196        } catch (err) {2197          console.warn("[Peach] clipboard write denied:", err);2198        }2199        const resp = await chrome.runtime.sendMessage({2200          type: "COPY",2201          payload: { text: entry.email, label: "Email", alreadyWritten },2202        }).catch(() => null) as { ok?: boolean } | null;2203        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2204        else flashCopyError(copyEmail);2205      });2206      actions.appendChild(copyEmail);2207    }22082209    const copyU = document.createElement("button");2210    copyU.className = "sp-action-btn";2211    copyU.type = "button";2212    const usernameIsEmail = entry.username?.includes("@") ?? false;2213    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2214    copyU.textContent = usernameIsEmail ? "Email" : "Username";2215    copyU.disabled = !entry.username;2216    copyU.addEventListener("click", async (e) => {2217      e.stopPropagation();2218      if (!entry.username) return;2219      let alreadyWritten = false;2220      try {2221        await navigator.clipboard.writeText(entry.username);2222        alreadyWritten = true;2223      } catch (err) {2224        console.warn("[Peach] clipboard write denied:", err);2225      }2226      const resp = await chrome.runtime.sendMessage({2227        type: "COPY",2228        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2229      }).catch(() => null) as { ok?: boolean } | null;2230      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2231      else flashCopyError(copyU);2232    });2233    actions.appendChild(copyU);22342235    const copyP = document.createElement("button");2236    copyP.className = "sp-action-btn";2237    copyP.type = "button";2238    copyP.title = "Copy password";2239    copyP.textContent = "Password";2240    copyP.addEventListener("click", async (e) => {2241      e.stopPropagation();2242      const resp = await chrome.runtime.sendMessage({2243        type: "GET_ENTRY_FOR_FILL",2244        payload: { id: entry.id },2245      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2246      if (!resp?.ok || !resp.data?.password) return;2247      let alreadyWritten = false;2248      try {2249        await navigator.clipboard.writeText(resp.data.password);2250        alreadyWritten = true;2251      } catch (err) {2252        console.warn("[Peach] clipboard write denied:", err);2253      }2254      const copyResp = await chrome.runtime.sendMessage({2255        type: "COPY",2256        payload: { text: resp.data.password, label: "Password", alreadyWritten },2257      }).catch(() => null) as { ok?: boolean } | null;2258      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2259      else flashCopyError(copyP);2260    });2261    actions.appendChild(copyP);22622263    let trayEl: HTMLDivElement | null = null;2264    let trayInterval: ReturnType<typeof setInterval> | null = null;22652266    function closeTray() {2267      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2268      trayEl?.remove();2269      trayEl = null;2270    }2271    // Register so dismiss() will close the tray and clear the interval2272    // even if the user dismisses without explicitly closing the tray.2273    cleanupHooks.push(closeTray);22742275    async function openTOTPTray() {2276      // Fetch the current TOTP code from the background. The raw base32 seed2277      // never enters the content script (SEV-3-C): we receive the live 6-digit2278      // code plus the seconds remaining, count down locally, and re-fetch a2279      // fresh code only when the 30s window rolls over.2280      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2281        const r = await chrome.runtime.sendMessage({2282          type: "GET_ENTRY_FOR_FILL",2283          payload: { id: entry.id },2284        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2285        if (!r?.ok || !r.data?.totpCode) return null;2286        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2287      }2288      let current = await fetchCode();2289      if (!current) return;22902291      trayEl = document.createElement("div");2292      trayEl.className = "sp-tray";22932294      const label = document.createElement("span");2295      label.className = "sp-tray-label";2296      label.textContent = "2FA";2297      trayEl.appendChild(label);22982299      const codeEl = document.createElement("div");2300      codeEl.className = "sp-totp-code";2301      trayEl.appendChild(codeEl);23022303      const ringNs = "http://www.w3.org/2000/svg";2304      const ring = document.createElementNS(ringNs, "svg");2305      ring.setAttribute("class", "sp-totp-ring");2306      ring.setAttribute("viewBox", "0 0 24 24");2307      const trackC = document.createElementNS(ringNs, "circle");2308      trackC.setAttribute("class", "ring-track");2309      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2310      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2311      const fillC = document.createElementNS(ringNs, "circle");2312      fillC.setAttribute("class", "ring-fill");2313      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2314      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2315      fillC.setAttribute("stroke-linecap", "round");2316      fillC.setAttribute("stroke-dasharray", "62.83");2317      ring.append(trackC, fillC);2318      trayEl.appendChild(ring);23192320      const copyBtn = document.createElement("button");2321      copyBtn.className = "sp-totp-copy";2322      copyBtn.type = "button";2323      copyBtn.textContent = "Copy";2324      trayEl.appendChild(copyBtn);23252326      function render() {2327        const { code, remaining } = current!;2328        // Group as "847 291" — easier to read than "847291"2329        codeEl.textContent = code.length === 62330          ? `${code.slice(0, 3)} ${code.slice(3)}`2331          : code;2332        // Ring fills counter-clockwise as time elapses: dashoffset goes from2333        // 0 (full ring) to 62.83 (empty) over the 30s window.2334        const fraction = (30 - remaining) / 30;2335        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2336      }2337      render();2338      trayInterval = setInterval(async () => {2339        if (!current) return;2340        current = { code: current.code, remaining: current.remaining - 1 };2341        // Window rolled over — pull a fresh code from the background.2342        if (current.remaining <= 0) {2343          const next = await fetchCode();2344          current = next ?? { code: current.code, remaining: 30 };2345        }2346        render();2347      }, 1000);23482349      copyBtn.addEventListener("click", async (e) => {2350        e.stopPropagation();2351        const code = current?.code;2352        if (!code) return;2353        let alreadyWritten = false;2354        try {2355          await navigator.clipboard.writeText(code);2356          alreadyWritten = true;2357        } catch (err) {2358          console.warn("[Peach] clipboard write denied:", err);2359        }2360        const resp = await chrome.runtime.sendMessage({2361          type: "COPY",2362          payload: { text: code, label: "TOTP", alreadyWritten },2363        }).catch(() => null) as { ok?: boolean } | null;2364        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2365        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2366      });23672368      platter.appendChild(trayEl);2369    }23702371    const editBtn = document.createElement("button");2372    editBtn.className = "sp-action-btn sp-action-edit";2373    editBtn.type = "button";2374    editBtn.title = "Edit entry";2375    editBtn.textContent = "Edit";2376    editBtn.addEventListener("click", (e) => {2377      e.stopPropagation();2378      closeTray();2379      void renderInlineEdit(entry);2380    });2381    actions.appendChild(editBtn);23822383    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2384    // "···" toggle was zero-savings (the toggle button took the same space2385    // the "2FA" label needed) and made the code one extra click away.2386    if (entry.hasTotp) void openTOTPTray();23872388    platter.appendChild(actionsGroup);2389    container.appendChild(platter);2390  }23912392  /**2393   * Inline-popup edit mode. Swaps the silver platter for an editable form2394   * over the same shadow-DOM surface so the user never leaves the page.2395   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2396   * with the new fields. Cancel returns without writing.2397   */2398  async function renderInlineEdit(summary: SelectorEntry) {2399    container.innerHTML = "";2400    const wrap = document.createElement("div");2401    wrap.className = "create-form-wrap";24022403    const head = document.createElement("div");2404    head.className = "create-head";2405    const back = document.createElement("button");2406    back.className = "back-btn";2407    back.type = "button";2408    back.title = "Cancel";2409    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>`;2410    back.addEventListener("click", () => renderSilverPlatter(summary));2411    head.appendChild(back);2412    const headLbl = document.createElement("div");2413    headLbl.className = "create-label";2414    headLbl.textContent = "Edit entry";2415    head.appendChild(headLbl);2416    wrap.appendChild(head);24172418    const body = document.createElement("div");2419    body.className = "create-body";24202421    // Loading shimmer while we fetch the full entry2422    const loading = document.createElement("div");2423    loading.className = "empty-hint";2424    loading.textContent = "loading…";2425    body.appendChild(loading);2426    wrap.appendChild(body);2427    container.appendChild(wrap);24282429    const [res, idRes] = await Promise.all([2430      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2431      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2432      chrome.runtime.sendMessage({2433        type: "GET_ENTRY_FOR_EDIT",2434        payload: { id: summary.id },2435      }).catch(() => null),2436      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2437    ]);2438    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2439    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];24402441    if (!entryRes || !entryRes.ok || !entryRes.data) {2442      loading.textContent = "couldn't load this entry. try again from the popup.";2443      return;2444    }2445    body.innerHTML = "";24462447    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2448      const group = document.createElement("div");2449      group.className = "f-group";2450      const lbl = document.createElement("div");2451      lbl.className = "f-label";2452      lbl.textContent = label;2453      const input = document.createElement("input");2454      input.className = "f-input";2455      input.type = type;2456      input.value = value;2457      input.autocomplete = "off";2458      group.append(lbl, input);2459      body.appendChild(group);2460      return { g: group, inp: input };2461    }24622463    const titleInput = field("title", entryRes.data.title ?? "").inp;2464    const urlInput = field("url", entryRes.data.url ?? "").inp;2465    urlInput.classList.add("url-f");2466    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2467    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2468    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2469    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2470    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");24712472    // Password row with reveal toggle + generator2473    const pwGroup = document.createElement("div");2474    pwGroup.className = "f-group";2475    const pwLbl = document.createElement("div");2476    pwLbl.className = "f-label";2477    pwLbl.textContent = "password";2478    const pwRow = document.createElement("div");2479    pwRow.className = "f-row";2480    const pwInput = document.createElement("input");2481    pwInput.className = "f-input";2482    pwInput.type = "password";2483    pwInput.value = entryRes.data.password ?? "";2484    pwInput.autocomplete = "new-password";2485    const revealBtn = document.createElement("button");2486    revealBtn.className = "gen-btn";2487    revealBtn.type = "button";2488    revealBtn.textContent = "show";2489    revealBtn.addEventListener("click", () => {2490      const reveal = pwInput.type === "password";2491      pwInput.type = reveal ? "text" : "password";2492      revealBtn.textContent = reveal ? "hide" : "show";2493    });2494    pwRow.append(pwInput, revealBtn);2495    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2496    editSmartGen.root.style.display = "none";2497    let editGenVisible = false;2498    const genToggleBtn = document.createElement("button");2499    genToggleBtn.className = "gen-toggle-link";2500    genToggleBtn.type = "button";2501    genToggleBtn.textContent = "⚙ generate";2502    genToggleBtn.addEventListener("click", () => {2503      editGenVisible = !editGenVisible;2504      pwRow.style.display = editGenVisible ? "none" : "";2505      editSmartGen.root.style.display = editGenVisible ? "" : "none";2506      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2507    });2508    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2509    body.appendChild(pwGroup);25102511    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;25122513    // Notes2514    const notesGroup = document.createElement("div");2515    notesGroup.className = "f-group";2516    const notesLbl = document.createElement("div");2517    notesLbl.className = "f-label";2518    notesLbl.textContent = "notes";2519    const notesInput = document.createElement("textarea");2520    notesInput.className = "f-input";2521    notesInput.rows = 3;2522    notesInput.value = entryRes.data.notes ?? "";2523    notesInput.style.fontFamily = "Inter, sans-serif";2524    notesInput.style.resize = "vertical";2525    notesGroup.append(notesLbl, notesInput);2526    body.appendChild(notesGroup);25272528    // Save / Cancel row2529    const actionsRow = document.createElement("div");2530    actionsRow.className = "f-row";2531    const saveBtn = document.createElement("button");2532    saveBtn.className = "save-btn";2533    saveBtn.type = "button";2534    saveBtn.textContent = "Save changes";2535    saveBtn.style.flex = "1";2536    const cancelBtn = document.createElement("button");2537    cancelBtn.className = "gen-btn";2538    cancelBtn.type = "button";2539    cancelBtn.textContent = "cancel";2540    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2541    actionsRow.append(saveBtn, cancelBtn);2542    body.appendChild(actionsRow);25432544    saveBtn.addEventListener("click", async () => {2545      saveBtn.disabled = true;2546      const originalLabel = saveBtn.textContent;2547      saveBtn.textContent = "Saving…";2548      const patch: Record<string, unknown> = {2549        title: titleInput.value.trim(),2550        url: urlInput.value.trim(),2551        username: usernameInput.value.trim(),2552        email: emailInput.value.trim() || undefined,2553        password: pwInput.value,2554        totp: totpInput.value.trim(),2555        notes: notesInput.value,2556      };2557      const updateRes = (await chrome.runtime.sendMessage({2558        type: "UPDATE_ENTRY",2559        payload: { id: summary.id, patch },2560      }).catch(() => null)) as { ok: boolean; error?: string } | null;2561      if (!updateRes?.ok) {2562        saveBtn.disabled = false;2563        saveBtn.textContent = originalLabel;2564        const err = document.createElement("div");2565        err.className = "empty-hint";2566        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2567        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2568        body.appendChild(err);2569        setTimeout(() => err.remove(), 3000);2570        return;2571      }2572      // Refresh the platter with updated summary fields2573      const refreshed: SelectorEntry = {2574        id: summary.id,2575        title: patch.title as string,2576        username: patch.username as string,2577        email: patch.email as string | undefined,2578        url: patch.url as string,2579        hasTotp: Boolean(patch.totp),2580        hasPasskey: summary.hasPasskey,2581      };2582      renderSilverPlatter(refreshed);2583    });25842585    queueMicrotask(() => titleInput.focus());2586  }25872588  function renderLocked() {2589    container.innerHTML = "";25902591    // Domain header (same as list view)2592    const domHdr = document.createElement("div");2593    domHdr.className = "domain-header";2594    const eyebrow = document.createElement("div");2595    eyebrow.className = "domain-eyebrow";2596    eyebrow.textContent = "vault locked";2597    const domName = document.createElement("div");2598    domName.className = "domain-name";2599    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2600    domHdr.append(eyebrow, domName);2601    container.appendChild(domHdr);26022603    const wrap = document.createElement("div");2604    wrap.className = "locked-wrap";26052606    // Icon + label row2607    const head = document.createElement("div"); head.className = "locked-head";2608    const icon = document.createElement("div"); icon.className = "locked-icon";2609    icon.innerHTML = keySvgStr();2610    const title = document.createElement("div"); title.className = "locked-title";2611    title.textContent = "unlock to autofill";2612    head.append(icon, title);26132614    // The master password is NEVER collected in page-hosted DOM. A malicious2615    // page can observe keystrokes on the shared DOM event stream (a capture-2616    // phase listener registered before Peach injects sees every key before any2617    // stopImmediatePropagation), which would leak the vault's root secret2618    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2619    // where keystrokes are isolated from the page. After the user unlocks2620    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2621    // automatically (see content/index.ts), so the flow resumes on its own.2622    const sub = document.createElement("div");2623    sub.className = "locked-sub";2624    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";26252626    const openBtn = document.createElement("button");2627    openBtn.className = "locked-btn";2628    openBtn.type = "button";2629    openBtn.textContent = "Open Peach to unlock";2630    openBtn.addEventListener("click", () => {2631      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2632      openBtn.textContent = "opening Peach…";2633      openBtn.disabled = true;2634      // openPopup() can't always open programmatically (browser/version/gesture2635      // limits); reset so the user can retry or click the toolbar icon.2636      setTimeout(() => {2637        if (openBtn.isConnected) {2638          openBtn.textContent = "Open Peach to unlock";2639          openBtn.disabled = false;2640        }2641      }, 2500);2642    });26432644    wrap.append(head, sub, openBtn);2645    container.appendChild(wrap);2646  }26472648  function handleKeyDown(e: KeyboardEvent) {2649    if (options.locked) {2650      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2651      return;2652    }2653    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2654      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2655      return;2656    }2657    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2658    const count = allEntryEls.length;2659    if (document.activeElement === searchInput) {2660      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2661      if (count === 0) return;2662      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2663    }2664    if (count === 0) return;2665    switch (e.key) {2666      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2667      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2668      case "Enter": {2669        if (focusedIndex >= 0) {2670          const el = allEntryEls[focusedIndex] as HTMLElement;2671          const id = el.dataset.id;2672          if (id) { onSelect(id); dismiss(); }2673          else if (el.classList.contains("is-new") || !id) {2674            // "New entry" row (last item, no data-id)2675            showCreateForm();2676          }2677        }2678        break;2679      }2680      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2681    }2682  }26832684  document.addEventListener("keydown", handleKeyDown);26852686  // Type-to-search from the silver platter. A printable single-character2687  // keystroke (no modifier) seeds the search query and switches into the2688  // list view, so the user can pivot to a different entry without first2689  // clicking the search icon. Capture phase so the anchor input does not2690  // receive the character before we hijack it.2691  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2692    if (currentMode !== "silver-platter") return;2693    if (e.ctrlKey || e.metaKey || e.altKey) return;2694    if (e.key.length !== 1) return;2695    e.preventDefault();2696    e.stopImmediatePropagation();2697    query = e.key;2698    renderList();2699  };2700  document.addEventListener("keydown", silverPlatterTypeHandler, true);2701  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));27022703  (modalAncestor ?? document.body).appendChild(host);27042705  function updatePosition() {2706    const r = anchorEl.getBoundingClientRect();2707    host.style.top = `${r.bottom + (modalAncestor ? 0 : window.scrollY) + 5}px`;2708    host.style.left = `${r.left + (modalAncestor ? 0 : window.scrollX)}px`;2709    host.style.width = `${popupWidth}px`;2710  }2711  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27122713  if (options.locked) {2714    renderLocked();2715  } else if (options.isSignup && options.savedIdentities) {2716    // State 10: identity helper — signup form detected, show derived2717    // identity list (emails then usernames) instead of vault entry list.2718    renderIdentityHelper();2719  } else if (entries.length === 1 && !options.isSignup) {2720    // Silver platter (State 1): single domain match → focused fill view.2721    // Multi-match goes through renderList instead.2722    renderSilverPlatter(entries[0]!);2723  } else {2724    renderList();2725  }27262727  let exitScheduled = false;2728  function dismiss(userAction = false) {2729    // Idempotent: dismiss() can be called from multiple paths (Escape,2730    // outside click, entry select, fill success, host page nav). The exit2731    // animation must only play once and host.remove() must run exactly once.2732    if (exitScheduled) return;2733    exitScheduled = true;2734    // Detach listeners synchronously so nothing can re-trigger during the2735    // 130ms exit window (a focusin firing here would race against the2736    // dismiss-lock work in Pass 2).2737    stopObserving();2738    document.removeEventListener("click", outsideClick, { capture: true });2739    document.removeEventListener("keydown", handleKeyDown);2740    for (const cleanup of cleanupHooks) {2741      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2742    }2743    if (userAction) options.onDismiss?.();2744    container.classList.add("is-exiting");2745    setTimeout(() => host.remove(), 130);2746  }27472748  function outsideClick(ev: MouseEvent) {2749    const path = ev.composedPath();2750    // Never dismiss when clicking the anchor field itself — that click is2751    // what triggered the selector to open, and the user may click the field2752    // again to re-focus it without intending to close the selector.2753    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2754  }2755  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2756  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);27572758  return dismiss;2759}27602761export function showTOTPSelector(2762  anchorEl: HTMLInputElement,2763  entries: SelectorEntry[],2764  onFill: (id: string) => void,2765  options: { domain?: string; onDismiss?: () => void } = {}2766): () => void {2767  const host = document.createElement("div");2768  host.style.cssText = "position: absolute; z-index: 2147483647;";2769  host.style.setProperty("--peach-accent", accentHex);2770  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2771  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2772  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2773  const shadow = host.attachShadow({ mode: "closed" });27742775  const style = shadow.appendChild(document.createElement("style"));2776  style.textContent = SELECTOR_STYLES;27772778  const rect = anchorEl.getBoundingClientRect();2779  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2780  host.style.left = `${rect.left + window.scrollX}px`;2781  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2782  host.style.width = `${popupWidth}px`;27832784  const container = shadow.appendChild(document.createElement("div"));2785  container.className = "peach-inline-popup";2786  container.setAttribute("data-theme", popupTheme);27872788  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2789  const current = entries.filter((entry) => entry.hasTotp);2790  let focusedIndex = current.length === 1 ? 0 : -1;27912792  function updatePosition() {2793    const r = anchorEl.getBoundingClientRect();2794    host.style.top = `${r.bottom + window.scrollY + 5}px`;2795    host.style.left = `${r.left + window.scrollX}px`;2796    host.style.width = `${popupWidth}px`;2797  }27982799  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);28002801  function choose(entry: SelectorEntry) {2802    onFill(entry.id);2803    dismiss();2804  }28052806  function render() {2807    container.innerHTML = "";28082809    const domHdr = document.createElement("div");2810    domHdr.className = "domain-header";2811    const headText = document.createElement("div");2812    headText.className = "domain-header-text";2813    const eyebrow = document.createElement("div");2814    eyebrow.className = "domain-eyebrow";2815    eyebrow.textContent = "2FA code";2816    const domName = document.createElement("div");2817    domName.className = "domain-name";2818    domName.textContent = domain;2819    headText.append(eyebrow, domName);2820    domHdr.appendChild(headText);2821    container.appendChild(domHdr);28222823    if (current.length === 1) {2824      const entry = current[0]!;2825      const platter = document.createElement("div");2826      platter.className = "silver-platter";28272828      const title = document.createElement("div");2829      title.className = "sp-title";2830      title.textContent = entry.title;2831      platter.appendChild(title);28322833      const sub = document.createElement("div");2834      sub.className = "sp-username";2835      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2836      platter.appendChild(sub);28372838      const fill = document.createElement("button");2839      fill.className = "sp-fill-btn";2840      fill.type = "button";2841      fill.textContent = "Fill 2FA code";2842      fill.addEventListener("click", () => choose(entry));2843      platter.appendChild(fill);28442845      container.appendChild(platter);2846      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2847      return;2848    }28492850    const results = document.createElement("div");2851    results.className = "results";2852    container.appendChild(results);28532854    for (let i = 0; i < current.length; i++) {2855      const entry = current[i]!;2856      const row = document.createElement("div");2857      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2858      row.dataset.index = String(i);2859      row.setAttribute("tabindex", "-1");28602861      const icon = document.createElement("div");2862      icon.className = "entry-icon";2863      icon.innerHTML = keySvgStr();2864      row.appendChild(icon);2865      const info = document.createElement("div");2866      info.className = "entry-info";2867      const title = document.createElement("div");2868      title.className = "entry-title";2869      title.textContent = entry.title;2870      const sub = document.createElement("div");2871      sub.className = "entry-sub";2872      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2873      info.append(title, sub);2874      row.appendChild(info);28752876      const badge = document.createElement("span");2877      badge.className = "totp-badge";2878      badge.textContent = "Fill";2879      row.appendChild(badge);2880      row.addEventListener("click", () => choose(entry));2881      results.appendChild(row);2882    }2883  }28842885  function setFocused(index: number) {2886    focusedIndex = index;2887    container.querySelectorAll(".entry").forEach((el, i) => {2888      el.classList.toggle("focused", i === focusedIndex);2889      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2890    });2891  }28922893  function handleKeyDown(e: KeyboardEvent) {2894    if (e.key === "Escape" || e.key === "Tab") {2895      e.preventDefault();2896      dismiss(true);2897      return;2898    }2899    if (current.length === 0) return;2900    if (e.key === "Enter") {2901      e.preventDefault();2902      choose(current[Math.max(0, focusedIndex)]!);2903      return;2904    }2905    if (current.length === 1) return;2906    if (e.key === "ArrowDown") {2907      e.preventDefault();2908      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2909    } else if (e.key === "ArrowUp") {2910      e.preventDefault();2911      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2912    }2913  }29142915  let exitScheduled = false;2916  function dismiss(userAction = false) {2917    if (exitScheduled) return;2918    exitScheduled = true;2919    stopObserving();2920    document.removeEventListener("click", outsideClick, { capture: true });2921    document.removeEventListener("keydown", handleKeyDown);2922    if (userAction) options.onDismiss?.();2923    container.classList.add("is-exiting");2924    setTimeout(() => host.remove(), 130);2925  }29262927  function outsideClick(ev: MouseEvent) {2928    const path = ev.composedPath();2929    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2930  }29312932  document.addEventListener("keydown", handleKeyDown);2933  document.body.appendChild(host);2934  render();2935  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);29362937  return dismiss;2938}29392940export interface CardSelectorEntry {2941  id: string;2942  title: string;2943  cardholderName?: string;2944  last4?: string;2945  expMonth?: string;2946  expYear?: string;2947  network?: import("../shared/types").CardNetwork;2948}29492950interface CardSelectorOptions {2951  domain?: string;2952  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2953  onFill: (entry: import("../shared/types").VaultEntry) => void;2954  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2955  onDismiss?: () => void;2956}29572958/**2959 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2960 * passkey create or get. Renders as a fixed-position floating popup (no2961 * field anchor needed — passkeys don't require a focused input). Uses the2962 * same theme tokens and entrance animation as all other inline popup states.2963 */2964export function showPasskeyProGate(): void {2965  const domain = location.hostname.replace(/^www\./, "");29662967  const host = document.createElement("div");2968  host.setAttribute("data-peach-passkey-gate", "1");2969  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2970  const shadow = host.attachShadow({ mode: "closed" });29712972  const style = document.createElement("style");2973  style.textContent = `2974    :host { all: initial; }2975    .gate-wrap {2976      position: fixed;2977      top: 50%;2978      left: 50%;2979      transform: translate(-50%, -50%);2980      width: 280px;2981      pointer-events: auto;2982      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2983    }2984    @keyframes g-in {2985      from { opacity:0; transform: translate(-50%,-52%); }2986      to   { opacity:1; transform: translate(-50%,-50%); }2987    }2988    .gate-wrap.is-exiting {2989      animation: g-out 130ms ease-in forwards;2990    }2991    @keyframes g-out {2992      to { opacity:0; transform: translate(-50%,-52%); }2993    }2994    .gate {2995      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2996      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2997      border-radius: 12px;2998      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2999      padding: 16px;3000      font-family: Inter, sans-serif;3001    }3002    .gate-header {3003      display: flex;3004      align-items: center;3005      gap: 7px;3006      margin-bottom: 12px;3007      padding-bottom: 10px;3008      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3009    }3010    .gate-domain {3011      font-size: 12px;3012      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3013      font-family: "IBM Plex Mono", monospace;3014      overflow: hidden;3015      text-overflow: ellipsis;3016      white-space: nowrap;3017    }3018    .gate-title {3019      font-size: 14px;3020      font-weight: 500;3021      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3022      margin-bottom: 6px;3023    }3024    .gate-subtitle {3025      font-size: 12px;3026      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3027      line-height: 1.5;3028      margin-bottom: 14px;3029    }3030    .gate-btn {3031      display: block;3032      width: 100%;3033      padding: 9px 0;3034      border-radius: 8px;3035      border: none;3036      cursor: pointer;3037      font-size: 13px;3038      font-family: Inter, sans-serif;3039      font-weight: 500;3040      transition: opacity 100ms;3041      margin-bottom: 7px;3042      text-align: center;3043    }3044    .gate-btn:last-child { margin-bottom: 0; }3045    .gate-btn--accent {3046      background: ${accentHex};3047      color: #fff;3048    }3049    .gate-btn--accent:hover { opacity: 0.88; }3050    .gate-btn--ghost {3051      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3052      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3053    }3054    .gate-btn--ghost:hover { opacity: 0.75; }3055    .backdrop {3056      position: fixed;3057      inset: 0;3058      pointer-events: auto;3059    }3060  `;3061  shadow.appendChild(style);30623063  const backdrop = document.createElement("div");3064  backdrop.className = "backdrop";3065  shadow.appendChild(backdrop);30663067  const wrap = document.createElement("div");3068  wrap.className = "gate-wrap";3069  shadow.appendChild(wrap);30703071  const gate = document.createElement("div");3072  gate.className = "gate";3073  wrap.appendChild(gate);30743075  // Header: peach icon + domain3076  const header = document.createElement("div");3077  header.className = "gate-header";3078  const icon = document.createElement("span");3079  icon.innerHTML = peachIconSvg();3080  const domainEl = document.createElement("span");3081  domainEl.className = "gate-domain";3082  domainEl.textContent = domain;3083  header.append(icon, domainEl);3084  gate.appendChild(header);30853086  const title = document.createElement("div");3087  title.className = "gate-title";3088  title.textContent = "Passkeys are part of Peach Pro.";3089  gate.appendChild(title);30903091  const subtitle = document.createElement("div");3092  subtitle.className = "gate-subtitle";3093  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3094  gate.appendChild(subtitle);30953096  const upgradeBtn = document.createElement("button");3097  upgradeBtn.className = "gate-btn gate-btn--accent";3098  upgradeBtn.type = "button";3099  upgradeBtn.textContent = "Upgrade to Pro";3100  gate.appendChild(upgradeBtn);31013102  const laterBtn = document.createElement("button");3103  laterBtn.className = "gate-btn gate-btn--ghost";3104  laterBtn.type = "button";3105  laterBtn.textContent = "Not right now";3106  gate.appendChild(laterBtn);31073108  function dismiss() {3109    wrap.classList.add("is-exiting");3110    setTimeout(() => host.remove(), 130);3111  }31123113  upgradeBtn.addEventListener("click", () => {3114    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3115    dismiss();3116  });3117  laterBtn.addEventListener("click", dismiss);3118  backdrop.addEventListener("click", dismiss);31193120  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3121    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3122  });31233124  document.body.appendChild(host);3125}31263127/**3128 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3129 * detector sees the page invoke navigator.credentials.create(); content/index.ts3130 * checks vault + decline state then calls this. "Save passkey to Peach"3131 * initiates the popup-context credential flow; "Not now" records a 30-day3132 * decline for the domain so we don't re-show on every page reload.3133 */3134export function showPasskeyRegistrationOffer(args: {3135  rpId: string;3136  rpName?: string;3137  userName?: string;3138  userDisplayName?: string;3139}): void {3140  const domain = location.hostname.replace(/^www\./, "");3141  const displayName = args.rpName || domain;31423143  const host = document.createElement("div");3144  host.setAttribute("data-peach-passkey-offer", "1");3145  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3146  const shadow = host.attachShadow({ mode: "closed" });31473148  const style = document.createElement("style");3149  style.textContent = `3150    :host { all: initial; }3151    .offer-wrap {3152      position: fixed;3153      top: 16px;3154      right: 16px;3155      width: 320px;3156      pointer-events: auto;3157      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3158    }3159    @keyframes o-in {3160      from { opacity: 0; transform: translateY(-6px); }3161      to   { opacity: 1; transform: translateY(0); }3162    }3163    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3164    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3165    .offer {3166      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3167      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3168      border-radius: 12px;3169      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3170      padding: 14px 14px 12px;3171      font-family: Inter, sans-serif;3172      position: relative;3173    }3174    .offer-close {3175      position: absolute;3176      top: 8px;3177      right: 8px;3178      width: 18px;3179      height: 18px;3180      border: none;3181      background: transparent;3182      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3183      cursor: pointer;3184      font-size: 14px;3185      line-height: 1;3186      padding: 0;3187    }3188    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3189    .offer-header {3190      display: flex;3191      align-items: center;3192      gap: 7px;3193      margin-bottom: 8px;3194      padding-bottom: 8px;3195      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3196    }3197    .offer-domain {3198      font-size: 12px;3199      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3200      font-family: "IBM Plex Mono", monospace;3201      overflow: hidden;3202      text-overflow: ellipsis;3203      white-space: nowrap;3204    }3205    .offer-title {3206      font-size: 13px;3207      font-weight: 500;3208      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3209      margin-bottom: 4px;3210    }3211    .offer-subtitle {3212      font-size: 11px;3213      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3214      line-height: 1.45;3215      margin-bottom: 12px;3216    }3217    .offer-btn {3218      display: block;3219      width: 100%;3220      padding: 8px 0;3221      border-radius: 7px;3222      border: none;3223      cursor: pointer;3224      font-size: 12px;3225      font-family: Inter, sans-serif;3226      font-weight: 500;3227      transition: opacity 100ms;3228      margin-bottom: 6px;3229      text-align: center;3230    }3231    .offer-btn:last-child { margin-bottom: 0; }3232    .offer-btn--accent { background: ${accentHex}; color: #fff; }3233    .offer-btn--accent:hover { opacity: 0.88; }3234    .offer-btn--ghost {3235      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3236      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3237    }3238    .offer-btn--ghost:hover { opacity: 0.75; }3239  `;3240  shadow.appendChild(style);32413242  const wrap = document.createElement("div");3243  wrap.className = "offer-wrap";3244  shadow.appendChild(wrap);32453246  const offer = document.createElement("div");3247  offer.className = "offer";3248  wrap.appendChild(offer);32493250  const closeBtn = document.createElement("button");3251  closeBtn.className = "offer-close";3252  closeBtn.type = "button";3253  closeBtn.setAttribute("aria-label", "Dismiss");3254  closeBtn.textContent = "✕";3255  offer.appendChild(closeBtn);32563257  const header = document.createElement("div");3258  header.className = "offer-header";3259  const icon = document.createElement("span");3260  icon.innerHTML = peachIconSvg();3261  const domainEl = document.createElement("span");3262  domainEl.className = "offer-domain";3263  domainEl.textContent = domain;3264  header.append(icon, domainEl);3265  offer.appendChild(header);32663267  const title = document.createElement("div");3268  title.className = "offer-title";3269  title.textContent = "This site supports passkeys.";3270  offer.appendChild(title);32713272  const subtitle = document.createElement("div");3273  subtitle.className = "offer-subtitle";3274  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3275  offer.appendChild(subtitle);32763277  const saveBtn = document.createElement("button");3278  saveBtn.className = "offer-btn offer-btn--accent";3279  saveBtn.type = "button";3280  saveBtn.textContent = "Save passkey to Peach";3281  offer.appendChild(saveBtn);32823283  const laterBtn = document.createElement("button");3284  laterBtn.className = "offer-btn offer-btn--ghost";3285  laterBtn.type = "button";3286  laterBtn.textContent = "Not now";3287  offer.appendChild(laterBtn);32883289  function dismiss(decline: boolean) {3290    if (decline) {3291      chrome.runtime.sendMessage({3292        type: "PASSKEY_OFFER_DECLINE",3293        payload: { domain },3294      }).catch(() => {});3295    }3296    wrap.classList.add("is-exiting");3297    setTimeout(() => host.remove(), 130);3298  }32993300  saveBtn.addEventListener("click", () => {3301    chrome.runtime.sendMessage({3302      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3303      payload: {3304        rpId: args.rpId,3305        rpName: args.rpName ?? displayName,3306        userName: args.userName ?? "user",3307        userDisplayName: args.userDisplayName,3308      },3309    }).catch(() => {});3310    dismiss(false);3311  });3312  laterBtn.addEventListener("click", () => dismiss(true));3313  closeBtn.addEventListener("click", () => dismiss(true));33143315  document.body.appendChild(host);3316}33173318/**3319 * State 11 — passkey available indicator. Shown when the user lands on a3320 * domain for which they already have a stored passkey. Tells them where to3321 * find it (the entry already shows in the vault list); the "Sign in with3322 * passkey" button opens the popup so they can use the platform authenticator3323 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3324 * the actual sign-in transparently, so this banner is informational only.3325 */3326export function showPasskeyAvailable(args: {3327  rpId: string;3328  userName: string;3329  fromBrowser?: "chrome" | "firefox";3330  currentBrowser?: "chrome" | "firefox" | "unknown";3331}): void {3332  const domain = location.hostname.replace(/^www\./, "");3333  const crossBrowser =3334    args.fromBrowser &&3335    args.currentBrowser &&3336    args.currentBrowser !== "unknown" &&3337    args.fromBrowser !== args.currentBrowser;33383339  const host = document.createElement("div");3340  host.setAttribute("data-peach-passkey-available", "1");3341  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3342  const shadow = host.attachShadow({ mode: "closed" });33433344  const style = document.createElement("style");3345  style.textContent = `3346    :host { all: initial; }3347    .avail-wrap {3348      position: fixed;3349      top: 16px;3350      right: 16px;3351      width: 320px;3352      pointer-events: auto;3353      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3354    }3355    @keyframes a-in {3356      from { opacity: 0; transform: translateY(-6px); }3357      to   { opacity: 1; transform: translateY(0); }3358    }3359    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3360    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3361    .avail {3362      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3363      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3364      border-radius: 12px;3365      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3366      padding: 14px 14px 12px;3367      font-family: Inter, sans-serif;3368      position: relative;3369    }3370    .avail-close {3371      position: absolute;3372      top: 8px;3373      right: 8px;3374      width: 18px;3375      height: 18px;3376      border: none;3377      background: transparent;3378      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3379      cursor: pointer;3380      font-size: 14px;3381      line-height: 1;3382      padding: 0;3383    }3384    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3385    .avail-header {3386      display: flex;3387      align-items: center;3388      gap: 7px;3389      margin-bottom: 8px;3390      padding-bottom: 8px;3391      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3392    }3393    .avail-domain {3394      font-size: 12px;3395      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3396      font-family: "IBM Plex Mono", monospace;3397    }3398    .avail-label {3399      font-size: 9px;3400      letter-spacing: 0.16em;3401      text-transform: uppercase;3402      color: ${accentHex};3403      margin-bottom: 4px;3404    }3405    .avail-user {3406      font-size: 13px;3407      font-weight: 500;3408      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3409      margin-bottom: 12px;3410      overflow: hidden;3411      text-overflow: ellipsis;3412      white-space: nowrap;3413    }3414    .avail-cross {3415      font-size: 11px;3416      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3417      line-height: 1.45;3418      margin-bottom: 12px;3419      padding: 8px;3420      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3421      border-radius: 6px;3422    }3423    .avail-btn {3424      display: block;3425      width: 100%;3426      padding: 8px 0;3427      border-radius: 7px;3428      border: none;3429      cursor: pointer;3430      font-size: 12px;3431      font-family: Inter, sans-serif;3432      font-weight: 500;3433      transition: opacity 100ms;3434      margin-bottom: 6px;3435      text-align: center;3436    }3437    .avail-btn:last-child { margin-bottom: 0; }3438    .avail-btn--accent { background: ${accentHex}; color: #fff; }3439    .avail-btn--accent:hover { opacity: 0.88; }3440    .avail-btn--ghost {3441      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3442      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3443    }3444    .avail-btn--ghost:hover { opacity: 0.75; }3445  `;3446  shadow.appendChild(style);34473448  const wrap = document.createElement("div");3449  wrap.className = "avail-wrap";3450  shadow.appendChild(wrap);34513452  const avail = document.createElement("div");3453  avail.className = "avail";3454  wrap.appendChild(avail);34553456  const closeBtn = document.createElement("button");3457  closeBtn.className = "avail-close";3458  closeBtn.type = "button";3459  closeBtn.setAttribute("aria-label", "Dismiss");3460  closeBtn.textContent = "✕";3461  avail.appendChild(closeBtn);34623463  const header = document.createElement("div");3464  header.className = "avail-header";3465  const icon = document.createElement("span");3466  icon.innerHTML = peachIconSvg();3467  const domainEl = document.createElement("span");3468  domainEl.className = "avail-domain";3469  domainEl.textContent = domain;3470  header.append(icon, domainEl);3471  avail.appendChild(header);34723473  const label = document.createElement("div");3474  label.className = "avail-label";3475  label.textContent = "PASSKEY";3476  avail.appendChild(label);34773478  const user = document.createElement("div");3479  user.className = "avail-user";3480  user.textContent = args.userName;3481  avail.appendChild(user);34823483  if (crossBrowser) {3484    const cross = document.createElement("div");3485    cross.className = "avail-cross";3486    cross.textContent =3487      args.fromBrowser === "chrome"3488        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3489        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3490    avail.appendChild(cross);3491  }34923493  const signInBtn = document.createElement("button");3494  signInBtn.className = "avail-btn avail-btn--accent";3495  signInBtn.type = "button";3496  signInBtn.textContent = "Sign in with passkey";3497  avail.appendChild(signInBtn);34983499  const passwordBtn = document.createElement("button");3500  passwordBtn.className = "avail-btn avail-btn--ghost";3501  passwordBtn.type = "button";3502  passwordBtn.textContent = "Use password instead";3503  avail.appendChild(passwordBtn);35043505  function dismiss() {3506    wrap.classList.add("is-exiting");3507    setTimeout(() => host.remove(), 130);3508  }35093510  signInBtn.addEventListener("click", () => {3511    // On Chrome: the user clicking the page's own Sign-in button is what3512    //   triggers webAuthenticationProxy → existing background flow handles it.3513    //   Our button just dismisses since the page itself drives auth.3514    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3515    //   and surface the entry for manual reference (popup view).3516    dismiss();3517    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3518  });3519  passwordBtn.addEventListener("click", dismiss);3520  closeBtn.addEventListener("click", dismiss);35213522  document.body.appendChild(host);3523}35243525/**3526 * State 7 — card silver platter. Single-card focused fill view rendered3527 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3528 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3529 * so card and login flows render identically. Multi-card list view is a3530 * follow-up; today this picks the first card.3531 */3532export function showCardSelector(3533  anchorEl: HTMLInputElement,3534  cards: CardSelectorEntry[],3535  options: CardSelectorOptions3536): () => void {3537  if (cards.length === 0) return () => {};3538  const card = cards[0]!;35393540  const host = document.createElement("div");3541  host.style.cssText = "position: absolute; z-index: 2147483647;";3542  host.style.setProperty("--peach-accent", accentHex);3543  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3544  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3545  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3546  const shadow = host.attachShadow({ mode: "closed" });35473548  const style = shadow.appendChild(document.createElement("style"));3549  style.textContent = SELECTOR_STYLES;35503551  const rect = anchorEl.getBoundingClientRect();3552  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3553  host.style.left = `${rect.left + window.scrollX}px`;3554  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;35553556  const container = shadow.appendChild(document.createElement("div"));3557  container.className = "peach-inline-popup";3558  container.setAttribute("data-theme", popupTheme);35593560  // Domain header — eyebrow communicates the card context, not the site3561  const domHdr = document.createElement("div");3562  domHdr.className = "domain-header";3563  const eyebrow = document.createElement("div");3564  eyebrow.className = "domain-eyebrow";3565  eyebrow.textContent = "Pay with Peach";3566  const domName = document.createElement("div");3567  domName.className = "domain-name";3568  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3569  domHdr.append(eyebrow, domName);3570  container.appendChild(domHdr);35713572  const platter = document.createElement("div");3573  platter.className = "card-platter";35743575  if (card.network && card.network !== "unknown") {3576    const net = document.createElement("div");3577    net.className = "cp-network";3578    net.textContent = card.network;3579    platter.appendChild(net);3580  }35813582  const nick = document.createElement("div");3583  nick.className = "cp-nickname";3584  nick.textContent = card.title;3585  platter.appendChild(nick);35863587  if (card.last4) {3588    const l4 = document.createElement("div");3589    l4.className = "cp-last4";3590    l4.textContent = `•••• ${card.last4}`;3591    platter.appendChild(l4);3592  }35933594  const meta = document.createElement("div");3595  meta.className = "cp-meta";3596  if (card.cardholderName) {3597    const name = document.createElement("span");3598    name.textContent = card.cardholderName;3599    meta.appendChild(name);3600  }3601  if (card.expMonth && card.expYear) {3602    if (card.cardholderName) {3603      const sep = document.createElement("span");3604      sep.className = "cp-meta-sep";3605      sep.textContent = "·";3606      meta.appendChild(sep);3607    }3608    const exp = document.createElement("span");3609    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3610    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3611    meta.appendChild(exp);3612  }3613  if (meta.childElementCount > 0) platter.appendChild(meta);36143615  const fillWrap = document.createElement("div");3616  fillWrap.className = "cp-fill-wrap";3617  const fillBtn = document.createElement("button");3618  fillBtn.className = "sp-fill-btn";3619  fillBtn.type = "button";3620  fillBtn.textContent = "Fill card details";3621  fillBtn.addEventListener("click", async () => {3622    if (fillBtn.disabled) return;3623    fillBtn.disabled = true;3624    fillBtn.classList.add("filled");3625    fillBtn.innerHTML = checkSvgStr();3626    const resp = await chrome.runtime.sendMessage({3627      type: "GET_ENTRY_FOR_FILL",3628      payload: { id: card.id },3629    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3630    if (resp?.ok && resp.data) options.onFill(resp.data);3631    setTimeout(() => dismiss(), 400);3632  });3633  fillWrap.appendChild(fillBtn);3634  platter.appendChild(fillWrap);36353636  // Secondary actions — copy number, copy CVC, dismiss3637  const actions = document.createElement("div");3638  actions.className = "sp-actions";36393640  function flashBtn(b: HTMLButtonElement) {3641    b.classList.add("flashed");3642    setTimeout(() => b.classList.remove("flashed"), 700);3643  }36443645  // M3/QUA-005: clipboard + background COPY both failed — show user.3646  function flashCopyError(b: HTMLButtonElement) {3647    const original = b.textContent ?? "";3648    b.textContent = "Blocked";3649    b.classList.add("flashed");3650    setTimeout(() => {3651      b.classList.remove("flashed");3652      if (b.isConnected) b.textContent = original;3653    }, 1200);3654  }36553656  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3657    const resp = await chrome.runtime.sendMessage({3658      type: "GET_ENTRY_FOR_FILL",3659      payload: { id: card.id },3660    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3661    return resp?.ok && resp.data ? resp.data : null;3662  }36633664  const copyNum = document.createElement("button");3665  copyNum.className = "sp-action-btn";3666  copyNum.type = "button";3667  copyNum.title = "Copy card number";3668  copyNum.textContent = "Copy number";3669  copyNum.addEventListener("click", async (e) => {3670    e.stopPropagation();3671    const full = await fetchFullCard();3672    if (!full?.cardNumber) return;3673    let alreadyWritten = false;3674    try {3675      await navigator.clipboard.writeText(full.cardNumber);3676      alreadyWritten = true;3677    } catch (err) {3678      console.warn("[Peach] clipboard write denied:", err);3679    }3680    const resp = await chrome.runtime.sendMessage({3681      type: "COPY",3682      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3683    }).catch(() => null) as { ok?: boolean } | null;3684    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3685    else flashCopyError(copyNum);3686  });3687  actions.appendChild(copyNum);36883689  const copyCvc = document.createElement("button");3690  copyCvc.className = "sp-action-btn";3691  copyCvc.type = "button";3692  copyCvc.title = "Copy CVC";3693  copyCvc.textContent = "Copy CVC";3694  copyCvc.addEventListener("click", async (e) => {3695    e.stopPropagation();3696    const full = await fetchFullCard();3697    if (!full?.cvc) return;3698    let alreadyWritten = false;3699    try {3700      await navigator.clipboard.writeText(full.cvc);3701      alreadyWritten = true;3702    } catch (err) {3703      console.warn("[Peach] clipboard write denied:", err);3704    }3705    const resp = await chrome.runtime.sendMessage({3706      type: "COPY",3707      payload: { text: full.cvc, label: "CVC", alreadyWritten },3708    }).catch(() => null) as { ok?: boolean } | null;3709    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3710    else flashCopyError(copyCvc);3711  });3712  actions.appendChild(copyCvc);37133714  const closeBtn = document.createElement("button");3715  closeBtn.className = "sp-action-btn";3716  closeBtn.type = "button";3717  closeBtn.title = "Dismiss";3718  closeBtn.textContent = "✕";3719  closeBtn.addEventListener("click", (e) => {3720    e.stopPropagation();3721    dismiss(true);3722  });3723  actions.appendChild(closeBtn);37243725  platter.appendChild(actions);3726  container.appendChild(platter);37273728  document.body.appendChild(host);3729  function updatePosition() {3730    const r = anchorEl.getBoundingClientRect();3731    host.style.top = `${r.bottom + window.scrollY + 5}px`;3732    host.style.left = `${r.left + window.scrollX}px`;3733  }3734  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);37353736  function onKeyDown(e: KeyboardEvent) {3737    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3738  }3739  document.addEventListener("keydown", onKeyDown);37403741  let exitScheduled = false;3742  function dismiss(userAction = false) {3743    if (exitScheduled) return;3744    exitScheduled = true;3745    stopObserving();3746    document.removeEventListener("click", outsideClick, { capture: true });3747    document.removeEventListener("keydown", onKeyDown);3748    if (userAction) options.onDismiss?.();3749    container.classList.add("is-exiting");3750    setTimeout(() => host.remove(), 130);3751  }37523753  function outsideClick(ev: MouseEvent) {3754    const path = ev.composedPath();3755    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3756  }3757  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);37583759  return dismiss;3760}