inject.ts

144.4 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { generatePassword } from "../shared/generate";14import { generateTOTP } from "../crypto/totp";15import { detectPasswordPolicy } from "./policy";1617let accentHex = "#E8956D";18let popupTheme: "dark" | "light" = "dark";19chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {20  const data = resp?.data;21  const name = data?.accentColor ?? "peach";22  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";23  popupTheme = data?.theme === "light" ? "light" : "dark";24});2526// 8-digit hex alpha helpers for the accent-derived shadow tokens.27// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing28// two hex digits as the alpha channel.29function withAlpha(hex: string, alpha: string): string {30  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS31  // always exposes 6-digit hex, so this is a guard against future changes32  // shipping shorthand colors that would silently break the var injection.33  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;34}3536export interface SelectorEntry {37  id: string;38  title: string;39  username?: string;40  email?: string;41  url?: string;42  hasTotp?: boolean;43  /** True when the entry also has a passkey credential attached. */44  hasPasskey?: boolean;45}4647interface SelectorOptions {48  domain?: string;49  searchableEntries?: SelectorEntry[];50  /** True when shown on a signup form — changes header label and entry-click behaviour */51  isSignup?: boolean;52  /**53   * Derived identity list (emails then usernames) for signup mode (State 10).54   * When present, renderIdentityHelper() is used instead of renderList().55   */56  savedIdentities?: SavedIdentity[];57  /**58   * Called after the user picks a saved identity (signup mode only) or59   * after successfully saving a new entry on a signup form.60   * Lets the caller fill the visible username + password fields.61   */62  onFillFields?: (username: string, password: string) => void;63  /**64   * When true, show an inline unlock form instead of the entries list.65   * Used when the vault is locked so the user can unlock without opening66   * the popup.67   */68  locked?: boolean;69  /**70   * Called after a successful inline unlock — the caller should re-query71   * entries and re-open the selector with real data.72   */73  onUnlocked?: () => void;74  /**75   * Called when the user explicitly dismisses the selector (Escape, Tab, or76   * click outside) — NOT when an entry is selected or on auto-close.77   * Used by the caller to suppress spurious reopens on the same field.78   */79  onDismiss?: () => void;80}8182function getDomainFromUrl(url: string): string {83  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }84}8586function keySvgStr(): string {87  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="rgba(240,232,216,0.35)" stroke-width="0.95" stroke-linecap="round"><rect x="2" y="5.5" width="8" height="6" rx="1.5"/><path d="M4 5.5V4.25A2 2 0 0 1 6 2.25A2 2 0 0 1 8 4.25V5.5"/></svg>`;88}8990function plusSvgStr(): string {91  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>`;92}9394function peachIconSvg(): string {95  // Peach body stays brand-peach regardless of `accentHex` — a sage or96  // sky accent must not turn the autofill icon green or blue. Accent97  // color still tints surrounding glow/hover halos below.98  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>`;99}100101function checkSvgStr(): string {102  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>`;103}104105function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {106  const { hostname, origin } = location;107  const parts = hostname.split(".");108  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",109    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",110    "oidc", "federation", "saml", "cas", "ldap"];111  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());112  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;113  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);114  return { origin, title, loginSubdomain };115}116117/**118 * Shows a bottom-of-page toast after filling credentials when the entry has119 * never matched the current site — offering to add the current origin to the120 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.121 */122export function showRememberSiteToast(123  pageDomain: string,124  entryId: string,125): void {126  const host = document.createElement("div");127  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";128  host.style.setProperty("--peach-accent", accentHex);129  const shadow = host.attachShadow({ mode: "closed" });130131  const style = document.createElement("style");132  style.textContent = `133    .bar {134      display:flex;align-items:center;gap:10px;padding:10px 14px;135      background:#131109;border:1px solid rgba(240,232,216,0.09);136      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);137      font-family:Inter,sans-serif;white-space:nowrap;138      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;139    }140    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }141    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }142    .yes {143      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;144      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;145    }146    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }147    .no {148      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;149      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;150    }151  `;152  shadow.appendChild(style);153154  const bar = document.createElement("div"); bar.className = "bar";155  const txt = document.createElement("span"); txt.className = "txt";156  txt.textContent = `Remember ${pageDomain} for this entry?`;157  const yesBtn = document.createElement("button"); yesBtn.className = "yes";158  yesBtn.textContent = "Remember";159  yesBtn.addEventListener("click", async () => {160    await chrome.runtime.sendMessage({161      type: "ADD_ADDITIONAL_URL",162      payload: { id: entryId, url: location.origin },163    });164    host.remove();165  });166  const noBtn = document.createElement("button"); noBtn.className = "no";167  noBtn.textContent = "Not now";168  noBtn.addEventListener("click", () => host.remove());169  bar.append(txt, yesBtn, noBtn);170  shadow.appendChild(bar);171  document.body.appendChild(host);172  setTimeout(() => host.remove(), 9000);173}174175interface SmartGenerator {176  root: HTMLElement;177  getPassword: () => string;178  /** Copy the current password to the clipboard with the standard pulse UX. */179  copy: () => Promise<void>;180}181182interface SmartGeneratorOptions {183  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */184  policy: PasswordPolicy;185  /**186   * Seed value: used as the displayed password without regenerating, e.g. the187   * password the user already typed into the page. The generator still188   * regenerates the moment any control changes.189   */190  initialPassword?: string;191  /** Fires every time the password regenerates (initial + on changes). */192  onChange?: (pw: string) => void;193}194195/**196 * Build the inline-popup smart-password generator. Mirrors the main popup's197 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset198 * pills + a policy hint that names the constraints Peach detected on the199 * page. Writing this in pure DOM rather than reusing the Solid component200 * keeps the content-script bundle small.201 */202function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {203  const policy = opts.policy ?? {};204205  // Start at site max (strongest password the site accepts), fall back to 64206  let length = policy.maxLength ?? 64;207  if (policy.minLength) length = Math.max(length, policy.minLength);208  if (length < 8) length = 8;209  if (length > 128) length = 128;210211  let upper = true;212  let lower = true;213  let numbers = true;214  let symbols = !policy.forbidsSymbols;215  if (policy.requiresSymbols) symbols = true;216  const forbiddenChars = policy.forbiddenChars ?? "";217218  let password = "";219220  const root = document.createElement("div");221  root.className = "pwgen-block";222223  const displayRow = root.appendChild(document.createElement("div"));224  displayRow.className = "pwgen-display-row";225  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;226  output.type = "text";227  output.className = "pwgen-output";228  output.setAttribute("autocomplete", "off");229  output.setAttribute("spellcheck", "false");230  output.setAttribute("autocorrect", "off");231  output.setAttribute("autocapitalize", "off");232233  const regenBtn = displayRow.appendChild(document.createElement("button"));234  regenBtn.className = "pwgen-icon-btn";235  regenBtn.type = "button";236  regenBtn.setAttribute("aria-label", "Regenerate password");237  regenBtn.title = "Regenerate";238  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>`;239240  const copyBtn = displayRow.appendChild(document.createElement("button"));241  copyBtn.className = "pwgen-icon-btn";242  copyBtn.type = "button";243  copyBtn.setAttribute("aria-label", "Copy password");244  copyBtn.title = "Copy";245  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>`;246247  const controls = root.appendChild(document.createElement("div"));248  controls.className = "pwgen-controls-row";249  const slider = controls.appendChild(document.createElement("input"));250  slider.type = "range";251  slider.className = "pwgen-slider";252  slider.min = "8";253  slider.max = "128";254  slider.value = String(length);255  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));256  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));257  const lenNum = controls.appendChild(document.createElement("span"));258  lenNum.className = "pwgen-len-num pwgen-len-num--edit";259  lenNum.textContent = String(length);260  lenNum.addEventListener("click", () => {261    const li = document.createElement("input");262    li.type = "text"; li.inputMode = "numeric";263    li.className = "pwgen-len-input"; li.value = String(length);264    lenNum.replaceWith(li);265    requestAnimationFrame(() => li.select());266    function commitLenEdit() {267      const n = parseInt(li.value, 10);268      if (!isNaN(n)) {269        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));270        slider.value = String(length);271        regenerate();272      }273      lenNum.textContent = String(length);274      li.replaceWith(lenNum);275    }276    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });277    li.addEventListener("blur", commitLenEdit);278  });279280  const pills = root.appendChild(document.createElement("div"));281  pills.className = "pwgen-pills";282283  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {284    const b = document.createElement("button");285    b.type = "button";286    b.className = `pwgen-pill ${on ? "is-on" : ""}`;287    b.textContent = label;288    b.addEventListener("click", () => {289      const next = !b.classList.contains("is-on");290      b.classList.toggle("is-on", next);291      onToggle(next);292    });293    return b;294  }295  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));296  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));297  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));298  pills.appendChild(makePill("!@#", symbols, (next) => {299    // The site forbids symbols — UI lets the user override but still warn.300    symbols = next;301    regenerate();302  }));303304  // Policy hint — surfaces what Peach read off the site so the user knows the305  // generator is already tuned to it. Only shows when something interesting306  // was detected.307  const hintParts: string[] = [];308  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);309  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);310  if (policy.requiresSymbols) hintParts.push("requires symbols");311  if (policy.forbidsSymbols) hintParts.push("no symbols");312  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);313  if (hintParts.length > 0) {314    const hint = root.appendChild(document.createElement("div"));315    hint.className = "pwgen-policy-hint";316    const accent = document.createElement("span");317    accent.className = "pwgen-hint-accent";318    accent.textContent = "site rules · ";319    const text = document.createTextNode(hintParts.join(" · "));320    hint.appendChild(accent);321    hint.appendChild(text);322  }323324  function regenerate() {325    // Falls back gracefully when the user toggles every charset off — the326    // shared generator forces lowercase in that case rather than throwing.327    password = generatePassword({328      length,329      includeUppercase: upper,330      includeLowercase: lower,331      includeNumbers: numbers,332      includeSymbols: symbols,333      forbiddenChars,334    });335    output.value = password;336    opts.onChange?.(password);337  }338339  output.addEventListener("input", () => {340    password = output.value;341    length = password.length;342    slider.value = String(Math.max(8, Math.min(128, length)));343    lenNum.textContent = String(length);344    opts.onChange?.(password);345  });346347  slider.addEventListener("input", () => {348    length = parseInt(slider.value, 10);349    lenNum.textContent = String(length);350    regenerate();351  });352  regenBtn.addEventListener("click", regenerate);353354  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;355  async function copy(): Promise<void> {356    try {357      await navigator.clipboard.writeText(password);358      copyBtn.classList.add("is-copied");359      if (copyResetTimer) clearTimeout(copyResetTimer);360      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);361    } catch {362      // Clipboard API may be denied — silently no-op; user still has regen UI.363    }364  }365  copyBtn.addEventListener("click", () => { void copy(); });366367  if (opts.initialPassword) {368    password = opts.initialPassword;369    output.value = password;370    opts.onChange?.(password);371  } else {372    regenerate();373  }374375  return {376    root,377    getPassword: () => password,378    copy,379  };380}381382export function observeAnchorPosition(383  anchorEl: HTMLElement,384  onUpdate: () => void385): () => void {386  let rafId = 0;387  let burstUntil = 0;388389  const runUpdate = () => {390    rafId = 0;391    onUpdate();392    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);393  };394  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };395  const scheduleBurst = (ms = 220) => {396    burstUntil = Math.max(burstUntil, performance.now() + ms);397    scheduleUpdate();398  };399400  const resizeObserver = new ResizeObserver(() => scheduleBurst());401  resizeObserver.observe(anchorEl);402  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);403404  const mutationObserver = new MutationObserver(() => scheduleBurst());405  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });406  if (anchorEl.parentElement) {407    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });408  }409410  const onScroll = () => scheduleUpdate();411  window.addEventListener("scroll", onScroll, true);412  window.addEventListener("resize", onScroll);413  window.visualViewport?.addEventListener("resize", onScroll);414  window.visualViewport?.addEventListener("scroll", onScroll);415  anchorEl.addEventListener("focus", () => scheduleBurst());416  anchorEl.addEventListener("input", () => scheduleBurst());417418  scheduleBurst(260);419420  return () => {421    if (rafId) cancelAnimationFrame(rafId);422    resizeObserver.disconnect();423    mutationObserver.disconnect();424    window.removeEventListener("scroll", onScroll, true);425    window.removeEventListener("resize", onScroll);426    window.visualViewport?.removeEventListener("resize", onScroll);427    window.visualViewport?.removeEventListener("scroll", onScroll);428  };429}430431export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {432  const button = document.createElement("button");433  button.type = "button";434  button.setAttribute("aria-label", "Peach autofill");435  button.title = "Fill with Peach";436  button.innerHTML = peachIconSvg();437  // position: fixed is load-bearing — not absolute. Absolute positioning438  // inherits the nearest positioned ancestor's box, which on sites with439  // overflow:hidden or sticky parents clips or offsets the icon. Fixed440  // anchors to the viewport and escapes all parent layout.441  button.style.cssText = `442    position: fixed; z-index: 2147483646;443    width: 26px; height: 26px; cursor: pointer;444    pointer-events: auto; border: none; padding: 3px;445    display: inline-flex; align-items: center; justify-content: center;446    background: transparent; border-radius: 999px;447    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;448    opacity: 0;449  `;450  button.addEventListener("mouseenter", () => {451    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;452    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;453    button.style.transform = "scale(1.08)";454  });455  button.addEventListener("mouseleave", () => {456    button.style.background = "transparent";457    button.style.boxShadow = "none";458    button.style.transform = "none";459  });460  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });461  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });462463  document.body.appendChild(button);464465  function updatePosition() {466    const rect = field.getBoundingClientRect();467    if (rect.width === 0 || rect.height === 0) {468      button.style.opacity = "0"; button.style.pointerEvents = "none";469      return;470    }471    const sz = 26;472    const inset = Math.max(5, Math.min(10, rect.height * 0.22));473    const top = rect.top + rect.height / 2 - sz / 2;474    // Clamp left so the icon stays fully inside the field's right edge, never475    // spilling onto an adjacent sibling button.476    const minLeft = rect.left + 4;477    const left = Math.max(minLeft, rect.right - sz - inset);478    // Hide if the field is too narrow to fit the icon cleanly (< 40px)479    if (rect.width < 40) {480      button.style.opacity = "0"; button.style.pointerEvents = "none";481      return;482    }483    button.style.top = `${top}px`;484    button.style.left = `${left}px`;485    button.style.opacity = "1"; button.style.pointerEvents = "auto";486  }487  updatePosition();488  requestAnimationFrame(() => { button.style.opacity = "1"; });489  const stopObserving = observeAnchorPosition(field, updatePosition);490  return () => { stopObserving(); button.remove(); };491}492493// All theme-dependent values resolve through tokens scoped to494// .peach-inline-popup[data-theme="dark|light"]. Accent variables495// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)496// are identical in both themes — only surface tokens differ. See497// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the498// theme switch — only literal brand-peach in peachIconSvg may stay raw.499const SELECTOR_STYLES = `500  :host { all: initial; }501  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }502503  .peach-inline-popup[data-theme="dark"] {504    --peach-bg:           #1a1410;505    --peach-bg-card:      #221c16;506    --peach-text:         #f5f0ea;507    --peach-text-dim:     #8a7a6a;508    --peach-text-muted:   #4a3a2a;509    --peach-border:       rgba(255,255,255,0.07);510    --peach-input-bg:     rgba(255,255,255,0.05);511    --peach-input-border: rgba(255,255,255,0.08);512  }513  .peach-inline-popup[data-theme="light"] {514    --peach-bg:           #fdf8f4;515    --peach-bg-card:      #f5ede4;516    --peach-text:         #1c1310;517    --peach-text-dim:     #6b5a4a;518    --peach-text-muted:   #a89080;519    --peach-border:       rgba(0,0,0,0.08);520    --peach-input-bg:     rgba(0,0,0,0.04);521    --peach-input-border: rgba(0,0,0,0.10);522  }523524  .peach-inline-popup {525    background: var(--peach-bg);526    border: 1px solid var(--peach-border-accent, var(--peach-border));527    border-radius: 14px;528    overflow: hidden;529    box-shadow:530      0 8px 40px var(--peach-glow, transparent),531      0 2px 12px rgba(0,0,0,0.5);532    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;533    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;534    transition: height 220ms cubic-bezier(0.16,1,0.3,1);535  }536  /* Light theme: shadow against a light page is too strong otherwise — drop both537     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */538  .peach-inline-popup[data-theme="light"] {539    box-shadow:540      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),541      0 2px 12px rgba(0,0,0,0.12);542  }543  .peach-inline-popup.is-exiting {544    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;545    pointer-events: none;546  }547548  @keyframes peach-enter {549    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }550    65%  { opacity: 1; filter: blur(0); }551    100% { opacity: 1; transform: translateY(0) scale(1); }552  }553  @keyframes peach-exit {554    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }555    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }556  }557  @keyframes peach-slide-in {558    from { opacity: 0; transform: translateX(12px); }559    to   { opacity: 1; transform: translateX(0); }560  }561  @keyframes peach-slide-back {562    from { opacity: 0; transform: translateX(-12px); }563    to   { opacity: 1; transform: translateX(0); }564  }565  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }566  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }567568  /* Domain header */569  .domain-header {570    padding: 9px 13px 7px;571    border-bottom: 1px solid var(--peach-border);572    display: flex; align-items: center; justify-content: space-between;573    gap: 8px;574  }575  .domain-header-text {576    display: flex; flex-direction: column; gap: 2px;577    min-width: 0; flex: 1;578  }579  .domain-eyebrow {580    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;581    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;582  }583  .domain-name {584    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);585    font-family: "IBM Plex Mono", monospace;586    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;587  }588  .domain-add-btn {589    flex-shrink: 0;590    width: 22px; height: 22px;591    display: inline-flex; align-items: center; justify-content: center;592    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);593    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);594    border-radius: 6px;595    color: var(--peach-accent);596    cursor: pointer; padding: 0;597    transition: background 120ms, border-color 120ms, transform 80ms;598    font-family: "IBM Plex Mono", monospace;599    font-size: 14px; line-height: 1;600  }601  .domain-add-btn:hover {602    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);603    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);604    transform: scale(1.06);605  }606  .domain-add-btn:active { transform: scale(0.96); }607608  /* Search */609  .search-wrap {610    padding: 9px 12px 7px;611    border-bottom: 1px solid var(--peach-border);612  }613  .search {614    width: 100%; background: var(--peach-input-bg);615    border: 1px solid var(--peach-input-border);616    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;617    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;618    transition: border-color 120ms, box-shadow 120ms;619  }620  .search:focus {621    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);622    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);623  }624  .search::placeholder { color: var(--peach-text-muted); }625626  /* Results */627  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }628  .results::-webkit-scrollbar { display: none; }629630  /* Entry rows */631  .entry {632    display: flex; align-items: center; padding: 8px 12px;633    cursor: pointer; border-bottom: 1px solid var(--peach-border);634    transition: background 70ms; position: relative; outline: none;635  }636  .entry:last-child { border-bottom: none; }637  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }638  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }639  .entry.focused::before {640    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;641    width: 2px; border-radius: 2px;642    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);643  }644645  .entry-icon {646    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;647    background: var(--peach-input-bg); border: 1px solid var(--peach-border);648    display: flex; align-items: center; justify-content: center;649    overflow: hidden; margin-right: 10px;650  }651  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }652  .entry-icon.is-new {653    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);654    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);655    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);656  }657658  .entry-info { flex: 1; min-width: 0; }659  .entry-title {660    font-size: 12.5px; color: var(--peach-text);661    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;662    line-height: 1.3;663  }664  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }665  .entry-sub {666    font-size: 10px; color: var(--peach-text-dim);667    font-family: "IBM Plex Mono", monospace;668    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;669    margin-top: 1px;670  }671672  .totp-badge {673    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;674    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);675    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);676    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;677  }678  .passkey-badge {679    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;680    border-radius: 4px;681    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);682    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);683    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);684    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;685  }686687  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }688689  .empty-hint {690    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);691    font-family: "IBM Plex Mono", monospace;692  }693694  /* Create form */695  .create-form-wrap {696    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;697  }698  .create-head {699    display: flex; align-items: center; gap: 8px;700    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);701  }702  .back-btn {703    background: transparent; border: none; cursor: pointer;704    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;705    display: flex; align-items: center; line-height: 0;706    transition: color 100ms, background 100ms;707  }708  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }709  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }710  /* minmax(0, 1fr) caps the grid track at the popup width — without it,711     long monospace content (e.g. a 60-char generated password) would712     auto-size the track wider than the popup and overflow the right edge. */713  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }714  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }715  .f-label {716    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;717    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;718  }719  .f-input {720    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);721    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;722    font-size: 11px; font-family: "IBM Plex Mono", monospace;723    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;724  }725  .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); }726  .f-input::placeholder { color: var(--peach-text-muted); }727  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }728  .f-row { display: flex; gap: 6px; }729  .f-row .f-input { flex: 1; min-width: 0; }730  .gen-btn {731    padding: 0 10px; border-radius: 7px; border: none;732    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);733    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);734    font-size: 10px; font-family: "IBM Plex Mono", monospace;735    cursor: pointer; white-space: nowrap; flex-shrink: 0;736    display: flex; align-items: center; gap: 4px;737    transition: background 100ms;738  }739  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }740  .gen-toggle-link {741    background: none; border: none; padding: 2px 0;742    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);743    font-size: 10px; font-family: "IBM Plex Mono", monospace;744    cursor: pointer; text-align: left; transition: color 100ms;745  }746  .gen-toggle-link:hover { color: var(--peach-accent); }747  .save-btn {748    width: 100%; padding: 8px; border-radius: 8px; border: none;749    background: var(--peach-accent); color: #fff; font-size: 12px;750    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;751    transition: background 120ms, box-shadow 120ms, transform 80ms;752    letter-spacing: 0.01em;753  }754  .save-btn:hover {755    background: color-mix(in srgb, var(--peach-accent) 82%, #000);756    box-shadow: 0 4px 20px var(--peach-glow, transparent);757  }758  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }759  .url-hint {760    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);761    font-family: "IBM Plex Mono", monospace; font-style: italic;762  }763764  /* Success */765  .success-wrap {766    display: flex; flex-direction: column; align-items: center;767    padding: 24px 16px 20px; gap: 8px;768    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;769  }770  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }771  .success-ring {772    width: 40px; height: 40px; border-radius: 50%;773    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);774    display: flex; align-items: center; justify-content: center;775  }776  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }777  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }778779  /* Silver platter (State 1 — single match) */780  .silver-platter {781    padding: 14px 14px 12px;782    display: flex; flex-direction: column; gap: 6px;783  }784  .sp-title {785    font-size: 14px; font-weight: 500; color: var(--peach-text);786    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;787    line-height: 1.25;788  }789  .sp-identity-row {790    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;791  }792  .sp-identity-label {793    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;794    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;795  }796  .sp-username {797    font-size: 12px; color: var(--peach-text-dim);798    font-family: "IBM Plex Mono", monospace;799    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;800    margin-bottom: 0;801  }802  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }803  .sp-fill-btn {804    width: 100%; padding: 11px; border-radius: 9px; border: none;805    background: var(--peach-accent); color: #fff;806    font-size: 13px; font-weight: 500; cursor: pointer;807    font-family: Inter, sans-serif; letter-spacing: 0.01em;808    display: flex; align-items: center; justify-content: center; min-height: 38px;809    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;810  }811  .sp-fill-btn:hover {812    filter: brightness(1.1);813    box-shadow: 0 4px 20px var(--peach-glow, transparent);814    transform: translateY(-1px);815  }816  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }817  .sp-fill-btn.filled {818    background: #16a34a; transform: none; filter: none;819    box-shadow: 0 4px 16px rgba(22,163,74,0.35);820    cursor: default;821  }822  .sp-fill-btn:disabled { cursor: default; }823  .sp-actions-group {824    margin-top: 6px;825    display: flex; flex-direction: column; gap: 4px;826  }827  .sp-actions-label {828    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;829    color: var(--peach-text-muted);830    font-family: "IBM Plex Mono", monospace;831    text-align: center;832  }833  .sp-actions {834    display: flex; gap: 4px; justify-content: space-between; align-items: center;835  }836  .sp-action-btn {837    flex: 1; height: 28px; border: none; border-radius: 6px;838    background: transparent; color: var(--peach-text-dim);839    font-size: 12px; cursor: pointer;840    transition: background 120ms ease, color 120ms ease;841    font-family: Inter, sans-serif; letter-spacing: 0.04em;842    display: inline-flex; align-items: center; justify-content: center; gap: 4px;843    white-space: nowrap; overflow: hidden;844  }845  .sp-action-btn:hover:not(:disabled) {846    background: color-mix(in srgb, var(--peach-text) 5%, transparent);847    color: var(--peach-text);848  }849  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }850  .sp-action-btn.flashed {851    color: var(--peach-accent);852    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);853  }854855  /* TOTP tray — shown below the silver-platter secondary actions */856  .sp-tray {857    margin-top: 8px;858    padding: 10px 12px;859    border-radius: 9px;860    background: var(--peach-input-bg);861    border: 1px solid var(--peach-input-border);862    display: flex; align-items: center; gap: 12px;863    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;864  }865  .sp-tray-label {866    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;867    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;868    flex-shrink: 0;869  }870  .sp-totp-code {871    font-size: 18px; font-weight: 500;872    color: var(--peach-text);873    font-family: "IBM Plex Mono", monospace;874    letter-spacing: 0.12em;875    flex: 1;876    text-align: center;877  }878  .sp-totp-ring {879    width: 22px; height: 22px; flex-shrink: 0;880  }881  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }882  .sp-totp-ring .ring-fill {883    stroke: var(--peach-accent);884    transition: stroke-dashoffset 1s linear;885    transform: rotate(-90deg);886    transform-origin: center;887  }888  .sp-totp-copy {889    background: transparent; border: none; cursor: pointer;890    padding: 4px 8px; border-radius: 5px;891    color: var(--peach-text-dim); font-size: 11px;892    font-family: Inter, sans-serif;893    transition: background 120ms, color 120ms;894  }895  .sp-totp-copy:hover {896    background: color-mix(in srgb, var(--peach-text) 5%, transparent);897    color: var(--peach-text);898  }899900  /* Card silver platter (State 7) — reuses .sp-* primary action classes */901  .card-platter {902    padding: 12px 14px 10px;903    display: flex; flex-direction: column; gap: 4px;904  }905  .cp-network {906    font-size: 10px; font-weight: 600;907    color: var(--peach-accent);908    letter-spacing: 0.08em; text-transform: uppercase;909    font-family: Inter, sans-serif;910  }911  .cp-nickname {912    font-size: 14px; font-weight: 500; color: var(--peach-text);913    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;914    line-height: 1.2;915  }916  .cp-last4 {917    font-size: 12px; color: var(--peach-text-dim);918    font-family: "IBM Plex Mono", monospace;919    letter-spacing: 0.04em;920    margin-top: 2px;921  }922  .cp-meta {923    font-size: 11px; color: var(--peach-text-dim);924    font-family: "IBM Plex Mono", monospace;925    margin-top: 2px;926    display: flex; gap: 10px; align-items: center;927  }928  .cp-meta-sep { opacity: 0.5; }929  .cp-fill-wrap { margin-top: 10px; }930931  /* Locked state */932  .locked-wrap {933    display: flex; flex-direction: column; align-items: stretch;934    padding: 14px 13px 13px; gap: 9px;935  }936  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }937  .locked-icon {938    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;939    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);940    display: flex; align-items: center; justify-content: center;941  }942  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }943  .locked-input {944    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);945    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;946    font-size: 11px; font-family: "IBM Plex Mono", monospace;947    outline: none; transition: border-color 120ms, box-shadow 120ms;948  }949  .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); }950  .locked-input::placeholder { color: var(--peach-text-muted); }951  .locked-btn {952    width: 100%; padding: 8px; border-radius: 8px; border: none;953    background: var(--peach-accent); color: #fff; font-size: 12px;954    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;955    transition: background 120ms;956    letter-spacing: 0.01em;957    box-shadow: 0 2px 16px var(--peach-glow, transparent);958    animation: peach-pulse-glow 2.4s ease-in-out infinite;959  }960  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }961  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }962  .locked-error {963    font-size: 10px; color: rgba(220,80,60,0.85);964    font-family: "IBM Plex Mono", monospace;965  }966967  @keyframes peach-pulse-glow {968    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }969    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),970                            0 0 48px var(--peach-glow, transparent); }971  }972973  /* ── State 10: identity helper ─────────────────────────────── */974  .identity-list {975    max-height: 192px; overflow-y: auto; padding: 4px 0;976    scrollbar-width: none;977  }978  .identity-list::-webkit-scrollbar { display: none; }979  .peach-identity-row {980    display: flex; align-items: center; gap: 10px;981    padding: 9px 12px; cursor: pointer; border-radius: 8px;982    transition: background 100ms ease;983  }984  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }985  .peach-identity-value {986    font-family: "IBM Plex Mono", monospace; font-size: 13px;987    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;988  }989  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }990  .identity-alt-row {991    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;992    border-radius: 8px; transition: background 100ms ease;993    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;994  }995  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }996  .identity-escape-row {997    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;998    border-radius: 8px; transition: background 100ms ease; outline: none;999    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1000    margin-top: 2px;1001  }1002  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1003  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1004  .identity-alt-input-wrap.open { display: flex; }1005  .identity-alt-input {1006    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1007    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1008    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1009    outline: none; transition: border-color 120ms;1010  }1011  .identity-alt-input:focus {1012    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1013    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1014  }1015  .identity-alt-confirm {1016    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1017    background: var(--peach-accent); color: #fff; font-size: 12px;1018    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1019  }1020  /* ── Generator view (after identity picked) ────────────────── */1021  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1022  .gen-confirmed {1023    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1024    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1025    border-radius: 8px;1026  }1027  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1028  .gen-confirmed-val {1029    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1030    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1031  }1032  .gen-label {1033    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1034    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1035  }1036  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1037  .gen-pw-val {1038    flex: 1; padding: 8px 10px; border-radius: 7px;1039    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1040    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1041    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1042  }1043  .gen-regen-btn {1044    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1045    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1046    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1047    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1048  }1049  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1050  .gen-fill-btn {1051    padding: 10px; border-radius: 8px; border: none;1052    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1053    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1054    transition: filter 120ms ease, transform 80ms ease;1055  }1056  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1057  .gen-fill-btn:active { transform: translateY(0); }10581059  /* ── Smart password generator (parity with main UI compact mode) ─── */1060  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1061  .pwgen-display-row {1062    display: flex; align-items: center; gap: 6px;1063    padding: 8px 10px; border-radius: 7px;1064    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1065  }1066  .pwgen-output {1067    flex: 1; min-width: 0; width: 0;1068    font-family: "IBM Plex Mono", monospace; font-size: 12px;1069    color: var(--peach-text);1070    background: transparent; border: none; outline: none; padding: 0;1071  }1072  .pwgen-icon-btn {1073    flex-shrink: 0;1074    width: 26px; height: 26px;1075    display: inline-flex; align-items: center; justify-content: center;1076    background: transparent; border: 1px solid var(--peach-input-border);1077    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1078    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1079  }1080  .pwgen-icon-btn:hover {1081    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1082    color: var(--peach-accent);1083    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1084  }1085  .pwgen-icon-btn.is-copied {1086    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1087    color: var(--peach-accent);1088    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1089  }1090  .pwgen-controls-row {1091    display: flex; align-items: center; gap: 8px;1092    flex-wrap: wrap;1093  }1094  .pwgen-slider {1095    flex: 1; min-width: 110px;1096    accent-color: var(--peach-accent);1097    cursor: pointer; height: 2px; background: transparent;1098  }1099  .pwgen-len-num {1100    font-family: "IBM Plex Mono", monospace; font-size: 11px;1101    color: var(--peach-accent); min-width: 22px; text-align: right;1102  }1103  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1104  .pwgen-len-input {1105    font-family: "IBM Plex Mono", monospace; font-size: 11px;1106    color: var(--peach-accent); width: 28px; text-align: right;1107    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1108    outline: none; padding: 0; min-width: 22px;1109  }1110  @keyframes identity-suggest-in {1111    from { opacity: 0; transform: translateY(-4px); }1112    to   { opacity: 1; transform: none; }1113  }1114  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1115    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1116  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1117  .identity-collapse-btn {1118    margin-left: auto; background: transparent; border: none; cursor: pointer;1119    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1120    line-height: 0; border-radius: 3px;1121    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1122  }1123  .identity-collapse-btn:hover { color: var(--peach-text); }1124  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1125  .identity-rows { display: grid; grid-template-rows: 1fr;1126    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1127  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1128  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1129    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1130    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1131    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1132  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1133  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1134  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1135  .identity-filter-pill {1136    padding: 2px 7px; border-radius: 999px;1137    border: 1px solid var(--peach-input-border);1138    background: transparent; color: var(--peach-text-muted);1139    font-family: "IBM Plex Mono", monospace; font-size: 9px;1140    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1141  }1142  .identity-filter-pill.is-on {1143    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1144    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1145    color: var(--peach-accent);1146  }1147  .identity-suggest-row {1148    display: flex; align-items: center; gap: 5px;1149    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1150    background: transparent; cursor: pointer; text-align: left;1151    transition: background 80ms;1152  }1153  .identity-suggest-row:hover,1154  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1155  .identity-suggest-val {1156    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1157    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1158  }1159  .identity-suggest-type {1160    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1161    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1162  }1163  .identity-suggest-type--email {1164    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1165    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1166  }1167  .identity-suggest-type--username {1168    color: var(--peach-text-muted);1169    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1170  }1171  .identity-suggest-meta {1172    font-family: "IBM Plex Mono", monospace; font-size: 9px;1173    color: var(--peach-text-muted); flex-shrink: 0;1174  }1175  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1176  .pwgen-pill {1177    padding: 3px 8px; border-radius: 999px;1178    border: 1px solid var(--peach-input-border);1179    background: transparent; color: var(--peach-text-muted);1180    font-family: "IBM Plex Mono", monospace; font-size: 9px;1181    letter-spacing: 0.06em; cursor: pointer;1182    transition: all 130ms ease;1183  }1184  .pwgen-pill.is-on {1185    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1186    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1187    color: var(--peach-accent);1188  }1189  .pwgen-pill:not(.is-on):hover {1190    color: var(--peach-text-dim);1191    border-color: var(--peach-text-muted);1192  }1193  .pwgen-policy-hint {1194    font-size: 10px; color: var(--peach-text-muted);1195    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1196    line-height: 1.3;1197  }1198  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11991200  /* ── Save offer (after password filled) ───────────────────── */1201  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1202  .save-offer-title {1203    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1204  }1205  .save-offer-row {1206    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1207    border-radius: 7px; background: var(--peach-input-bg);1208    border: 1px solid var(--peach-input-border);1209  }1210  .save-offer-lbl {1211    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1212    font-family: "IBM Plex Mono", monospace;1213  }1214  .save-offer-val {1215    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1216    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1217  }1218  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1219  .save-offer-save {1220    flex: 1; padding: 9px; border-radius: 8px; border: none;1221    background: var(--peach-accent); color: #fff; font-size: 13px;1222    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1223  }1224  .save-offer-save:hover { filter: brightness(1.08); }1225  .save-offer-skip {1226    flex: 1; padding: 9px; border-radius: 8px; border: none;1227    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1228    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1229    font-family: Inter, sans-serif; transition: background 100ms ease;1230  }1231  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1232`;12331234export function showAutofillSelector(1235  anchorEl: HTMLInputElement,1236  entries: SelectorEntry[],1237  onSelect: (id: string) => void,1238  options: SelectorOptions = {}1239): () => void {1240  const host = document.createElement("div");1241  host.style.cssText = "position: absolute; z-index: 2147483647;";1242  host.style.setProperty("--peach-accent", accentHex);1243  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1244  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1245  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1246  const shadow = host.attachShadow({ mode: "closed" });12471248  const style = shadow.appendChild(document.createElement("style"));1249  style.textContent = SELECTOR_STYLES;12501251  const rect = anchorEl.getBoundingClientRect();1252  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1253  host.style.left = `${rect.left + window.scrollX}px`;1254  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1255  // wide single-input fields (e.g. centered email input on signup pages).1256  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1257  // expand the host after the initial measurement.1258  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1259  host.style.width = `${popupWidth}px`;12601261  const container = shadow.appendChild(document.createElement("div"));1262  container.className = "peach-inline-popup";1263  container.setAttribute("data-theme", popupTheme);12641265  const searchableEntries = options.searchableEntries ?? [];1266  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12671268  let query = "";1269  let focusedIndex = -1;1270  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1271  let searchInput: HTMLInputElement | null = null;1272  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1273  // setInterval. Add to this list — don't fan out the dismiss function.1274  const cleanupHooks: Array<() => void> = [];12751276  // Smooth height transitions whenever content changes height.1277  // ResizeObserver fires on natural height changes; we freeze the old height,1278  // then animate to the new one so the surface never jumps.1279  {1280    let prevH = 0;1281    let blocked = false;1282    const heightRo = new ResizeObserver(([entry]) => {1283      if (blocked) return;1284      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1285      if (prevH > 0 && Math.abs(h - prevH) > 1) {1286        blocked = true;1287        container.style.height = `${prevH}px`;1288        requestAnimationFrame(() => requestAnimationFrame(() => {1289          container.style.height = `${h}px`;1290          prevH = h;1291          const onEnd = (e: TransitionEvent) => {1292            if (e.propertyName !== "height") return;1293            container.style.height = "";1294            blocked = false;1295            container.removeEventListener("transitionend", onEnd);1296          };1297          container.addEventListener("transitionend", onEnd);1298        }));1299      } else {1300        prevH = h;1301      }1302    });1303    heightRo.observe(container);1304    cleanupHooks.push(() => heightRo.disconnect());1305  }13061307  // Pre-capture the anchor field value for username prefill1308  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1309  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1310  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13111312  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1313    const seen = new Set<string>();1314    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1315  }13161317  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1318    const q = value.trim().toLowerCase();1319    const deduped = uniqueEntries(source);1320    if (!q) return deduped.slice(0, 8);1321    return deduped.filter(e =>1322      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1323    ).slice(0, 12);1324  }13251326  function activeEntries(): SelectorEntry[] {1327    // When user is typing a search, filter across all known entries (domain matches + vault)1328    if (query.trim()) {1329      const merged = uniqueEntries([...entries, ...searchableEntries]);1330      return filterEntries(merged, query);1331    }1332    // Default: show domain matches; fall back to vault search when no matches1333    if (entries.length > 0) return entries;1334    return filterEntries(searchableEntries, "").slice(0, 8);1335  }13361337  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1338    const icon = document.createElement("div");1339    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1340    if (isNew) {1341      icon.innerHTML = plusSvgStr();1342    } else {1343      // Use the generic key glyph for all entries in the page-injected selector.1344      // Avoids disclosing vault domains to any third party and avoids needing1345      // to expose the browser favicon API to page context via web_accessible_resources.1346      void url;1347      icon.innerHTML = keySvgStr();1348    }1349    return icon;1350  }13511352  function renderIdentityHelper() {1353    container.innerHTML = "";1354    const identities = options.savedIdentities ?? [];13551356    // Header: "NEW ACCOUNT" + domain name1357    const hdr = container.appendChild(document.createElement("div"));1358    hdr.className = "domain-header";1359    const eyebrow = hdr.appendChild(document.createElement("div"));1360    eyebrow.className = "domain-eyebrow";1361    eyebrow.textContent = "NEW ACCOUNT";1362    const domName = hdr.appendChild(document.createElement("div"));1363    domName.className = "domain-name";1364    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13651366    // Identity rows1367    const list = container.appendChild(document.createElement("div"));1368    list.className = "identity-list";1369    for (const id of identities) {1370      const row = list.appendChild(document.createElement("div"));1371      row.className = "peach-identity-row";1372      row.setAttribute("tabindex", "-1");1373      const val = row.appendChild(document.createElement("div"));1374      val.className = "peach-identity-value";1375      val.textContent = id.value;1376      const meta = row.appendChild(document.createElement("div"));1377      meta.className = "peach-identity-meta";1378      meta.textContent = `used ${id.useCount}×`;1379      row.addEventListener("click", () => {1380        options.onFillFields?.(id.value, "");1381        renderGenerator(id.value);1382      });1383    }13841385    // Divider before "Use a different email…"1386    if (identities.length > 0) {1387      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1388    }13891390    // "Use a different email…" expandable row1391    const altRow = container.appendChild(document.createElement("div"));1392    altRow.className = "identity-alt-row";1393    altRow.textContent = "+ Use a different email…";13941395    const altInputWrap = container.appendChild(document.createElement("div"));1396    altInputWrap.className = "identity-alt-input-wrap";1397    const altInput = altInputWrap.appendChild(document.createElement("input"));1398    altInput.className = "identity-alt-input";1399    altInput.type = "email";1400    altInput.placeholder = "[email protected]";1401    altInput.setAttribute("autocomplete", "off");1402    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1403    altConfirm.className = "identity-alt-confirm";1404    altConfirm.type = "button";1405    altConfirm.textContent = "✓";14061407    function fillCustomEmail() {1408      const v = altInput.value.trim();1409      if (!v) return;1410      options.onFillFields?.(v, "");1411      renderGenerator(v);1412    }14131414    altRow.addEventListener("click", () => {1415      altRow.style.display = "none";1416      altInputWrap.classList.add("open");1417      altInput.focus();1418    });1419    altConfirm.addEventListener("click", fillCustomEmail);1420    altInput.addEventListener("keydown", (e) => {1421      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1422    });14231424    // Escape hatch: user already has a vault entry for this site but it1425    // wasn't detected (different domain, old entry, etc.). Tapping this1426    // switches to the full searchable list so they can find and fill it;1427    // selecting an entry there will trigger the remember-site toast if1428    // the domain isn't already associated.1429    if ((options.searchableEntries?.length ?? 0) > 0) {1430      const escapeRow = container.appendChild(document.createElement("div"));1431      escapeRow.className = "identity-escape-row";1432      escapeRow.textContent = "I already have an account →";1433      escapeRow.setAttribute("tabindex", "0");1434      escapeRow.addEventListener("click", () => renderList());1435      escapeRow.addEventListener("keydown", (e) => {1436        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1437      });1438    }1439  }14401441  function renderGenerator(filledEmail: string) {1442    container.innerHTML = "";1443    const sitePolicy = detectPasswordPolicy();14441445    const wrap = container.appendChild(document.createElement("div"));1446    wrap.className = "gen-view";14471448    // Header: domain + NEW ACCOUNT1449    const hdrRow = wrap.appendChild(document.createElement("div"));1450    hdrRow.className = "domain-header";1451    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1452    eyebrow2.className = "domain-eyebrow";1453    eyebrow2.textContent = "NEW ACCOUNT";1454    const domName2 = hdrRow.appendChild(document.createElement("div"));1455    domName2.className = "domain-name";1456    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14571458    // Confirmed email row1459    const conf = wrap.appendChild(document.createElement("div"));1460    conf.className = "gen-confirmed";1461    const confCheck = conf.appendChild(document.createElement("span"));1462    confCheck.className = "gen-confirmed-check";1463    confCheck.textContent = "✓";1464    const confVal = conf.appendChild(document.createElement("div"));1465    confVal.className = "gen-confirmed-val";1466    confVal.textContent = filledEmail;14671468    const lbl = wrap.appendChild(document.createElement("div"));1469    lbl.className = "gen-label";1470    lbl.textContent = "Generate a password";14711472    let currentPw = "";1473    const smartGen = createSmartGenerator({1474      policy: sitePolicy,1475      onChange: (pw) => { currentPw = pw; },1476    });1477    wrap.appendChild(smartGen.root);14781479    const fillBtn = wrap.appendChild(document.createElement("button"));1480    fillBtn.className = "gen-fill-btn";1481    fillBtn.type = "button";1482    fillBtn.textContent = "Copy & fill";1483    fillBtn.addEventListener("click", () => {1484      if (!currentPw) return;1485      options.onFillFields?.("", currentPw);1486      renderSaveOffer(filledEmail, currentPw);1487    });1488  }14891490  function renderSaveOffer(filledEmail: string, filledPassword: string) {1491    container.innerHTML = "";1492    const domain = options.domain ?? location.hostname.replace(/^www\./, "");14931494    const wrap = container.appendChild(document.createElement("div"));1495    wrap.className = "save-offer";14961497    const title = wrap.appendChild(document.createElement("div"));1498    title.className = "save-offer-title";1499    title.textContent = "Save this login to Peach?";15001501    function detailRow(label: string, value: string) {1502      const row = wrap.appendChild(document.createElement("div"));1503      row.className = "save-offer-row";1504      const lbl = row.appendChild(document.createElement("div"));1505      lbl.className = "save-offer-lbl";1506      lbl.textContent = label;1507      const val = row.appendChild(document.createElement("div"));1508      val.className = "save-offer-val";1509      val.textContent = value;1510    }15111512    detailRow("site", domain);1513    detailRow("email", filledEmail);1514    detailRow("password", "••••••••••••••••");15151516    const btns = wrap.appendChild(document.createElement("div"));1517    btns.className = "save-offer-btns";15181519    const saveBtn = btns.appendChild(document.createElement("button"));1520    saveBtn.className = "save-offer-save";1521    saveBtn.type = "button";1522    saveBtn.textContent = "Save";1523    saveBtn.addEventListener("click", async () => {1524      saveBtn.disabled = true;1525      saveBtn.textContent = "Saving…";1526      try {1527        const res = await chrome.runtime.sendMessage({1528          type: "ADD_ENTRY",1529          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1530        });1531        if ((res as { ok?: boolean }).ok) {1532          showSuccess(sTitle);1533        } else {1534          saveBtn.disabled = false;1535          saveBtn.textContent = "Save";1536        }1537      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1538    });15391540    const skipBtn = btns.appendChild(document.createElement("button"));1541    skipBtn.className = "save-offer-skip";1542    skipBtn.type = "button";1543    skipBtn.textContent = "Not now";1544    skipBtn.addEventListener("click", () => { dismiss(true); });1545  }15461547  function renderList() {1548    container.innerHTML = "";1549    focusedIndex = -1;1550    searchInput = null;15511552    const current = activeEntries();15531554    // Domain header (always show) — eyebrow + domain on the left,1555    // a "+" shortcut to the create form on the right so the user is never1556    // trapped in the search list when they want to make a new entry.1557    const domHdr = document.createElement("div");1558    domHdr.className = "domain-header";1559    const headText = document.createElement("div");1560    headText.className = "domain-header-text";1561    const eyebrow = document.createElement("div");1562    eyebrow.className = "domain-eyebrow";1563    eyebrow.textContent = options.isSignup1564      ? "Sign up as"1565      : entries.length > 0 ? "Saved for this site" : "No saved login";1566    const domName = document.createElement("div");1567    domName.className = "domain-name";1568    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1569    headText.append(eyebrow, domName);1570    domHdr.appendChild(headText);15711572    if (!options.isSignup) {1573      const addBtn = document.createElement("button");1574      addBtn.className = "domain-add-btn";1575      addBtn.type = "button";1576      addBtn.setAttribute("aria-label", "Create new entry");1577      addBtn.title = "Create new entry";1578      addBtn.textContent = "+";1579      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1580      domHdr.appendChild(addBtn);1581    }15821583    container.appendChild(domHdr);15841585    // Search — always show so user can find entries beyond the domain matches1586    const sw = document.createElement("div"); sw.className = "search-wrap";1587    searchInput = document.createElement("input");1588    searchInput.className = "search";1589    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1590    searchInput.value = query;1591    searchInput.addEventListener("input", () => {1592      query = searchInput?.value ?? "";1593      renderList();1594      searchInput?.focus();1595      searchInput?.setSelectionRange(query.length, query.length);1596    });1597    sw.appendChild(searchInput);1598    container.appendChild(sw);15991600    // Results1601    const results = document.createElement("div");1602    results.className = "results";1603    container.appendChild(results);16041605    if (current.length === 0 && entries.length > 0) {1606      // Show a hint but don't render empty entries1607    }16081609    for (let i = 0; i < current.length; i++) {1610      const e = current[i]!;1611      const entryEl = document.createElement("div");1612      entryEl.className = "entry";1613      entryEl.dataset.id = e.id;1614      entryEl.dataset.index = String(i);1615      entryEl.setAttribute("tabindex", "-1");16161617      entryEl.appendChild(makeEntryIcon(e.url));16181619      const info = document.createElement("div"); info.className = "entry-info";1620      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1621      const subEl = document.createElement("div"); subEl.className = "entry-sub";1622      const domain = e.url ? getDomainFromUrl(e.url) : "";1623      subEl.textContent = domain || e.username || "";1624      info.append(titleEl, subEl);1625      entryEl.appendChild(info);16261627      if (e.hasTotp) {1628        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1629        entryEl.appendChild(badge);1630      }1631      if (e.hasPasskey) {1632        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1633        entryEl.appendChild(badge);1634      }16351636      entryEl.addEventListener("click", () => {1637        if (options.isSignup && options.onFillFields) {1638          // Signup mode: clicking a saved identity fills the username field1639          options.onFillFields(e.username ?? "", "");1640          dismiss();1641        } else {1642          onSelect(e.id);1643          dismiss();1644        }1645      });1646      results.appendChild(entryEl);1647    }16481649    // Divider before "New entry"1650    if (current.length > 0) {1651      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1652    }16531654    // "New entry" row — always present1655    const newEl = document.createElement("div");1656    newEl.className = "entry";1657    newEl.setAttribute("tabindex", "-1");1658    newEl.appendChild(makeEntryIcon(undefined, true));16591660    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1661    const newTitle = document.createElement("div");1662    newTitle.className = "entry-title is-new";1663    newTitle.textContent = `New entry for ${sTitle}`;1664    const newSub = document.createElement("div");1665    newSub.className = "entry-sub";1666    newSub.textContent = sOrigin;1667    newInfo.append(newTitle, newSub);1668    newEl.appendChild(newInfo);1669    newEl.addEventListener("click", showCreateForm);1670    results.appendChild(newEl);16711672    // Focus search if present1673    if (searchInput) {1674      requestAnimationFrame(() => searchInput?.focus());1675    }1676  }16771678  function setFocused(idx: number) {1679    const all = container.querySelectorAll<HTMLElement>(".entry");1680    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1681    focusedIndex = idx;1682    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1683  }16841685  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1686    const typed = identities.filter(s => s.type === fieldType);1687    if (!typed.length) return;1688    let collapsed = false;1689    let suppressNextFocus = false;16901691    const list = g.appendChild(document.createElement("div"));1692    list.className = "identity-suggest-list";1693    list.style.display = "none";16941695    // Collapse toggle — sits alone now that filter pills are gone1696    const collapseRow = list.appendChild(document.createElement("div"));1697    collapseRow.className = "identity-filter-row";1698    collapseRow.style.justifyContent = "flex-end";1699    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1700    collapseBtn.type = "button";1701    collapseBtn.className = "identity-collapse-btn";1702    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>`;1703    collapseBtn.addEventListener("mousedown", (e) => {1704      e.preventDefault();1705      collapsed = !collapsed;1706      collapseBtn.classList.toggle("is-collapsed", collapsed);1707      rowsWrapper.classList.toggle("is-collapsed", collapsed);1708    });17091710    const rowsWrapper = list.appendChild(document.createElement("div"));1711    rowsWrapper.className = "identity-rows";1712    const rows = rowsWrapper.appendChild(document.createElement("div"));1713    rows.className = "identity-rows-inner";17141715    function pick(value: string) {1716      inp.value = value;1717      list.style.display = "none";1718      suppressNextFocus = true;1719      inp.focus();1720    }17211722    function render() {1723      const q = inp.value.toLowerCase();1724      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1725      rows.innerHTML = "";1726      if (!filtered.length) { list.style.display = "none"; return; }1727      for (const s of filtered) {1728        const row = rows.appendChild(document.createElement("button"));1729        row.type = "button"; row.className = "identity-suggest-row";1730        const val = row.appendChild(document.createElement("span"));1731        val.className = "identity-suggest-val"; val.textContent = s.value;1732        const meta = row.appendChild(document.createElement("span"));1733        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1734        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1735        row.addEventListener("keydown", (e) => {1736          if (e.key === "ArrowDown") {1737            e.preventDefault();1738            (row.nextElementSibling as HTMLElement | null)?.focus();1739          } else if (e.key === "ArrowUp") {1740            e.preventDefault();1741            const prev = row.previousElementSibling as HTMLElement | null;1742            if (prev) prev.focus();1743            else inp.focus();1744          } else if (e.key === "Enter" || e.key === " ") {1745            e.preventDefault();1746            pick(s.value);1747          } else if (e.key === "Escape") {1748            e.preventDefault();1749            list.style.display = "none";1750            suppressNextFocus = true;1751            inp.focus();1752          }1753        });1754        row.addEventListener("blur", (e) => {1755          const rt = (e as FocusEvent).relatedTarget as Node | null;1756          if (rt && (rt === inp || list.contains(rt))) return;1757          setTimeout(() => { list.style.display = "none"; }, 150);1758        });1759      }1760      list.style.display = "";1761    }17621763    inp.addEventListener("focus", () => {1764      if (suppressNextFocus) { suppressNextFocus = false; return; }1765      render();1766    });1767    inp.addEventListener("input", render);1768    inp.addEventListener("keydown", (e) => {1769      if (list.style.display === "none") return;1770      if (e.key === "ArrowDown" && !collapsed) {1771        e.preventDefault();1772        (rows.firstElementChild as HTMLElement | null)?.focus();1773      } else if (e.key === "Escape") {1774        e.preventDefault();1775        list.style.display = "none";1776      }1777    });1778    inp.addEventListener("blur", (e) => {1779      const rt = (e as FocusEvent).relatedTarget as Node | null;1780      if (rt && list.contains(rt)) return;1781      setTimeout(() => { list.style.display = "none"; }, 150);1782    });1783  }17841785  async function showCreateForm() {1786    currentMode = "create";1787    container.innerHTML = "";17881789    // Guard: the service worker may lock the vault between when the selector1790    // opens and when the user clicks "New entry". Show the inline unlock form1791    // instead of silently failing on save.1792    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1793    if (!statusRes?.unlocked) {1794      renderLocked();1795      return;1796    }17971798    // Detect page password policy once for this form — reused on every1799    // regenerate click so the user always gets a compliant password.1800    const sitePolicy = detectPasswordPolicy();18011802    // Fetch identities on-demand — they're passed in signup context but not1803    // in login/search context where the user still clicks "New entry".1804    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1805    if (!formIdentities.length) {1806      try {1807        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1808        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1809      } catch { /* silent fallback */ }1810    }18111812    const wrap = document.createElement("div");1813    wrap.className = "create-form-wrap";18141815    // Header1816    const head = document.createElement("div"); head.className = "create-head";1817    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1818    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>`;1819    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1820    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1821    head.append(backBtn, lbl);18221823    // Body1824    const body = document.createElement("div"); body.className = "create-body";18251826    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1827      const g = document.createElement("div"); g.className = "f-group";1828      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1829      const inp = document.createElement("input"); inp.className = "f-input";1830      g.append(l, inp); return { g, inp };1831    }18321833    // Title1834    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1835    body.appendChild(tg.g);18361837    // URL1838    const ug = fGroup("website");1839    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1840    if (loginSubdomain) {1841      const h = document.createElement("div"); h.className = "url-hint";1842      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1843    }1844    body.appendChild(ug.g);18451846    // Username — pre-fill from anchor if it doesn't look like an email1847    const xg = fGroup("username");1848    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1849    xg.inp.placeholder = "johndoe";1850    xg.inp.setAttribute("autocomplete", "off");1851    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1852    body.appendChild(xg.g);18531854    // Email — pre-fill from anchor if it looks like an email1855    const eg = fGroup("email");1856    (eg.inp as HTMLInputElement).type = "email";1857    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1858    eg.inp.placeholder = "[email protected]";1859    eg.inp.setAttribute("autocomplete", "off");1860    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1861    body.appendChild(eg.g);18621863    // Password — full smart generator with charset pills + length slider +1864    // policy hint. Mirrors the main UI's compact generator so users get the1865    // same controls inline as in the popup.1866    const pg = fGroup("password");1867    pg.inp.remove(); // smartGen provides its own display — no separate input needed1868    let currentPassword = prePassword || "";1869    const smartGen = createSmartGenerator({1870      policy: sitePolicy,1871      initialPassword: prePassword || undefined,1872      onChange: (pw) => { currentPassword = pw; },1873    });1874    pg.g.appendChild(smartGen.root);1875    body.appendChild(pg.g);18761877    // Save1878    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1879    saveBtn.textContent = "Save entry";1880    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1881    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1882    saveBtn.addEventListener("click", async () => {1883      const title = tg.inp.value.trim();1884      const pw = currentPassword.trim();1885      const username = xg.inp.value.trim();1886      const email = eg.inp.value.trim();1887      if (!title) {1888        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1889        showFormError("Entry needs a title");1890        return;1891      }1892      if (!pw) {1893        showFormError("Entry needs a password — tap regen to make one");1894        return;1895      }1896      errEl.style.display = "none";1897      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1898      try {1899        const res = await chrome.runtime.sendMessage({1900          type: "ADD_ENTRY",1901          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1902        });1903        if ((res as { ok?: boolean }).ok) {1904          // Fill the detected form. onFillFields uses whichever identity the1905          // page anchored on — the vault captures both username and email.1906          options.onFillFields?.(username || email, pw);1907          showSuccess(title);1908        } else {1909          const errMsg = (res as { error?: string }).error === "vault locked"1910            ? "Vault locked — open Peach to save"1911            : "Could not save entry";1912          showFormError(errMsg);1913          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1914        }1915      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1916    });1917    body.appendChild(saveBtn);1918    body.appendChild(errEl);19191920    wrap.append(head, body);1921    container.appendChild(wrap);1922    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1923  }19241925  function showSuccess(title: string) {1926    currentMode = "success";1927    container.innerHTML = "";1928    const wrap = document.createElement("div"); wrap.className = "success-wrap";1929    const ring = document.createElement("div"); ring.className = "success-ring";1930    ring.innerHTML = checkSvgStr();1931    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1932    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1933    wrap.append(ring, t, s);1934    container.appendChild(wrap);1935    setTimeout(() => dismiss(), 1600);1936  }19371938  function flashActionBtn(btn: HTMLButtonElement) {1939    btn.classList.add("flashed");1940    setTimeout(() => btn.classList.remove("flashed"), 700);1941  }19421943  // M3/QUA-005: when both the direct clipboard write and the background COPY1944  // fallback fail, briefly show the user that the copy did not happen.1945  function flashCopyError(btn: HTMLButtonElement) {1946    const original = btn.textContent ?? "";1947    btn.textContent = "Blocked";1948    btn.classList.add("flashed");1949    setTimeout(() => {1950      btn.classList.remove("flashed");1951      if (btn.isConnected) btn.textContent = original;1952    }, 1200);1953  }19541955  function renderSilverPlatter(entry: SelectorEntry) {1956    container.innerHTML = "";1957    searchInput = null;1958    focusedIndex = -1;1959    currentMode = "silver-platter";19601961    const domHdr = document.createElement("div");1962    domHdr.className = "domain-header";1963    const headText = document.createElement("div");1964    headText.className = "domain-header-text";1965    const eyebrow = document.createElement("div");1966    eyebrow.className = "domain-eyebrow";1967    eyebrow.textContent = "Saved for this site";1968    const domName = document.createElement("div");1969    domName.className = "domain-name";1970    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1971    headText.append(eyebrow, domName);1972    domHdr.appendChild(headText);1973    if (!options.isSignup) {1974      const addBtn = document.createElement("button");1975      addBtn.className = "domain-add-btn";1976      addBtn.type = "button";1977      addBtn.setAttribute("aria-label", "Create new entry");1978      addBtn.title = "Create new entry";1979      addBtn.textContent = "+";1980      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1981      domHdr.appendChild(addBtn);1982    }1983    container.appendChild(domHdr);19841985    const platter = document.createElement("div");1986    platter.className = "silver-platter";19871988    const titleEl = document.createElement("div");1989    titleEl.className = "sp-title";1990    titleEl.textContent = entry.title;1991    platter.appendChild(titleEl);19921993    if (entry.email) {1994      const emailEl = document.createElement("div");1995      emailEl.className = "sp-identity-row";1996      const emailLbl = document.createElement("span");1997      emailLbl.className = "sp-identity-label";1998      emailLbl.textContent = "email";1999      const emailVal = document.createElement("span");2000      emailVal.className = "sp-username";2001      emailVal.textContent = entry.email;2002      emailEl.append(emailLbl, emailVal);2003      platter.appendChild(emailEl);2004    }20052006    if (entry.username) {2007      const userEl = document.createElement("div");2008      userEl.className = "sp-identity-row";2009      const userLbl = document.createElement("span");2010      userLbl.className = "sp-identity-label";2011      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2012      const userVal = document.createElement("span");2013      userVal.className = "sp-username";2014      userVal.textContent = entry.username;2015      userEl.append(userLbl, userVal);2016      platter.appendChild(userEl);2017    }20182019    const fillBtn = document.createElement("button");2020    fillBtn.className = "sp-fill-btn";2021    fillBtn.type = "button";2022    fillBtn.textContent = "Fill credentials";2023    fillBtn.addEventListener("click", () => {2024      if (fillBtn.disabled) return;2025      fillBtn.disabled = true;2026      fillBtn.classList.add("filled");2027      fillBtn.innerHTML = checkSvgStr();2028      // Fire the fill, then exit via the standard exit animation. The fill2029      // itself is async (handled in index.ts) — by 400ms the form is filled2030      // and the popup begins its exit. Total dwell from click to host2031      // removal: 400ms + 130ms (exit animation) = 530ms.2032      onSelect(entry.id);2033      setTimeout(() => dismiss(), 400);2034    });2035    platter.appendChild(fillBtn);20362037    const actionsGroup = document.createElement("div");2038    actionsGroup.className = "sp-actions-group";2039    const actionsLabel = document.createElement("div");2040    actionsLabel.className = "sp-actions-label";2041    actionsLabel.textContent = "Copy";2042    actionsGroup.appendChild(actionsLabel);20432044    const actions = document.createElement("div");2045    actions.className = "sp-actions";2046    actionsGroup.appendChild(actions);20472048    if (entry.email) {2049      const copyEmail = document.createElement("button");2050      copyEmail.className = "sp-action-btn";2051      copyEmail.type = "button";2052      copyEmail.title = "Copy email";2053      copyEmail.textContent = "Email";2054      copyEmail.addEventListener("click", async (e) => {2055        e.stopPropagation();2056        let alreadyWritten = false;2057        try {2058          await navigator.clipboard.writeText(entry.email!);2059          alreadyWritten = true;2060        } catch (err) {2061          console.warn("[Peach] clipboard write denied:", err);2062        }2063        const resp = await chrome.runtime.sendMessage({2064          type: "COPY",2065          payload: { text: entry.email, label: "Email", alreadyWritten },2066        }).catch(() => null) as { ok?: boolean } | null;2067        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2068        else flashCopyError(copyEmail);2069      });2070      actions.appendChild(copyEmail);2071    }20722073    const copyU = document.createElement("button");2074    copyU.className = "sp-action-btn";2075    copyU.type = "button";2076    const usernameIsEmail = entry.username?.includes("@") ?? false;2077    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2078    copyU.textContent = usernameIsEmail ? "Email" : "Username";2079    copyU.disabled = !entry.username;2080    copyU.addEventListener("click", async (e) => {2081      e.stopPropagation();2082      if (!entry.username) return;2083      let alreadyWritten = false;2084      try {2085        await navigator.clipboard.writeText(entry.username);2086        alreadyWritten = true;2087      } catch (err) {2088        console.warn("[Peach] clipboard write denied:", err);2089      }2090      const resp = await chrome.runtime.sendMessage({2091        type: "COPY",2092        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2093      }).catch(() => null) as { ok?: boolean } | null;2094      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2095      else flashCopyError(copyU);2096    });2097    actions.appendChild(copyU);20982099    const copyP = document.createElement("button");2100    copyP.className = "sp-action-btn";2101    copyP.type = "button";2102    copyP.title = "Copy password";2103    copyP.textContent = "Password";2104    copyP.addEventListener("click", async (e) => {2105      e.stopPropagation();2106      const resp = await chrome.runtime.sendMessage({2107        type: "GET_ENTRY_FOR_FILL",2108        payload: { id: entry.id },2109      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2110      if (!resp?.ok || !resp.data?.password) return;2111      let alreadyWritten = false;2112      try {2113        await navigator.clipboard.writeText(resp.data.password);2114        alreadyWritten = true;2115      } catch (err) {2116        console.warn("[Peach] clipboard write denied:", err);2117      }2118      const copyResp = await chrome.runtime.sendMessage({2119        type: "COPY",2120        payload: { text: resp.data.password, label: "Password", alreadyWritten },2121      }).catch(() => null) as { ok?: boolean } | null;2122      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2123      else flashCopyError(copyP);2124    });2125    actions.appendChild(copyP);21262127    let trayEl: HTMLDivElement | null = null;2128    let trayInterval: ReturnType<typeof setInterval> | null = null;21292130    function closeTray() {2131      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2132      trayEl?.remove();2133      trayEl = null;2134    }2135    // Register so dismiss() will close the tray and clear the interval2136    // even if the user dismisses without explicitly closing the tray.2137    cleanupHooks.push(closeTray);21382139    async function openTOTPTray() {2140      // Fetch the entry to get the TOTP secret. The selector summary doesn't2141      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2142      // the message-passing surface minimal per Projects.md §5.2).2143      const resp = await chrome.runtime.sendMessage({2144        type: "GET_ENTRY_FOR_FILL",2145        payload: { id: entry.id },2146      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2147      const secret = resp?.ok ? resp.data?.totp : undefined;2148      if (!secret) return;21492150      trayEl = document.createElement("div");2151      trayEl.className = "sp-tray";21522153      const label = document.createElement("span");2154      label.className = "sp-tray-label";2155      label.textContent = "2FA";2156      trayEl.appendChild(label);21572158      const codeEl = document.createElement("div");2159      codeEl.className = "sp-totp-code";2160      trayEl.appendChild(codeEl);21612162      const ringNs = "http://www.w3.org/2000/svg";2163      const ring = document.createElementNS(ringNs, "svg");2164      ring.setAttribute("class", "sp-totp-ring");2165      ring.setAttribute("viewBox", "0 0 24 24");2166      const trackC = document.createElementNS(ringNs, "circle");2167      trackC.setAttribute("class", "ring-track");2168      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2169      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2170      const fillC = document.createElementNS(ringNs, "circle");2171      fillC.setAttribute("class", "ring-fill");2172      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2173      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2174      fillC.setAttribute("stroke-linecap", "round");2175      fillC.setAttribute("stroke-dasharray", "62.83");2176      ring.append(trackC, fillC);2177      trayEl.appendChild(ring);21782179      const copyBtn = document.createElement("button");2180      copyBtn.className = "sp-totp-copy";2181      copyBtn.type = "button";2182      copyBtn.textContent = "Copy";2183      trayEl.appendChild(copyBtn);21842185      function refresh() {2186        const { code, remaining } = generateTOTP(secret!);2187        // Group as "847 291" — easier to read than "847291"2188        codeEl.textContent = code.length === 62189          ? `${code.slice(0, 3)} ${code.slice(3)}`2190          : code;2191        // Ring fills counter-clockwise as time elapses: dashoffset goes from2192        // 0 (full ring) to 62.83 (empty) over the 30s window.2193        const fraction = (30 - remaining) / 30;2194        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2195      }2196      refresh();2197      trayInterval = setInterval(refresh, 1000);21982199      copyBtn.addEventListener("click", async (e) => {2200        e.stopPropagation();2201        const { code } = generateTOTP(secret!);2202        let alreadyWritten = false;2203        try {2204          await navigator.clipboard.writeText(code);2205          alreadyWritten = true;2206        } catch (err) {2207          console.warn("[Peach] clipboard write denied:", err);2208        }2209        const resp = await chrome.runtime.sendMessage({2210          type: "COPY",2211          payload: { text: code, label: "TOTP", alreadyWritten },2212        }).catch(() => null) as { ok?: boolean } | null;2213        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2214        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2215      });22162217      platter.appendChild(trayEl);2218    }22192220    const editBtn = document.createElement("button");2221    editBtn.className = "sp-action-btn sp-action-edit";2222    editBtn.type = "button";2223    editBtn.title = "Edit entry";2224    editBtn.textContent = "Edit";2225    editBtn.addEventListener("click", (e) => {2226      e.stopPropagation();2227      closeTray();2228      void renderInlineEdit(entry);2229    });2230    actions.appendChild(editBtn);22312232    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2233    // "···" toggle was zero-savings (the toggle button took the same space2234    // the "2FA" label needed) and made the code one extra click away.2235    if (entry.hasTotp) void openTOTPTray();22362237    platter.appendChild(actionsGroup);2238    container.appendChild(platter);2239  }22402241  /**2242   * Inline-popup edit mode. Swaps the silver platter for an editable form2243   * over the same shadow-DOM surface so the user never leaves the page.2244   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2245   * with the new fields. Cancel returns without writing.2246   */2247  async function renderInlineEdit(summary: SelectorEntry) {2248    container.innerHTML = "";2249    const wrap = document.createElement("div");2250    wrap.className = "create-form-wrap";22512252    const head = document.createElement("div");2253    head.className = "create-head";2254    const back = document.createElement("button");2255    back.className = "back-btn";2256    back.type = "button";2257    back.title = "Cancel";2258    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>`;2259    back.addEventListener("click", () => renderSilverPlatter(summary));2260    head.appendChild(back);2261    const headLbl = document.createElement("div");2262    headLbl.className = "create-label";2263    headLbl.textContent = "Edit entry";2264    head.appendChild(headLbl);2265    wrap.appendChild(head);22662267    const body = document.createElement("div");2268    body.className = "create-body";22692270    // Loading shimmer while we fetch the full entry2271    const loading = document.createElement("div");2272    loading.className = "empty-hint";2273    loading.textContent = "loading…";2274    body.appendChild(loading);2275    wrap.appendChild(body);2276    container.appendChild(wrap);22772278    const [res, idRes] = await Promise.all([2279      chrome.runtime.sendMessage({2280        type: "GET_ENTRY_FOR_FILL",2281        payload: { id: summary.id },2282      }).catch(() => null),2283      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2284    ]);2285    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2286    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];22872288    if (!entryRes || !entryRes.ok || !entryRes.data) {2289      loading.textContent = "couldn't load this entry. try again from the popup.";2290      return;2291    }2292    body.innerHTML = "";22932294    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2295      const group = document.createElement("div");2296      group.className = "f-group";2297      const lbl = document.createElement("div");2298      lbl.className = "f-label";2299      lbl.textContent = label;2300      const input = document.createElement("input");2301      input.className = "f-input";2302      input.type = type;2303      input.value = value;2304      input.autocomplete = "off";2305      group.append(lbl, input);2306      body.appendChild(group);2307      return { g: group, inp: input };2308    }23092310    const titleInput = field("title", entryRes.data.title ?? "").inp;2311    const urlInput = field("url", entryRes.data.url ?? "").inp;2312    urlInput.classList.add("url-f");2313    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2314    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2315    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2316    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2317    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");23182319    // Password row with reveal toggle + generator2320    const pwGroup = document.createElement("div");2321    pwGroup.className = "f-group";2322    const pwLbl = document.createElement("div");2323    pwLbl.className = "f-label";2324    pwLbl.textContent = "password";2325    const pwRow = document.createElement("div");2326    pwRow.className = "f-row";2327    const pwInput = document.createElement("input");2328    pwInput.className = "f-input";2329    pwInput.type = "password";2330    pwInput.value = entryRes.data.password ?? "";2331    pwInput.autocomplete = "new-password";2332    const revealBtn = document.createElement("button");2333    revealBtn.className = "gen-btn";2334    revealBtn.type = "button";2335    revealBtn.textContent = "show";2336    revealBtn.addEventListener("click", () => {2337      const reveal = pwInput.type === "password";2338      pwInput.type = reveal ? "text" : "password";2339      revealBtn.textContent = reveal ? "hide" : "show";2340    });2341    pwRow.append(pwInput, revealBtn);2342    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2343    editSmartGen.root.style.display = "none";2344    let editGenVisible = false;2345    const genToggleBtn = document.createElement("button");2346    genToggleBtn.className = "gen-toggle-link";2347    genToggleBtn.type = "button";2348    genToggleBtn.textContent = "⚙ generate";2349    genToggleBtn.addEventListener("click", () => {2350      editGenVisible = !editGenVisible;2351      pwRow.style.display = editGenVisible ? "none" : "";2352      editSmartGen.root.style.display = editGenVisible ? "" : "none";2353      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2354    });2355    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2356    body.appendChild(pwGroup);23572358    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;23592360    // Notes2361    const notesGroup = document.createElement("div");2362    notesGroup.className = "f-group";2363    const notesLbl = document.createElement("div");2364    notesLbl.className = "f-label";2365    notesLbl.textContent = "notes";2366    const notesInput = document.createElement("textarea");2367    notesInput.className = "f-input";2368    notesInput.rows = 3;2369    notesInput.value = entryRes.data.notes ?? "";2370    notesInput.style.fontFamily = "Inter, sans-serif";2371    notesInput.style.resize = "vertical";2372    notesGroup.append(notesLbl, notesInput);2373    body.appendChild(notesGroup);23742375    // Save / Cancel row2376    const actionsRow = document.createElement("div");2377    actionsRow.className = "f-row";2378    const saveBtn = document.createElement("button");2379    saveBtn.className = "save-btn";2380    saveBtn.type = "button";2381    saveBtn.textContent = "Save changes";2382    saveBtn.style.flex = "1";2383    const cancelBtn = document.createElement("button");2384    cancelBtn.className = "gen-btn";2385    cancelBtn.type = "button";2386    cancelBtn.textContent = "cancel";2387    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2388    actionsRow.append(saveBtn, cancelBtn);2389    body.appendChild(actionsRow);23902391    saveBtn.addEventListener("click", async () => {2392      saveBtn.disabled = true;2393      const originalLabel = saveBtn.textContent;2394      saveBtn.textContent = "Saving…";2395      const patch: Record<string, unknown> = {2396        title: titleInput.value.trim(),2397        url: urlInput.value.trim(),2398        username: usernameInput.value.trim(),2399        email: emailInput.value.trim() || undefined,2400        password: pwInput.value,2401        totp: totpInput.value.trim(),2402        notes: notesInput.value,2403      };2404      const updateRes = (await chrome.runtime.sendMessage({2405        type: "UPDATE_ENTRY",2406        payload: { id: summary.id, patch },2407      }).catch(() => null)) as { ok: boolean; error?: string } | null;2408      if (!updateRes?.ok) {2409        saveBtn.disabled = false;2410        saveBtn.textContent = originalLabel;2411        const err = document.createElement("div");2412        err.className = "empty-hint";2413        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2414        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2415        body.appendChild(err);2416        setTimeout(() => err.remove(), 3000);2417        return;2418      }2419      // Refresh the platter with updated summary fields2420      const refreshed: SelectorEntry = {2421        id: summary.id,2422        title: patch.title as string,2423        username: patch.username as string,2424        email: patch.email as string | undefined,2425        url: patch.url as string,2426        hasTotp: Boolean(patch.totp),2427        hasPasskey: summary.hasPasskey,2428      };2429      renderSilverPlatter(refreshed);2430    });24312432    queueMicrotask(() => titleInput.focus());2433  }24342435  function renderLocked() {2436    container.innerHTML = "";24372438    // Domain header (same as list view)2439    const domHdr = document.createElement("div");2440    domHdr.className = "domain-header";2441    const eyebrow = document.createElement("div");2442    eyebrow.className = "domain-eyebrow";2443    eyebrow.textContent = "vault locked";2444    const domName = document.createElement("div");2445    domName.className = "domain-name";2446    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2447    domHdr.append(eyebrow, domName);2448    container.appendChild(domHdr);24492450    const wrap = document.createElement("div");2451    wrap.className = "locked-wrap";24522453    // Icon + label row2454    const head = document.createElement("div"); head.className = "locked-head";2455    const icon = document.createElement("div"); icon.className = "locked-icon";2456    icon.innerHTML = keySvgStr();2457    const title = document.createElement("div"); title.className = "locked-title";2458    title.textContent = "unlock to autofill";2459    head.append(icon, title);24602461    // Password input2462    const pwInp = document.createElement("input");2463    pwInp.className = "locked-input";2464    pwInp.type = "password";2465    pwInp.placeholder = "master password";2466    pwInp.setAttribute("autocomplete", "current-password");24672468    // Error line (hidden initially)2469    const errEl = document.createElement("div");2470    errEl.className = "locked-error";2471    errEl.style.display = "none";24722473    // Unlock button2474    const unlockBtn = document.createElement("button");2475    unlockBtn.className = "locked-btn";2476    unlockBtn.type = "button";2477    unlockBtn.textContent = "unlock";24782479    async function tryUnlock() {2480      const pw = pwInp.value.trim();2481      if (!pw) { pwInp.focus(); return; }2482      unlockBtn.disabled = true;2483      unlockBtn.textContent = "unlocking…";2484      errEl.style.display = "none";2485      try {2486        const res = await chrome.runtime.sendMessage({2487          type: "UNLOCK",2488          payload: { password: pw },2489        });2490        if ((res as { ok?: boolean }).ok) {2491          dismiss();2492          options.onUnlocked?.();2493        } else {2494          errEl.textContent = "incorrect password";2495          errEl.style.display = "block";2496          pwInp.value = "";2497          pwInp.focus();2498          unlockBtn.disabled = false;2499          unlockBtn.textContent = "unlock";2500        }2501      } catch {2502        errEl.textContent = "could not reach Peach";2503        errEl.style.display = "block";2504        unlockBtn.disabled = false;2505        unlockBtn.textContent = "unlock";2506      }2507    }25082509    pwInp.addEventListener("keydown", (e) => {2510      e.stopPropagation();2511      if (e.key === "Enter") void tryUnlock();2512    });2513    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2514    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2515    unlockBtn.addEventListener("click", () => void tryUnlock());25162517    wrap.append(head, pwInp, errEl, unlockBtn);2518    container.appendChild(wrap);25192520    // Keep the MV3 service worker alive while the locked popup is visible.2521    // Without this, the SW goes idle (~30 s) while the user types their2522    // password, and the UNLOCK message pays a 100-300 ms wakeup penalty2523    // before the crypto even starts — perceptible as a delay vs the always-2524    // live extension popup page.2525    const keepaliveId = setInterval(() => {2526      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});2527    }, 20_000);2528    cleanupHooks.push(() => clearInterval(keepaliveId));25292530    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2531    // the page reclaims focus from our Shadow DOM input before the user can2532    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2533    // Instead: intercept keystrokes at the document capture phase — this runs2534    // before any page handler regardless of which element technically has2535    // OS focus — and route them into our input.2536    const captureKeydown = (e: KeyboardEvent) => {2537      if (!host.isConnected) {2538        document.removeEventListener("keydown", captureKeydown, true);2539        return;2540      }2541      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2542      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2543      // Intercept before page handlers and give our input focus.2544      e.stopImmediatePropagation();2545      if (e.key === "Escape") { dismiss(true); return; }2546      if (e.key === "Enter") { void tryUnlock(); return; }2547      // For all other printable/editing keys, ensure our input has focus so2548      // the browser delivers the keystroke there naturally.2549      if (document.activeElement !== host) {2550        pwInp.focus({ preventScroll: true });2551      }2552    };2553    captureKeydownRef = captureKeydown;2554    document.addEventListener("keydown", captureKeydown, true);25552556    // Best-effort focus on open — may be overridden by page focus trap,2557    // but the capture listener above handles typing regardless.2558    pwInp.focus({ preventScroll: true });2559    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2560  }25612562  function handleKeyDown(e: KeyboardEvent) {2563    if (options.locked) {2564      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2565      return;2566    }2567    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2568      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2569      return;2570    }2571    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2572    const count = allEntryEls.length;2573    if (document.activeElement === searchInput) {2574      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2575      if (count === 0) return;2576      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2577    }2578    if (count === 0) return;2579    switch (e.key) {2580      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2581      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2582      case "Enter": {2583        if (focusedIndex >= 0) {2584          const el = allEntryEls[focusedIndex] as HTMLElement;2585          const id = el.dataset.id;2586          if (id) { onSelect(id); dismiss(); }2587          else if (el.classList.contains("is-new") || !id) {2588            // "New entry" row (last item, no data-id)2589            showCreateForm();2590          }2591        }2592        break;2593      }2594      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2595    }2596  }25972598  document.addEventListener("keydown", handleKeyDown);25992600  document.body.appendChild(host);26012602  function updatePosition() {2603    const r = anchorEl.getBoundingClientRect();2604    host.style.top = `${r.bottom + window.scrollY + 5}px`;2605    host.style.left = `${r.left + window.scrollX}px`;2606    host.style.width = `${popupWidth}px`;2607  }2608  // These bindings are referenced from renderLocked()/dismiss() — they MUST2609  // be initialized before renderLocked() runs, or the synchronous assignment2610  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2611  // and throws ReferenceError. The throw lands after the popup is rendered2612  // but before showAutofillSelector returns its dismiss handle, leaving an2613  // orphan host in the DOM (which is what caused the locked-popup stacking2614  // and missing autofocus on every click).2615  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2616  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26172618  if (options.locked) {2619    renderLocked();2620  } else if (options.isSignup && options.savedIdentities) {2621    // State 10: identity helper — signup form detected, show derived2622    // identity list (emails then usernames) instead of vault entry list.2623    renderIdentityHelper();2624  } else if (entries.length === 1 && !options.isSignup) {2625    // Silver platter (State 1): single domain match → focused fill view.2626    // Multi-match goes through renderList instead.2627    renderSilverPlatter(entries[0]!);2628  } else {2629    renderList();2630  }26312632  let exitScheduled = false;2633  function dismiss(userAction = false) {2634    // Idempotent: dismiss() can be called from multiple paths (Escape,2635    // outside click, entry select, fill success, host page nav). The exit2636    // animation must only play once and host.remove() must run exactly once.2637    if (exitScheduled) return;2638    exitScheduled = true;2639    // Detach listeners synchronously so nothing can re-trigger during the2640    // 130ms exit window (a focusin firing here would race against the2641    // dismiss-lock work in Pass 2).2642    stopObserving();2643    document.removeEventListener("click", outsideClick, { capture: true });2644    document.removeEventListener("keydown", handleKeyDown);2645    if (captureKeydownRef) {2646      document.removeEventListener("keydown", captureKeydownRef, true);2647      captureKeydownRef = null;2648    }2649    for (const cleanup of cleanupHooks) {2650      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2651    }2652    if (userAction) options.onDismiss?.();2653    container.classList.add("is-exiting");2654    setTimeout(() => host.remove(), 130);2655  }26562657  function outsideClick(ev: MouseEvent) {2658    const path = ev.composedPath();2659    // Never dismiss when clicking the anchor field itself — that click is2660    // what triggered the selector to open, and the user may click the field2661    // again to re-focus it without intending to close the selector.2662    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2663  }2664  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2665  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);26662667  return dismiss;2668}26692670export function showTOTPSelector(2671  anchorEl: HTMLInputElement,2672  entries: SelectorEntry[],2673  onFill: (id: string) => void,2674  options: { domain?: string; onDismiss?: () => void } = {}2675): () => void {2676  const host = document.createElement("div");2677  host.style.cssText = "position: absolute; z-index: 2147483647;";2678  host.style.setProperty("--peach-accent", accentHex);2679  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2680  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2681  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2682  const shadow = host.attachShadow({ mode: "closed" });26832684  const style = shadow.appendChild(document.createElement("style"));2685  style.textContent = SELECTOR_STYLES;26862687  const rect = anchorEl.getBoundingClientRect();2688  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2689  host.style.left = `${rect.left + window.scrollX}px`;2690  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2691  host.style.width = `${popupWidth}px`;26922693  const container = shadow.appendChild(document.createElement("div"));2694  container.className = "peach-inline-popup";2695  container.setAttribute("data-theme", popupTheme);26962697  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2698  const current = entries.filter((entry) => entry.hasTotp);2699  let focusedIndex = current.length === 1 ? 0 : -1;27002701  function updatePosition() {2702    const r = anchorEl.getBoundingClientRect();2703    host.style.top = `${r.bottom + window.scrollY + 5}px`;2704    host.style.left = `${r.left + window.scrollX}px`;2705    host.style.width = `${popupWidth}px`;2706  }27072708  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27092710  function choose(entry: SelectorEntry) {2711    onFill(entry.id);2712    dismiss();2713  }27142715  function render() {2716    container.innerHTML = "";27172718    const domHdr = document.createElement("div");2719    domHdr.className = "domain-header";2720    const headText = document.createElement("div");2721    headText.className = "domain-header-text";2722    const eyebrow = document.createElement("div");2723    eyebrow.className = "domain-eyebrow";2724    eyebrow.textContent = "2FA code";2725    const domName = document.createElement("div");2726    domName.className = "domain-name";2727    domName.textContent = domain;2728    headText.append(eyebrow, domName);2729    domHdr.appendChild(headText);2730    container.appendChild(domHdr);27312732    if (current.length === 1) {2733      const entry = current[0]!;2734      const platter = document.createElement("div");2735      platter.className = "silver-platter";27362737      const title = document.createElement("div");2738      title.className = "sp-title";2739      title.textContent = entry.title;2740      platter.appendChild(title);27412742      const sub = document.createElement("div");2743      sub.className = "sp-username";2744      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2745      platter.appendChild(sub);27462747      const fill = document.createElement("button");2748      fill.className = "sp-fill-btn";2749      fill.type = "button";2750      fill.textContent = "Fill 2FA code";2751      fill.addEventListener("click", () => choose(entry));2752      platter.appendChild(fill);27532754      container.appendChild(platter);2755      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2756      return;2757    }27582759    const results = document.createElement("div");2760    results.className = "results";2761    container.appendChild(results);27622763    for (let i = 0; i < current.length; i++) {2764      const entry = current[i]!;2765      const row = document.createElement("div");2766      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2767      row.dataset.index = String(i);2768      row.setAttribute("tabindex", "-1");27692770      const icon = document.createElement("div");2771      icon.className = "entry-icon";2772      icon.innerHTML = keySvgStr();2773      row.appendChild(icon);2774      const info = document.createElement("div");2775      info.className = "entry-info";2776      const title = document.createElement("div");2777      title.className = "entry-title";2778      title.textContent = entry.title;2779      const sub = document.createElement("div");2780      sub.className = "entry-sub";2781      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2782      info.append(title, sub);2783      row.appendChild(info);27842785      const badge = document.createElement("span");2786      badge.className = "totp-badge";2787      badge.textContent = "Fill";2788      row.appendChild(badge);2789      row.addEventListener("click", () => choose(entry));2790      results.appendChild(row);2791    }2792  }27932794  function setFocused(index: number) {2795    focusedIndex = index;2796    container.querySelectorAll(".entry").forEach((el, i) => {2797      el.classList.toggle("focused", i === focusedIndex);2798      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2799    });2800  }28012802  function handleKeyDown(e: KeyboardEvent) {2803    if (e.key === "Escape" || e.key === "Tab") {2804      e.preventDefault();2805      dismiss(true);2806      return;2807    }2808    if (current.length === 0) return;2809    if (e.key === "Enter") {2810      e.preventDefault();2811      choose(current[Math.max(0, focusedIndex)]!);2812      return;2813    }2814    if (current.length === 1) return;2815    if (e.key === "ArrowDown") {2816      e.preventDefault();2817      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2818    } else if (e.key === "ArrowUp") {2819      e.preventDefault();2820      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2821    }2822  }28232824  let exitScheduled = false;2825  function dismiss(userAction = false) {2826    if (exitScheduled) return;2827    exitScheduled = true;2828    stopObserving();2829    document.removeEventListener("click", outsideClick, { capture: true });2830    document.removeEventListener("keydown", handleKeyDown);2831    if (userAction) options.onDismiss?.();2832    container.classList.add("is-exiting");2833    setTimeout(() => host.remove(), 130);2834  }28352836  function outsideClick(ev: MouseEvent) {2837    const path = ev.composedPath();2838    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2839  }28402841  document.addEventListener("keydown", handleKeyDown);2842  document.body.appendChild(host);2843  render();2844  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);28452846  return dismiss;2847}28482849export interface CardSelectorEntry {2850  id: string;2851  title: string;2852  cardholderName?: string;2853  last4?: string;2854  expMonth?: string;2855  expYear?: string;2856  network?: import("../shared/types").CardNetwork;2857}28582859interface CardSelectorOptions {2860  domain?: string;2861  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2862  onFill: (entry: import("../shared/types").VaultEntry) => void;2863  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2864  onDismiss?: () => void;2865}28662867/**2868 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2869 * passkey create or get. Renders as a fixed-position floating popup (no2870 * field anchor needed — passkeys don't require a focused input). Uses the2871 * same theme tokens and entrance animation as all other inline popup states.2872 */2873export function showPasskeyProGate(): void {2874  const domain = location.hostname.replace(/^www\./, "");28752876  const host = document.createElement("div");2877  host.setAttribute("data-peach-passkey-gate", "1");2878  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2879  const shadow = host.attachShadow({ mode: "closed" });28802881  const style = document.createElement("style");2882  style.textContent = `2883    :host { all: initial; }2884    .gate-wrap {2885      position: fixed;2886      top: 50%;2887      left: 50%;2888      transform: translate(-50%, -50%);2889      width: 280px;2890      pointer-events: auto;2891      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2892    }2893    @keyframes g-in {2894      from { opacity:0; transform: translate(-50%,-52%); }2895      to   { opacity:1; transform: translate(-50%,-50%); }2896    }2897    .gate-wrap.is-exiting {2898      animation: g-out 130ms ease-in forwards;2899    }2900    @keyframes g-out {2901      to { opacity:0; transform: translate(-50%,-52%); }2902    }2903    .gate {2904      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2905      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2906      border-radius: 12px;2907      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2908      padding: 16px;2909      font-family: Inter, sans-serif;2910    }2911    .gate-header {2912      display: flex;2913      align-items: center;2914      gap: 7px;2915      margin-bottom: 12px;2916      padding-bottom: 10px;2917      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2918    }2919    .gate-domain {2920      font-size: 12px;2921      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2922      font-family: "IBM Plex Mono", monospace;2923      overflow: hidden;2924      text-overflow: ellipsis;2925      white-space: nowrap;2926    }2927    .gate-title {2928      font-size: 14px;2929      font-weight: 500;2930      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2931      margin-bottom: 6px;2932    }2933    .gate-subtitle {2934      font-size: 12px;2935      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2936      line-height: 1.5;2937      margin-bottom: 14px;2938    }2939    .gate-btn {2940      display: block;2941      width: 100%;2942      padding: 9px 0;2943      border-radius: 8px;2944      border: none;2945      cursor: pointer;2946      font-size: 13px;2947      font-family: Inter, sans-serif;2948      font-weight: 500;2949      transition: opacity 100ms;2950      margin-bottom: 7px;2951      text-align: center;2952    }2953    .gate-btn:last-child { margin-bottom: 0; }2954    .gate-btn--accent {2955      background: ${accentHex};2956      color: #fff;2957    }2958    .gate-btn--accent:hover { opacity: 0.88; }2959    .gate-btn--ghost {2960      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2961      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2962    }2963    .gate-btn--ghost:hover { opacity: 0.75; }2964    .backdrop {2965      position: fixed;2966      inset: 0;2967      pointer-events: auto;2968    }2969  `;2970  shadow.appendChild(style);29712972  const backdrop = document.createElement("div");2973  backdrop.className = "backdrop";2974  shadow.appendChild(backdrop);29752976  const wrap = document.createElement("div");2977  wrap.className = "gate-wrap";2978  shadow.appendChild(wrap);29792980  const gate = document.createElement("div");2981  gate.className = "gate";2982  wrap.appendChild(gate);29832984  // Header: peach icon + domain2985  const header = document.createElement("div");2986  header.className = "gate-header";2987  const icon = document.createElement("span");2988  icon.innerHTML = peachIconSvg();2989  const domainEl = document.createElement("span");2990  domainEl.className = "gate-domain";2991  domainEl.textContent = domain;2992  header.append(icon, domainEl);2993  gate.appendChild(header);29942995  const title = document.createElement("div");2996  title.className = "gate-title";2997  title.textContent = "Passkeys are part of Peach Pro.";2998  gate.appendChild(title);29993000  const subtitle = document.createElement("div");3001  subtitle.className = "gate-subtitle";3002  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3003  gate.appendChild(subtitle);30043005  const upgradeBtn = document.createElement("button");3006  upgradeBtn.className = "gate-btn gate-btn--accent";3007  upgradeBtn.type = "button";3008  upgradeBtn.textContent = "Upgrade to Pro";3009  gate.appendChild(upgradeBtn);30103011  const laterBtn = document.createElement("button");3012  laterBtn.className = "gate-btn gate-btn--ghost";3013  laterBtn.type = "button";3014  laterBtn.textContent = "Not right now";3015  gate.appendChild(laterBtn);30163017  function dismiss() {3018    wrap.classList.add("is-exiting");3019    setTimeout(() => host.remove(), 130);3020  }30213022  upgradeBtn.addEventListener("click", () => {3023    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3024    dismiss();3025  });3026  laterBtn.addEventListener("click", dismiss);3027  backdrop.addEventListener("click", dismiss);30283029  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3030    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3031  });30323033  document.body.appendChild(host);3034}30353036/**3037 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3038 * detector sees the page invoke navigator.credentials.create(); content/index.ts3039 * checks vault + decline state then calls this. "Save passkey to Peach"3040 * initiates the popup-context credential flow; "Not now" records a 30-day3041 * decline for the domain so we don't re-show on every page reload.3042 */3043export function showPasskeyRegistrationOffer(args: {3044  rpId: string;3045  rpName?: string;3046  userName?: string;3047  userDisplayName?: string;3048}): void {3049  const domain = location.hostname.replace(/^www\./, "");3050  const displayName = args.rpName || domain;30513052  const host = document.createElement("div");3053  host.setAttribute("data-peach-passkey-offer", "1");3054  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3055  const shadow = host.attachShadow({ mode: "closed" });30563057  const style = document.createElement("style");3058  style.textContent = `3059    :host { all: initial; }3060    .offer-wrap {3061      position: fixed;3062      top: 16px;3063      right: 16px;3064      width: 320px;3065      pointer-events: auto;3066      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3067    }3068    @keyframes o-in {3069      from { opacity: 0; transform: translateY(-6px); }3070      to   { opacity: 1; transform: translateY(0); }3071    }3072    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3073    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3074    .offer {3075      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3076      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3077      border-radius: 12px;3078      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3079      padding: 14px 14px 12px;3080      font-family: Inter, sans-serif;3081      position: relative;3082    }3083    .offer-close {3084      position: absolute;3085      top: 8px;3086      right: 8px;3087      width: 18px;3088      height: 18px;3089      border: none;3090      background: transparent;3091      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3092      cursor: pointer;3093      font-size: 14px;3094      line-height: 1;3095      padding: 0;3096    }3097    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3098    .offer-header {3099      display: flex;3100      align-items: center;3101      gap: 7px;3102      margin-bottom: 8px;3103      padding-bottom: 8px;3104      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3105    }3106    .offer-domain {3107      font-size: 12px;3108      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3109      font-family: "IBM Plex Mono", monospace;3110      overflow: hidden;3111      text-overflow: ellipsis;3112      white-space: nowrap;3113    }3114    .offer-title {3115      font-size: 13px;3116      font-weight: 500;3117      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3118      margin-bottom: 4px;3119    }3120    .offer-subtitle {3121      font-size: 11px;3122      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3123      line-height: 1.45;3124      margin-bottom: 12px;3125    }3126    .offer-btn {3127      display: block;3128      width: 100%;3129      padding: 8px 0;3130      border-radius: 7px;3131      border: none;3132      cursor: pointer;3133      font-size: 12px;3134      font-family: Inter, sans-serif;3135      font-weight: 500;3136      transition: opacity 100ms;3137      margin-bottom: 6px;3138      text-align: center;3139    }3140    .offer-btn:last-child { margin-bottom: 0; }3141    .offer-btn--accent { background: ${accentHex}; color: #fff; }3142    .offer-btn--accent:hover { opacity: 0.88; }3143    .offer-btn--ghost {3144      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3145      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3146    }3147    .offer-btn--ghost:hover { opacity: 0.75; }3148  `;3149  shadow.appendChild(style);31503151  const wrap = document.createElement("div");3152  wrap.className = "offer-wrap";3153  shadow.appendChild(wrap);31543155  const offer = document.createElement("div");3156  offer.className = "offer";3157  wrap.appendChild(offer);31583159  const closeBtn = document.createElement("button");3160  closeBtn.className = "offer-close";3161  closeBtn.type = "button";3162  closeBtn.setAttribute("aria-label", "Dismiss");3163  closeBtn.textContent = "✕";3164  offer.appendChild(closeBtn);31653166  const header = document.createElement("div");3167  header.className = "offer-header";3168  const icon = document.createElement("span");3169  icon.innerHTML = peachIconSvg();3170  const domainEl = document.createElement("span");3171  domainEl.className = "offer-domain";3172  domainEl.textContent = domain;3173  header.append(icon, domainEl);3174  offer.appendChild(header);31753176  const title = document.createElement("div");3177  title.className = "offer-title";3178  title.textContent = "This site supports passkeys.";3179  offer.appendChild(title);31803181  const subtitle = document.createElement("div");3182  subtitle.className = "offer-subtitle";3183  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3184  offer.appendChild(subtitle);31853186  const saveBtn = document.createElement("button");3187  saveBtn.className = "offer-btn offer-btn--accent";3188  saveBtn.type = "button";3189  saveBtn.textContent = "Save passkey to Peach";3190  offer.appendChild(saveBtn);31913192  const laterBtn = document.createElement("button");3193  laterBtn.className = "offer-btn offer-btn--ghost";3194  laterBtn.type = "button";3195  laterBtn.textContent = "Not now";3196  offer.appendChild(laterBtn);31973198  function dismiss(decline: boolean) {3199    if (decline) {3200      chrome.runtime.sendMessage({3201        type: "PASSKEY_OFFER_DECLINE",3202        payload: { domain },3203      }).catch(() => {});3204    }3205    wrap.classList.add("is-exiting");3206    setTimeout(() => host.remove(), 130);3207  }32083209  saveBtn.addEventListener("click", () => {3210    chrome.runtime.sendMessage({3211      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3212      payload: {3213        rpId: args.rpId,3214        rpName: args.rpName ?? displayName,3215        userName: args.userName ?? "user",3216        userDisplayName: args.userDisplayName,3217      },3218    }).catch(() => {});3219    dismiss(false);3220  });3221  laterBtn.addEventListener("click", () => dismiss(true));3222  closeBtn.addEventListener("click", () => dismiss(true));32233224  document.body.appendChild(host);3225}32263227/**3228 * State 11 — passkey available indicator. Shown when the user lands on a3229 * domain for which they already have a stored passkey. Tells them where to3230 * find it (the entry already shows in the vault list); the "Sign in with3231 * passkey" button opens the popup so they can use the platform authenticator3232 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3233 * the actual sign-in transparently, so this banner is informational only.3234 */3235export function showPasskeyAvailable(args: {3236  rpId: string;3237  userName: string;3238  fromBrowser?: "chrome" | "firefox";3239  currentBrowser?: "chrome" | "firefox" | "unknown";3240}): void {3241  const domain = location.hostname.replace(/^www\./, "");3242  const crossBrowser =3243    args.fromBrowser &&3244    args.currentBrowser &&3245    args.currentBrowser !== "unknown" &&3246    args.fromBrowser !== args.currentBrowser;32473248  const host = document.createElement("div");3249  host.setAttribute("data-peach-passkey-available", "1");3250  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3251  const shadow = host.attachShadow({ mode: "closed" });32523253  const style = document.createElement("style");3254  style.textContent = `3255    :host { all: initial; }3256    .avail-wrap {3257      position: fixed;3258      top: 16px;3259      right: 16px;3260      width: 320px;3261      pointer-events: auto;3262      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3263    }3264    @keyframes a-in {3265      from { opacity: 0; transform: translateY(-6px); }3266      to   { opacity: 1; transform: translateY(0); }3267    }3268    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3269    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3270    .avail {3271      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3272      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3273      border-radius: 12px;3274      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3275      padding: 14px 14px 12px;3276      font-family: Inter, sans-serif;3277      position: relative;3278    }3279    .avail-close {3280      position: absolute;3281      top: 8px;3282      right: 8px;3283      width: 18px;3284      height: 18px;3285      border: none;3286      background: transparent;3287      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3288      cursor: pointer;3289      font-size: 14px;3290      line-height: 1;3291      padding: 0;3292    }3293    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3294    .avail-header {3295      display: flex;3296      align-items: center;3297      gap: 7px;3298      margin-bottom: 8px;3299      padding-bottom: 8px;3300      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3301    }3302    .avail-domain {3303      font-size: 12px;3304      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3305      font-family: "IBM Plex Mono", monospace;3306    }3307    .avail-label {3308      font-size: 9px;3309      letter-spacing: 0.16em;3310      text-transform: uppercase;3311      color: ${accentHex};3312      margin-bottom: 4px;3313    }3314    .avail-user {3315      font-size: 13px;3316      font-weight: 500;3317      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3318      margin-bottom: 12px;3319      overflow: hidden;3320      text-overflow: ellipsis;3321      white-space: nowrap;3322    }3323    .avail-cross {3324      font-size: 11px;3325      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3326      line-height: 1.45;3327      margin-bottom: 12px;3328      padding: 8px;3329      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3330      border-radius: 6px;3331    }3332    .avail-btn {3333      display: block;3334      width: 100%;3335      padding: 8px 0;3336      border-radius: 7px;3337      border: none;3338      cursor: pointer;3339      font-size: 12px;3340      font-family: Inter, sans-serif;3341      font-weight: 500;3342      transition: opacity 100ms;3343      margin-bottom: 6px;3344      text-align: center;3345    }3346    .avail-btn:last-child { margin-bottom: 0; }3347    .avail-btn--accent { background: ${accentHex}; color: #fff; }3348    .avail-btn--accent:hover { opacity: 0.88; }3349    .avail-btn--ghost {3350      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3351      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3352    }3353    .avail-btn--ghost:hover { opacity: 0.75; }3354  `;3355  shadow.appendChild(style);33563357  const wrap = document.createElement("div");3358  wrap.className = "avail-wrap";3359  shadow.appendChild(wrap);33603361  const avail = document.createElement("div");3362  avail.className = "avail";3363  wrap.appendChild(avail);33643365  const closeBtn = document.createElement("button");3366  closeBtn.className = "avail-close";3367  closeBtn.type = "button";3368  closeBtn.setAttribute("aria-label", "Dismiss");3369  closeBtn.textContent = "✕";3370  avail.appendChild(closeBtn);33713372  const header = document.createElement("div");3373  header.className = "avail-header";3374  const icon = document.createElement("span");3375  icon.innerHTML = peachIconSvg();3376  const domainEl = document.createElement("span");3377  domainEl.className = "avail-domain";3378  domainEl.textContent = domain;3379  header.append(icon, domainEl);3380  avail.appendChild(header);33813382  const label = document.createElement("div");3383  label.className = "avail-label";3384  label.textContent = "PASSKEY";3385  avail.appendChild(label);33863387  const user = document.createElement("div");3388  user.className = "avail-user";3389  user.textContent = args.userName;3390  avail.appendChild(user);33913392  if (crossBrowser) {3393    const cross = document.createElement("div");3394    cross.className = "avail-cross";3395    cross.textContent =3396      args.fromBrowser === "chrome"3397        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3398        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3399    avail.appendChild(cross);3400  }34013402  const signInBtn = document.createElement("button");3403  signInBtn.className = "avail-btn avail-btn--accent";3404  signInBtn.type = "button";3405  signInBtn.textContent = "Sign in with passkey";3406  avail.appendChild(signInBtn);34073408  const passwordBtn = document.createElement("button");3409  passwordBtn.className = "avail-btn avail-btn--ghost";3410  passwordBtn.type = "button";3411  passwordBtn.textContent = "Use password instead";3412  avail.appendChild(passwordBtn);34133414  function dismiss() {3415    wrap.classList.add("is-exiting");3416    setTimeout(() => host.remove(), 130);3417  }34183419  signInBtn.addEventListener("click", () => {3420    // On Chrome: the user clicking the page's own Sign-in button is what3421    //   triggers webAuthenticationProxy → existing background flow handles it.3422    //   Our button just dismisses since the page itself drives auth.3423    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3424    //   and surface the entry for manual reference (popup view).3425    dismiss();3426    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3427  });3428  passwordBtn.addEventListener("click", dismiss);3429  closeBtn.addEventListener("click", dismiss);34303431  document.body.appendChild(host);3432}34333434/**3435 * State 7 — card silver platter. Single-card focused fill view rendered3436 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3437 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3438 * so card and login flows render identically. Multi-card list view is a3439 * follow-up; today this picks the first card.3440 */3441export function showCardSelector(3442  anchorEl: HTMLInputElement,3443  cards: CardSelectorEntry[],3444  options: CardSelectorOptions3445): () => void {3446  if (cards.length === 0) return () => {};3447  const card = cards[0]!;34483449  const host = document.createElement("div");3450  host.style.cssText = "position: absolute; z-index: 2147483647;";3451  host.style.setProperty("--peach-accent", accentHex);3452  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3453  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3454  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3455  const shadow = host.attachShadow({ mode: "closed" });34563457  const style = shadow.appendChild(document.createElement("style"));3458  style.textContent = SELECTOR_STYLES;34593460  const rect = anchorEl.getBoundingClientRect();3461  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3462  host.style.left = `${rect.left + window.scrollX}px`;3463  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;34643465  const container = shadow.appendChild(document.createElement("div"));3466  container.className = "peach-inline-popup";3467  container.setAttribute("data-theme", popupTheme);34683469  // Domain header — eyebrow communicates the card context, not the site3470  const domHdr = document.createElement("div");3471  domHdr.className = "domain-header";3472  const eyebrow = document.createElement("div");3473  eyebrow.className = "domain-eyebrow";3474  eyebrow.textContent = "Pay with Peach";3475  const domName = document.createElement("div");3476  domName.className = "domain-name";3477  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3478  domHdr.append(eyebrow, domName);3479  container.appendChild(domHdr);34803481  const platter = document.createElement("div");3482  platter.className = "card-platter";34833484  if (card.network && card.network !== "unknown") {3485    const net = document.createElement("div");3486    net.className = "cp-network";3487    net.textContent = card.network;3488    platter.appendChild(net);3489  }34903491  const nick = document.createElement("div");3492  nick.className = "cp-nickname";3493  nick.textContent = card.title;3494  platter.appendChild(nick);34953496  if (card.last4) {3497    const l4 = document.createElement("div");3498    l4.className = "cp-last4";3499    l4.textContent = `•••• ${card.last4}`;3500    platter.appendChild(l4);3501  }35023503  const meta = document.createElement("div");3504  meta.className = "cp-meta";3505  if (card.cardholderName) {3506    const name = document.createElement("span");3507    name.textContent = card.cardholderName;3508    meta.appendChild(name);3509  }3510  if (card.expMonth && card.expYear) {3511    if (card.cardholderName) {3512      const sep = document.createElement("span");3513      sep.className = "cp-meta-sep";3514      sep.textContent = "·";3515      meta.appendChild(sep);3516    }3517    const exp = document.createElement("span");3518    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3519    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3520    meta.appendChild(exp);3521  }3522  if (meta.childElementCount > 0) platter.appendChild(meta);35233524  const fillWrap = document.createElement("div");3525  fillWrap.className = "cp-fill-wrap";3526  const fillBtn = document.createElement("button");3527  fillBtn.className = "sp-fill-btn";3528  fillBtn.type = "button";3529  fillBtn.textContent = "Fill card details";3530  fillBtn.addEventListener("click", async () => {3531    if (fillBtn.disabled) return;3532    fillBtn.disabled = true;3533    fillBtn.classList.add("filled");3534    fillBtn.innerHTML = checkSvgStr();3535    const resp = await chrome.runtime.sendMessage({3536      type: "GET_ENTRY_FOR_FILL",3537      payload: { id: card.id },3538    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3539    if (resp?.ok && resp.data) options.onFill(resp.data);3540    setTimeout(() => dismiss(), 400);3541  });3542  fillWrap.appendChild(fillBtn);3543  platter.appendChild(fillWrap);35443545  // Secondary actions — copy number, copy CVC, dismiss3546  const actions = document.createElement("div");3547  actions.className = "sp-actions";35483549  function flashBtn(b: HTMLButtonElement) {3550    b.classList.add("flashed");3551    setTimeout(() => b.classList.remove("flashed"), 700);3552  }35533554  // M3/QUA-005: clipboard + background COPY both failed — show user.3555  function flashCopyError(b: HTMLButtonElement) {3556    const original = b.textContent ?? "";3557    b.textContent = "Blocked";3558    b.classList.add("flashed");3559    setTimeout(() => {3560      b.classList.remove("flashed");3561      if (b.isConnected) b.textContent = original;3562    }, 1200);3563  }35643565  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3566    const resp = await chrome.runtime.sendMessage({3567      type: "GET_ENTRY_FOR_FILL",3568      payload: { id: card.id },3569    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3570    return resp?.ok && resp.data ? resp.data : null;3571  }35723573  const copyNum = document.createElement("button");3574  copyNum.className = "sp-action-btn";3575  copyNum.type = "button";3576  copyNum.title = "Copy card number";3577  copyNum.textContent = "Copy number";3578  copyNum.addEventListener("click", async (e) => {3579    e.stopPropagation();3580    const full = await fetchFullCard();3581    if (!full?.cardNumber) return;3582    let alreadyWritten = false;3583    try {3584      await navigator.clipboard.writeText(full.cardNumber);3585      alreadyWritten = true;3586    } catch (err) {3587      console.warn("[Peach] clipboard write denied:", err);3588    }3589    const resp = await chrome.runtime.sendMessage({3590      type: "COPY",3591      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3592    }).catch(() => null) as { ok?: boolean } | null;3593    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3594    else flashCopyError(copyNum);3595  });3596  actions.appendChild(copyNum);35973598  const copyCvc = document.createElement("button");3599  copyCvc.className = "sp-action-btn";3600  copyCvc.type = "button";3601  copyCvc.title = "Copy CVC";3602  copyCvc.textContent = "Copy CVC";3603  copyCvc.addEventListener("click", async (e) => {3604    e.stopPropagation();3605    const full = await fetchFullCard();3606    if (!full?.cvc) return;3607    let alreadyWritten = false;3608    try {3609      await navigator.clipboard.writeText(full.cvc);3610      alreadyWritten = true;3611    } catch (err) {3612      console.warn("[Peach] clipboard write denied:", err);3613    }3614    const resp = await chrome.runtime.sendMessage({3615      type: "COPY",3616      payload: { text: full.cvc, label: "CVC", alreadyWritten },3617    }).catch(() => null) as { ok?: boolean } | null;3618    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3619    else flashCopyError(copyCvc);3620  });3621  actions.appendChild(copyCvc);36223623  const closeBtn = document.createElement("button");3624  closeBtn.className = "sp-action-btn";3625  closeBtn.type = "button";3626  closeBtn.title = "Dismiss";3627  closeBtn.textContent = "✕";3628  closeBtn.addEventListener("click", (e) => {3629    e.stopPropagation();3630    dismiss(true);3631  });3632  actions.appendChild(closeBtn);36333634  platter.appendChild(actions);3635  container.appendChild(platter);36363637  document.body.appendChild(host);3638  function updatePosition() {3639    const r = anchorEl.getBoundingClientRect();3640    host.style.top = `${r.bottom + window.scrollY + 5}px`;3641    host.style.left = `${r.left + window.scrollX}px`;3642  }3643  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);36443645  function onKeyDown(e: KeyboardEvent) {3646    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3647  }3648  document.addEventListener("keydown", onKeyDown);36493650  let exitScheduled = false;3651  function dismiss(userAction = false) {3652    if (exitScheduled) return;3653    exitScheduled = true;3654    stopObserving();3655    document.removeEventListener("click", outsideClick, { capture: true });3656    document.removeEventListener("keydown", onKeyDown);3657    if (userAction) options.onDismiss?.();3658    container.classList.add("is-exiting");3659    setTimeout(() => host.remove(), 130);3660  }36613662  function outsideClick(ev: MouseEvent) {3663    const path = ev.composedPath();3664    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3665  }3666  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);36673668  return dismiss;3669}