inject.ts

176.9 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 PasswordHistoryItem, type SavedIdentity } from "../shared/types";13import { generatePassword } from "../shared/generate";14import { detectPasswordPolicy } from "./policy";15import {16  filterSavedIdentities,17  identityFilterLabel,18  resolveCustomIdentityKind,19  type IdentityFilterMode,20  type IdentityKind,21} from "./identity-helper";2223// Coarse "time since" label for the inline password-history list. Mirrors the24// main popup's helper — "roughly when", not a precise duration.25function timeSince(when: number): string {26  const secs = Math.max(0, Math.floor((Date.now() - when) / 1000));27  if (secs < 60) return "just now";28  const mins = Math.floor(secs / 60);29  if (mins < 60) return `${mins}m ago`;30  const hours = Math.floor(mins / 60);31  if (hours < 24) return `${hours}h ago`;32  const days = Math.floor(hours / 24);33  if (days < 30) return `${days}d ago`;34  const months = Math.floor(days / 30);35  if (months < 12) return `${months}mo ago`;36  return `${Math.floor(months / 12)}y ago`;37}3839let accentHex = "#E8956D";40let popupTheme: "dark" | "light" = "dark";41chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {42  const data = resp?.data;43  const name = data?.accentColor ?? "peach";44  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";45  popupTheme = data?.theme === "light" ? "light" : "dark";46});4748// 8-digit hex alpha helpers for the accent-derived shadow tokens.49// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing50// two hex digits as the alpha channel.51function withAlpha(hex: string, alpha: string): string {52  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS53  // always exposes 6-digit hex, so this is a guard against future changes54  // shipping shorthand colors that would silently break the var injection.55  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;56}5758export interface SelectorEntry {59  id: string;60  title: string;61  username?: string;62  email?: string;63  url?: string;64  hasTotp?: boolean;65  /** True when the entry also has a passkey credential attached. */66  hasPasskey?: boolean;67}6869interface SelectorOptions {70  domain?: string;71  searchableEntries?: SelectorEntry[];72  /**73   * MV-2: lazy loader for the vault-wide searchable list. Invoked only on an74   * explicit user search gesture, never on passive popup open, so the full75   * account inventory never ships into the page world unless the user asks.76   * Result is cached for the popup's lifetime.77   */78  loadSearchableEntries?: () => Promise<SelectorEntry[]>;79  /** True when shown on a signup form — changes header label and entry-click behaviour */80  isSignup?: boolean;81  /**82   * Identity kind the current signup field is expecting. Used to avoid83   * assuming email when the user is actually filling a username.84   */85  identityKind?: IdentityKind;86  /**87   * Derived identity list (emails then usernames) for signup mode (State 10).88   * When present, renderIdentityHelper() is used instead of renderList().89   */90  savedIdentities?: SavedIdentity[];91  /**92   * Called after the user picks a saved identity (signup mode only) or93   * after successfully saving a new entry on a signup form.94   * Lets the caller fill the visible username + password fields.95   */96  onFillFields?: (username: string, password: string, email?: string) => void;97  /**98   * True when the form has both a distinct username field AND a distinct email99   * field (e.g. Name / Username / Email / Password signup forms). Enables the100   * two-step identity wizard: first pick the field type the user clicked on,101   * then pick the other, then generate a password.102   */103  hasEmailField?: boolean;104  /**105   * When true, show an inline unlock form instead of the entries list.106   * Used when the vault is locked so the user can unlock without opening107   * the popup.108   */109  locked?: boolean;110  /**111   * Called after a successful inline unlock — the caller should re-query112   * entries and re-open the selector with real data.113   */114  onUnlocked?: () => void;115  /**116   * Called when the user explicitly dismisses the selector (Escape, Tab, or117   * click outside) — NOT when an entry is selected or on auto-close.118   * Used by the caller to suppress spurious reopens on the same field.119   */120  onDismiss?: () => void;121}122123function getDomainFromUrl(url: string): string {124  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }125}126127function keySvgStr(): string {128  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>`;129}130131function plusSvgStr(): string {132  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>`;133}134135function searchSvgStr(): string {136  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><circle cx="5.25" cy="5.25" r="3.5"/><path d="M7.9 7.9l2.35 2.35"/></svg>`;137}138139function backSvgStr(): string {140  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 2.5L3.5 6l4 3.5"/></svg>`;141}142143function peachIconSvg(): string {144  // Peach body stays brand-peach regardless of `accentHex` — a sage or145  // sky accent must not turn the autofill icon green or blue. Accent146  // color still tints surrounding glow/hover halos below.147  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>`;148}149150function checkSvgStr(): string {151  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>`;152}153154function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {155  const { hostname, origin } = location;156  const parts = hostname.split(".");157  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",158    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",159    "oidc", "federation", "saml", "cas", "ldap"];160  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());161  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;162  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);163  return { origin, title, loginSubdomain };164}165166/**167 * Shows a bottom-of-page toast after filling credentials when the entry has168 * never matched the current site — offering to add the current origin to the169 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.170 */171export function showRememberSiteToast(172  pageDomain: string,173  entryId: string,174): void {175  const host = document.createElement("div");176  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";177  host.style.setProperty("--peach-accent", accentHex);178  const shadow = host.attachShadow({ mode: "closed" });179180  const style = document.createElement("style");181  style.textContent = `182    .bar {183      display:flex;align-items:center;gap:10px;padding:10px 14px;184      background:#131109;border:1px solid rgba(240,232,216,0.09);185      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);186      font-family:Inter,sans-serif;white-space:nowrap;187      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;188    }189    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }190    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }191    .yes {192      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;193      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;194    }195    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }196    .no {197      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;198      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;199    }200  `;201  shadow.appendChild(style);202203  const bar = document.createElement("div"); bar.className = "bar";204  const txt = document.createElement("span"); txt.className = "txt";205  txt.textContent = `Remember ${pageDomain} for this entry?`;206  const yesBtn = document.createElement("button"); yesBtn.className = "yes";207  yesBtn.textContent = "Remember";208  yesBtn.addEventListener("click", async () => {209    await chrome.runtime.sendMessage({210      type: "ADD_ADDITIONAL_URL",211      payload: { id: entryId, url: location.origin },212    });213    host.remove();214  });215  const noBtn = document.createElement("button"); noBtn.className = "no";216  noBtn.textContent = "Not now";217  noBtn.addEventListener("click", () => host.remove());218  bar.append(txt, yesBtn, noBtn);219  shadow.appendChild(bar);220  document.body.appendChild(host);221  setTimeout(() => host.remove(), 9000);222}223224interface SmartGenerator {225  root: HTMLElement;226  getPassword: () => string;227  /** Copy the current password to the clipboard with the standard pulse UX. */228  copy: () => Promise<void>;229}230231interface SmartGeneratorOptions {232  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */233  policy: PasswordPolicy;234  /**235   * Seed value: used as the displayed password without regenerating, e.g. the236   * password the user already typed into the page. The generator still237   * regenerates the moment any control changes.238   */239  initialPassword?: string;240  /** Fires every time the password regenerates (initial + on changes). */241  onChange?: (pw: string) => void;242}243244/**245 * Build the inline-popup smart-password generator. Mirrors the main popup's246 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset247 * pills + a policy hint that names the constraints Peach detected on the248 * page. Writing this in pure DOM rather than reusing the Solid component249 * keeps the content-script bundle small.250 */251function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {252  const policy = opts.policy ?? {};253254  // Start at site max (strongest password the site accepts), fall back to 64255  let length = policy.maxLength ?? 64;256  if (policy.minLength) length = Math.max(length, policy.minLength);257  if (length < 8) length = 8;258  if (length > 128) length = 128;259260  let upper = true;261  let lower = true;262  let numbers = true;263  let symbols = !policy.forbidsSymbols;264  if (policy.requiresSymbols) symbols = true;265  const forbiddenChars = policy.forbiddenChars ?? "";266267  let password = "";268269  const root = document.createElement("div");270  root.className = "pwgen-block";271272  const displayRow = root.appendChild(document.createElement("div"));273  displayRow.className = "pwgen-display-row";274  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;275  output.type = "text";276  output.className = "pwgen-output";277  output.setAttribute("autocomplete", "off");278  output.setAttribute("spellcheck", "false");279  output.setAttribute("autocorrect", "off");280  output.setAttribute("autocapitalize", "off");281282  const regenBtn = displayRow.appendChild(document.createElement("button"));283  regenBtn.className = "pwgen-icon-btn";284  regenBtn.type = "button";285  regenBtn.setAttribute("aria-label", "Regenerate password");286  regenBtn.title = "Regenerate";287  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>`;288289  const copyBtn = displayRow.appendChild(document.createElement("button"));290  copyBtn.className = "pwgen-icon-btn";291  copyBtn.type = "button";292  copyBtn.setAttribute("aria-label", "Copy password");293  copyBtn.title = "Copy";294  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>`;295296  const controls = root.appendChild(document.createElement("div"));297  controls.className = "pwgen-controls-row";298  const slider = controls.appendChild(document.createElement("input"));299  slider.type = "range";300  slider.className = "pwgen-slider";301  slider.min = "8";302  slider.max = "128";303  slider.value = String(length);304  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));305  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));306  const lenNum = controls.appendChild(document.createElement("span"));307  lenNum.className = "pwgen-len-num pwgen-len-num--edit";308  lenNum.textContent = String(length);309  lenNum.addEventListener("click", () => {310    const li = document.createElement("input");311    li.type = "text"; li.inputMode = "numeric";312    li.className = "pwgen-len-input"; li.value = String(length);313    lenNum.replaceWith(li);314    requestAnimationFrame(() => li.select());315    function commitLenEdit() {316      const n = parseInt(li.value, 10);317      if (!isNaN(n)) {318        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));319        slider.value = String(length);320        regenerate();321      }322      lenNum.textContent = String(length);323      li.replaceWith(lenNum);324    }325    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });326    li.addEventListener("blur", commitLenEdit);327  });328329  const pills = root.appendChild(document.createElement("div"));330  pills.className = "pwgen-pills";331332  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {333    const b = document.createElement("button");334    b.type = "button";335    b.className = `pwgen-pill ${on ? "is-on" : ""}`;336    b.textContent = label;337    b.addEventListener("click", () => {338      const next = !b.classList.contains("is-on");339      b.classList.toggle("is-on", next);340      onToggle(next);341    });342    return b;343  }344  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));345  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));346  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));347  pills.appendChild(makePill("!@#", symbols, (next) => {348    // The site forbids symbols — UI lets the user override but still warn.349    symbols = next;350    regenerate();351  }));352353  // Policy hint — surfaces what Peach read off the site so the user knows the354  // generator is already tuned to it. Only shows when something interesting355  // was detected.356  const hintParts: string[] = [];357  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);358  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);359  if (policy.requiresSymbols) hintParts.push("requires symbols");360  if (policy.forbidsSymbols) hintParts.push("no symbols");361  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);362  if (hintParts.length > 0) {363    const hint = root.appendChild(document.createElement("div"));364    hint.className = "pwgen-policy-hint";365    const accent = document.createElement("span");366    accent.className = "pwgen-hint-accent";367    accent.textContent = "site rules · ";368    const text = document.createTextNode(hintParts.join(" · "));369    hint.appendChild(accent);370    hint.appendChild(text);371  }372373  function regenerate() {374    // Falls back gracefully when the user toggles every charset off — the375    // shared generator forces lowercase in that case rather than throwing.376    password = generatePassword({377      length,378      includeUppercase: upper,379      includeLowercase: lower,380      includeNumbers: numbers,381      includeSymbols: symbols,382      forbiddenChars,383    });384    output.value = password;385    opts.onChange?.(password);386  }387388  output.addEventListener("input", () => {389    password = output.value;390    length = password.length;391    slider.value = String(Math.max(8, Math.min(128, length)));392    lenNum.textContent = String(length);393    opts.onChange?.(password);394  });395396  slider.addEventListener("input", () => {397    length = parseInt(slider.value, 10);398    lenNum.textContent = String(length);399    regenerate();400  });401  regenBtn.addEventListener("click", regenerate);402403  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;404  async function copy(): Promise<void> {405    try {406      await navigator.clipboard.writeText(password);407      copyBtn.classList.add("is-copied");408      if (copyResetTimer) clearTimeout(copyResetTimer);409      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);410    } catch {411      // Clipboard API may be denied — silently no-op; user still has regen UI.412    }413  }414  copyBtn.addEventListener("click", () => { void copy(); });415416  if (opts.initialPassword) {417    password = opts.initialPassword;418    output.value = password;419    opts.onChange?.(password);420  } else {421    regenerate();422  }423424  return {425    root,426    getPassword: () => password,427    copy,428  };429}430431export function observeAnchorPosition(432  anchorEl: HTMLElement,433  onUpdate: () => void434): () => void {435  let rafId = 0;436  let burstUntil = 0;437438  const runUpdate = () => {439    rafId = 0;440    onUpdate();441    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);442  };443  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };444  const scheduleBurst = (ms = 220) => {445    burstUntil = Math.max(burstUntil, performance.now() + ms);446    scheduleUpdate();447  };448449  const resizeObserver = new ResizeObserver(() => scheduleBurst());450  resizeObserver.observe(anchorEl);451  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);452453  const mutationObserver = new MutationObserver(() => scheduleBurst());454  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });455  if (anchorEl.parentElement) {456    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });457  }458459  const onScroll = () => scheduleUpdate();460  window.addEventListener("scroll", onScroll, true);461  window.addEventListener("resize", onScroll);462  window.visualViewport?.addEventListener("resize", onScroll);463  window.visualViewport?.addEventListener("scroll", onScroll);464  anchorEl.addEventListener("focus", () => scheduleBurst());465  anchorEl.addEventListener("input", () => scheduleBurst());466467  scheduleBurst(260);468469  return () => {470    if (rafId) cancelAnimationFrame(rafId);471    resizeObserver.disconnect();472    mutationObserver.disconnect();473    window.removeEventListener("scroll", onScroll, true);474    window.removeEventListener("resize", onScroll);475    window.visualViewport?.removeEventListener("resize", onScroll);476    window.visualViewport?.removeEventListener("scroll", onScroll);477  };478}479480export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {481  const button = document.createElement("button");482  button.type = "button";483  button.setAttribute("aria-label", "Peach autofill");484  button.title = "Fill with Peach";485  button.innerHTML = peachIconSvg();486  // position: fixed is load-bearing — not absolute. Absolute positioning487  // inherits the nearest positioned ancestor's box, which on sites with488  // overflow:hidden or sticky parents clips or offsets the icon. Fixed489  // anchors to the viewport and escapes all parent layout.490  button.style.cssText = `491    position: fixed; z-index: 2147483646;492    width: 26px; height: 26px; cursor: pointer;493    pointer-events: auto; border: none; padding: 3px;494    display: inline-flex; align-items: center; justify-content: center;495    background: transparent; border-radius: 999px;496    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;497    opacity: 0;498  `;499  button.addEventListener("mouseenter", () => {500    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;501    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;502    button.style.transform = "scale(1.08)";503  });504  button.addEventListener("mouseleave", () => {505    button.style.background = "transparent";506    button.style.boxShadow = "none";507    button.style.transform = "none";508  });509  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });510  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });511512  document.body.appendChild(button);513514  function updatePosition() {515    const rect = field.getBoundingClientRect();516    if (rect.width === 0 || rect.height === 0) {517      button.style.opacity = "0"; button.style.pointerEvents = "none";518      return;519    }520    const sz = 26;521    const inset = Math.max(5, Math.min(10, rect.height * 0.22));522    const top = rect.top + rect.height / 2 - sz / 2;523    // Clamp left so the icon stays fully inside the field's right edge, never524    // spilling onto an adjacent sibling button.525    const minLeft = rect.left + 4;526    const left = Math.max(minLeft, rect.right - sz - inset);527    // Hide if the field is too narrow to fit the icon cleanly (< 40px)528    if (rect.width < 40) {529      button.style.opacity = "0"; button.style.pointerEvents = "none";530      return;531    }532    button.style.top = `${top}px`;533    button.style.left = `${left}px`;534    button.style.opacity = "1"; button.style.pointerEvents = "auto";535  }536  updatePosition();537  requestAnimationFrame(() => { button.style.opacity = "1"; });538  const stopObserving = observeAnchorPosition(field, updatePosition);539  return () => { stopObserving(); button.remove(); };540}541542// All theme-dependent values resolve through tokens scoped to543// .peach-inline-popup[data-theme="dark|light"]. Accent variables544// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)545// are identical in both themes — only surface tokens differ. See546// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the547// theme switch — only literal brand-peach in peachIconSvg may stay raw.548const SELECTOR_STYLES = `549  :host { all: initial; }550  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }551552  .peach-inline-popup[data-theme="dark"] {553    --peach-bg:           #1a1410;554    --peach-bg-card:      #221c16;555    --peach-text:         #f5f0ea;556    --peach-text-dim:     #8a7a6a;557    --peach-text-muted:   #4a3a2a;558    --peach-border:       rgba(255,255,255,0.07);559    --peach-input-bg:     rgba(255,255,255,0.05);560    --peach-input-border: rgba(255,255,255,0.08);561  }562  .peach-inline-popup[data-theme="light"] {563    --peach-bg:           #fdf8f4;564    --peach-bg-card:      #f5ede4;565    --peach-text:         #1c1310;566    --peach-text-dim:     #6b5a4a;567    --peach-text-muted:   #a89080;568    --peach-border:       rgba(0,0,0,0.08);569    --peach-input-bg:     rgba(0,0,0,0.04);570    --peach-input-border: rgba(0,0,0,0.10);571  }572573  .peach-inline-popup {574    background: var(--peach-bg);575    border: 1px solid var(--peach-border-accent, var(--peach-border));576    border-radius: 14px;577    overflow: hidden;578    box-shadow:579      0 8px 40px var(--peach-glow, transparent),580      0 2px 12px rgba(0,0,0,0.5);581    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;582    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;583    transition: height 220ms cubic-bezier(0.16,1,0.3,1);584  }585  /* Light theme: shadow against a light page is too strong otherwise — drop both586     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */587  .peach-inline-popup[data-theme="light"] {588    box-shadow:589      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),590      0 2px 12px rgba(0,0,0,0.12);591  }592  .peach-inline-popup.is-exiting {593    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;594    pointer-events: none;595  }596597  @keyframes peach-enter {598    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }599    65%  { opacity: 1; filter: blur(0); }600    100% { opacity: 1; transform: translateY(0) scale(1); }601  }602  @keyframes peach-exit {603    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }604    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }605  }606  @keyframes peach-slide-in {607    from { opacity: 0; transform: translateX(12px); }608    to   { opacity: 1; transform: translateX(0); }609  }610  @keyframes peach-slide-back {611    from { opacity: 0; transform: translateX(-12px); }612    to   { opacity: 1; transform: translateX(0); }613  }614  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }615  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }616617  /* Domain header */618  .domain-header {619    padding: 9px 13px 7px;620    border-bottom: 1px solid var(--peach-border);621    display: flex; align-items: center; justify-content: space-between;622    gap: 8px;623  }624  .domain-header-text {625    display: flex; flex-direction: column; gap: 2px;626    min-width: 0; flex: 1;627  }628  .domain-eyebrow {629    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;630    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;631  }632  .domain-name {633    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);634    font-family: "IBM Plex Mono", monospace;635    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;636  }637  .domain-header-actions {638    display: inline-flex; align-items: center; gap: 5px;639    flex-shrink: 0;640  }641  .domain-add-btn,642  .domain-search-btn {643    flex-shrink: 0;644    width: 22px; height: 22px;645    display: inline-flex; align-items: center; justify-content: center;646    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);647    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);648    border-radius: 6px;649    color: var(--peach-accent);650    cursor: pointer; padding: 0;651    transition: background 120ms, border-color 120ms, transform 80ms;652    font-family: "IBM Plex Mono", monospace;653    font-size: 14px; line-height: 1;654  }655  .domain-add-btn:hover,656  .domain-search-btn:hover {657    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);658    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);659    transform: scale(1.06);660  }661  .domain-add-btn:active,662  .domain-search-btn:active { transform: scale(0.96); }663664  /* Search */665  .search-wrap {666    padding: 9px 12px 7px;667    border-bottom: 1px solid var(--peach-border);668  }669  .search {670    width: 100%; background: var(--peach-input-bg);671    border: 1px solid var(--peach-input-border);672    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;673    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;674    transition: border-color 120ms, box-shadow 120ms;675  }676  .search:focus {677    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);678    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);679  }680  .search::placeholder { color: var(--peach-text-muted); }681682  /* Results */683  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }684  .results::-webkit-scrollbar { display: none; }685686  /* Entry rows */687  .entry {688    display: flex; align-items: center; padding: 8px 12px;689    cursor: pointer; border-bottom: 1px solid var(--peach-border);690    transition: background 70ms; position: relative; outline: none;691  }692  .entry:last-child { border-bottom: none; }693  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }694  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }695  .entry.focused::before {696    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;697    width: 2px; border-radius: 2px;698    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);699  }700701  .entry-icon {702    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;703    background: var(--peach-input-bg); border: 1px solid var(--peach-border);704    display: flex; align-items: center; justify-content: center;705    overflow: hidden; margin-right: 10px;706  }707  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }708  .entry-icon.is-new {709    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);710    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);711    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);712  }713714  .entry-info { flex: 1; min-width: 0; }715  .entry-title {716    font-size: 12.5px; color: var(--peach-text);717    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;718    line-height: 1.3;719  }720  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }721  .entry-sub {722    font-size: 10px; color: var(--peach-text-dim);723    font-family: "IBM Plex Mono", monospace;724    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;725    margin-top: 1px;726  }727728  .totp-badge {729    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;730    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);731    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);732    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;733  }734  .passkey-badge {735    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;736    border-radius: 4px;737    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);738    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);739    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);740    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;741  }742743  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }744745  .empty-hint {746    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);747    font-family: "IBM Plex Mono", monospace;748  }749750  /* Create form */751  .create-form-wrap {752    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;753  }754  .create-head {755    display: flex; align-items: center; gap: 8px;756    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);757  }758  .back-btn {759    background: transparent; border: none; cursor: pointer;760    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;761    display: flex; align-items: center; line-height: 0;762    transition: color 100ms, background 100ms;763  }764  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }765  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }766  /* minmax(0, 1fr) caps the grid track at the popup width — without it,767     long monospace content (e.g. a 60-char generated password) would768     auto-size the track wider than the popup and overflow the right edge. */769  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }770  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }771  .f-label {772    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;773    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;774  }775  .f-input {776    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);777    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;778    font-size: 11px; font-family: "IBM Plex Mono", monospace;779    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;780  }781  .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); }782  .f-input::placeholder { color: var(--peach-text-muted); }783  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }784  .f-row { display: flex; gap: 6px; }785  .f-row .f-input { flex: 1; min-width: 0; }786  .gen-btn {787    padding: 0 10px; border-radius: 7px; border: none;788    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);789    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);790    font-size: 10px; font-family: "IBM Plex Mono", monospace;791    cursor: pointer; white-space: nowrap; flex-shrink: 0;792    display: flex; align-items: center; gap: 4px;793    transition: background 100ms;794  }795  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }796  .gen-toggle-link {797    background: none; border: none; padding: 2px 0;798    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);799    font-size: 10px; font-family: "IBM Plex Mono", monospace;800    cursor: pointer; text-align: left; transition: color 100ms;801  }802  .gen-toggle-link:hover { color: var(--peach-accent); }803  .pw-history {804    display: grid; gap: 4px; margin-top: 4px;805    max-height: 150px; overflow-y: auto; scrollbar-width: thin;806  }807  .pw-history-row {808    display: flex; align-items: center; justify-content: space-between; gap: 6px;809    padding: 5px 7px; border-radius: 7px;810    background: color-mix(in srgb, var(--peach-accent) 6%, transparent);811    border: 1px solid color-mix(in srgb, var(--peach-accent) 10%, transparent);812  }813  .pw-history-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }814  .pw-history-pw {815    font-family: "IBM Plex Mono", monospace; font-size: 11px;816    color: var(--peach-t1, #eee); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;817  }818  .pw-history-age {819    font-family: "IBM Plex Mono", monospace; font-size: 9px;820    color: color-mix(in srgb, var(--peach-accent) 55%, transparent); letter-spacing: 0.03em;821  }822  .pw-history-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }823  .pw-history-btn {824    background: none; border: none; padding: 2px 5px; border-radius: 5px;825    color: color-mix(in srgb, var(--peach-accent) 65%, transparent);826    font-size: 9px; font-family: "IBM Plex Mono", monospace; cursor: pointer;827    transition: color 100ms, background 100ms;828  }829  .pw-history-btn:hover {830    color: var(--peach-accent);831    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);832  }833  .pw-history-empty {834    font-family: "IBM Plex Mono", monospace; font-size: 10px; line-height: 1.45;835    color: color-mix(in srgb, var(--peach-accent) 55%, transparent);836    padding: 6px 8px; border-radius: 7px;837    background: color-mix(in srgb, var(--peach-accent) 5%, transparent);838    border: 1px solid color-mix(in srgb, var(--peach-accent) 9%, transparent);839  }840  .save-btn {841    width: 100%; padding: 8px; border-radius: 8px; border: none;842    background: var(--peach-accent); color: #fff; font-size: 12px;843    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;844    transition: background 120ms, box-shadow 120ms, transform 80ms;845    letter-spacing: 0.01em;846  }847  .save-btn:hover {848    background: color-mix(in srgb, var(--peach-accent) 82%, #000);849    box-shadow: 0 4px 20px var(--peach-glow, transparent);850  }851  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }852  .url-hint {853    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);854    font-family: "IBM Plex Mono", monospace; font-style: italic;855  }856857  /* Success */858  .success-wrap {859    display: flex; flex-direction: column; align-items: center;860    padding: 24px 16px 20px; gap: 8px;861    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;862  }863  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }864  .success-ring {865    width: 40px; height: 40px; border-radius: 50%;866    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);867    display: flex; align-items: center; justify-content: center;868  }869  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }870  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }871872  /* Silver platter (State 1 — single match) */873  .silver-platter {874    padding: 14px 14px 12px;875    display: flex; flex-direction: column; gap: 6px;876  }877  .sp-title {878    font-size: 14px; font-weight: 500; color: var(--peach-text);879    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;880    line-height: 1.25;881  }882  .sp-identity-row {883    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;884  }885  .sp-identity-label {886    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;887    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;888  }889  .sp-username {890    font-size: 12px; color: var(--peach-text-dim);891    font-family: "IBM Plex Mono", monospace;892    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;893    margin-bottom: 0;894  }895  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }896  .sp-fill-btn {897    width: 100%; padding: 11px; border-radius: 9px; border: none;898    background: var(--peach-accent); color: #fff;899    font-size: 13px; font-weight: 500; cursor: pointer;900    font-family: Inter, sans-serif; letter-spacing: 0.01em;901    display: flex; align-items: center; justify-content: center; min-height: 38px;902    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;903  }904  .sp-fill-btn:hover {905    filter: brightness(1.1);906    box-shadow: 0 4px 20px var(--peach-glow, transparent);907    transform: translateY(-1px);908  }909  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }910  .sp-fill-btn.filled {911    background: #16a34a; transform: none; filter: none;912    box-shadow: 0 4px 16px rgba(22,163,74,0.35);913    cursor: default;914  }915  .sp-fill-btn:disabled { cursor: default; }916  .sp-actions-group {917    margin-top: 6px;918    display: flex; flex-direction: column; gap: 4px;919  }920  .sp-actions-label {921    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;922    color: var(--peach-text-muted);923    font-family: "IBM Plex Mono", monospace;924    text-align: center;925  }926  .sp-actions {927    display: flex; gap: 4px; justify-content: space-between; align-items: center;928  }929  .sp-action-btn {930    flex: 1; height: 28px; border: none; border-radius: 6px;931    background: transparent; color: var(--peach-text-dim);932    font-size: 12px; cursor: pointer;933    transition: background 120ms ease, color 120ms ease;934    font-family: Inter, sans-serif; letter-spacing: 0.04em;935    display: inline-flex; align-items: center; justify-content: center; gap: 4px;936    white-space: nowrap; overflow: hidden;937  }938  .sp-action-btn:hover:not(:disabled) {939    background: color-mix(in srgb, var(--peach-text) 5%, transparent);940    color: var(--peach-text);941  }942  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }943  .sp-action-btn.flashed {944    color: var(--peach-accent);945    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);946  }947948  /* TOTP tray — shown below the silver-platter secondary actions */949  .sp-tray {950    margin-top: 8px;951    padding: 10px 12px;952    border-radius: 9px;953    background: var(--peach-input-bg);954    border: 1px solid var(--peach-input-border);955    display: flex; align-items: center; gap: 12px;956    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;957  }958  .sp-tray-label {959    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;960    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;961    flex-shrink: 0;962  }963  .sp-totp-code {964    font-size: 18px; font-weight: 500;965    color: var(--peach-text);966    font-family: "IBM Plex Mono", monospace;967    letter-spacing: 0.12em;968    flex: 1;969    text-align: center;970  }971  .sp-totp-ring {972    width: 22px; height: 22px; flex-shrink: 0;973  }974  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }975  .sp-totp-ring .ring-fill {976    stroke: var(--peach-accent);977    transition: stroke-dashoffset 1s linear;978    transform: rotate(-90deg);979    transform-origin: center;980  }981  .sp-totp-copy {982    background: transparent; border: none; cursor: pointer;983    padding: 4px 8px; border-radius: 5px;984    color: var(--peach-text-dim); font-size: 11px;985    font-family: Inter, sans-serif;986    transition: background 120ms, color 120ms;987  }988  .sp-totp-copy:hover {989    background: color-mix(in srgb, var(--peach-text) 5%, transparent);990    color: var(--peach-text);991  }992993  /* Card silver platter (State 7) — reuses .sp-* primary action classes */994  .card-platter {995    padding: 12px 14px 10px;996    display: flex; flex-direction: column; gap: 4px;997  }998  .cp-network {999    font-size: 10px; font-weight: 600;1000    color: var(--peach-accent);1001    letter-spacing: 0.08em; text-transform: uppercase;1002    font-family: Inter, sans-serif;1003  }1004  .cp-nickname {1005    font-size: 14px; font-weight: 500; color: var(--peach-text);1006    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1007    line-height: 1.2;1008  }1009  .cp-last4 {1010    font-size: 12px; color: var(--peach-text-dim);1011    font-family: "IBM Plex Mono", monospace;1012    letter-spacing: 0.04em;1013    margin-top: 2px;1014  }1015  .cp-meta {1016    font-size: 11px; color: var(--peach-text-dim);1017    font-family: "IBM Plex Mono", monospace;1018    margin-top: 2px;1019    display: flex; gap: 10px; align-items: center;1020  }1021  .cp-meta-sep { opacity: 0.5; }1022  .cp-fill-wrap { margin-top: 10px; }10231024  /* Locked state */1025  .locked-wrap {1026    display: flex; flex-direction: column; align-items: stretch;1027    padding: 14px 13px 13px; gap: 9px;1028  }1029  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }1030  .locked-icon {1031    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;1032    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1033    display: flex; align-items: center; justify-content: center;1034  }1035  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }1036  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }1037  .locked-input {1038    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1039    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;1040    font-size: 11px; font-family: "IBM Plex Mono", monospace;1041    outline: none; transition: border-color 120ms, box-shadow 120ms;1042  }1043  .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); }1044  .locked-input::placeholder { color: var(--peach-text-muted); }1045  .locked-btn {1046    width: 100%; padding: 8px; border-radius: 8px; border: none;1047    background: var(--peach-accent); color: #fff; font-size: 12px;1048    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;1049    transition: background 120ms;1050    letter-spacing: 0.01em;1051    box-shadow: 0 2px 16px var(--peach-glow, transparent);1052    animation: peach-pulse-glow 2.4s ease-in-out infinite;1053  }1054  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }1055  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }1056  .locked-error {1057    font-size: 10px; color: rgba(220,80,60,0.85);1058    font-family: "IBM Plex Mono", monospace;1059  }10601061  @keyframes peach-pulse-glow {1062    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }1063    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),1064                            0 0 48px var(--peach-glow, transparent); }1065  }10661067  /* ── State 10: identity helper ─────────────────────────────── */1068  .identity-list {1069    max-height: 192px; overflow-y: auto; padding: 4px 0;1070    scrollbar-width: none;1071  }1072  .identity-list::-webkit-scrollbar { display: none; }1073  .peach-identity-row {1074    display: flex; align-items: center; gap: 10px;1075    padding: 9px 12px; cursor: pointer; border-radius: 8px;1076    transition: background 100ms ease;1077  }1078  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1079  .peach-identity-value {1080    font-family: "IBM Plex Mono", monospace; font-size: 13px;1081    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1082  }1083  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1084  .identity-search-wrap {1085    display: flex; flex-direction: column; gap: 6px;1086  }1087  .identity-mode-toggle {1088    display: inline-flex; gap: 4px; flex-wrap: wrap;1089  }1090  .identity-mode-btn {1091    border: 1px solid var(--peach-input-border);1092    background: var(--peach-input-bg);1093    color: var(--peach-text-dim);1094    border-radius: 999px;1095    padding: 4px 9px;1096    cursor: pointer;1097    font-family: "IBM Plex Mono", monospace;1098    font-size: 9px;1099    letter-spacing: 0.03em;1100    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1101  }1102  .identity-mode-btn:hover {1103    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1104    color: var(--peach-text);1105  }1106  .identity-mode-btn.is-active {1107    color: var(--peach-accent);1108    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1109    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1110  }1111  .identity-mode-btn:active { transform: translateY(1px); }1112  .identity-custom-row {1113    display: flex; flex-direction: column; gap: 2px;1114    padding: 9px 12px; cursor: pointer; border-radius: 8px;1115    transition: background 100ms ease;1116  }1117  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1118  .identity-custom-row-title {1119    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1120  }1121  .identity-custom-row-sub {1122    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1123  }1124  .identity-empty {1125    padding: 10px 12px 2px; color: var(--peach-text-dim);1126    font-size: 10px; font-family: "IBM Plex Mono", monospace;1127  }1128  .identity-alt-row {1129    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1130    border-radius: 8px; transition: background 100ms ease;1131    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1132  }1133  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1134  .identity-escape-row {1135    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1136    border-radius: 8px; transition: background 100ms ease; outline: none;1137    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1138    margin-top: 2px;1139  }1140  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1141  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1142  .identity-alt-input-wrap.open { display: flex; }1143  .identity-alt-input {1144    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1145    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1146    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1147    outline: none; transition: border-color 120ms;1148  }1149  .identity-alt-input:focus {1150    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1151    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1152  }1153  .identity-alt-confirm {1154    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1155    background: var(--peach-accent); color: #fff; font-size: 12px;1156    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1157  }1158  /* ── Generator view (after identity picked) ────────────────── */1159  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1160  .gen-confirmed {1161    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1162    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1163    border-radius: 8px;1164  }1165  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1166  .gen-confirmed-val {1167    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1168    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1169  }1170  .gen-label {1171    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1172    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1173  }1174  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1175  .gen-pw-val {1176    flex: 1; padding: 8px 10px; border-radius: 7px;1177    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1178    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1179    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1180  }1181  .gen-regen-btn {1182    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1183    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1184    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1185    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1186  }1187  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1188  .gen-fill-btn {1189    padding: 10px; border-radius: 8px; border: none;1190    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1191    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1192    transition: filter 120ms ease, transform 80ms ease;1193  }1194  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1195  .gen-fill-btn:active { transform: translateY(0); }11961197  /* ── Smart password generator (parity with main UI compact mode) ─── */1198  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1199  .pwgen-display-row {1200    display: flex; align-items: center; gap: 6px;1201    padding: 8px 10px; border-radius: 7px;1202    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1203  }1204  .pwgen-output {1205    flex: 1; min-width: 0; width: 0;1206    font-family: "IBM Plex Mono", monospace; font-size: 12px;1207    color: var(--peach-text);1208    background: transparent; border: none; outline: none; padding: 0;1209  }1210  .pwgen-icon-btn {1211    flex-shrink: 0;1212    width: 26px; height: 26px;1213    display: inline-flex; align-items: center; justify-content: center;1214    background: transparent; border: 1px solid var(--peach-input-border);1215    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1216    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1217  }1218  .pwgen-icon-btn:hover {1219    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1220    color: var(--peach-accent);1221    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1222  }1223  .pwgen-icon-btn.is-copied {1224    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1225    color: var(--peach-accent);1226    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1227  }1228  .pwgen-controls-row {1229    display: flex; align-items: center; gap: 8px;1230    flex-wrap: wrap;1231  }1232  .pwgen-slider {1233    flex: 1; min-width: 110px;1234    accent-color: var(--peach-accent);1235    cursor: pointer; height: 2px; background: transparent;1236  }1237  .pwgen-len-num {1238    font-family: "IBM Plex Mono", monospace; font-size: 11px;1239    color: var(--peach-accent); min-width: 22px; text-align: right;1240  }1241  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1242  .pwgen-len-input {1243    font-family: "IBM Plex Mono", monospace; font-size: 11px;1244    color: var(--peach-accent); width: 28px; text-align: right;1245    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1246    outline: none; padding: 0; min-width: 22px;1247  }1248  @keyframes identity-suggest-in {1249    from { opacity: 0; transform: translateY(-4px); }1250    to   { opacity: 1; transform: none; }1251  }1252  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1253    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1254  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1255  .identity-collapse-btn {1256    margin-left: auto; background: transparent; border: none; cursor: pointer;1257    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1258    line-height: 0; border-radius: 3px;1259    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1260  }1261  .identity-collapse-btn:hover { color: var(--peach-text); }1262  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1263  .identity-rows { display: grid; grid-template-rows: 1fr;1264    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1265  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1266  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1267    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1268  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1269  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1270  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1271  .identity-filter-pill {1272    padding: 2px 7px; border-radius: 999px;1273    border: 1px solid var(--peach-input-border);1274    background: transparent; color: var(--peach-text-muted);1275    font-family: "IBM Plex Mono", monospace; font-size: 9px;1276    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1277  }1278  .identity-filter-pill.is-on {1279    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1280    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1281    color: var(--peach-accent);1282  }1283  .identity-suggest-row {1284    display: flex; align-items: center; gap: 5px;1285    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1286    background: transparent; cursor: pointer; text-align: left;1287    transition: background 80ms;1288  }1289  .identity-suggest-row:hover,1290  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1291  .identity-suggest-val {1292    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1293    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1294  }1295  .identity-suggest-type {1296    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1297    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1298  }1299  .identity-suggest-type--email {1300    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1301    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1302  }1303  .identity-suggest-type--username {1304    color: var(--peach-text-muted);1305    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1306  }1307  .identity-suggest-meta {1308    font-family: "IBM Plex Mono", monospace; font-size: 9px;1309    color: var(--peach-text-muted); flex-shrink: 0;1310  }1311  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1312  .pwgen-pill {1313    padding: 3px 8px; border-radius: 999px;1314    border: 1px solid var(--peach-input-border);1315    background: transparent; color: var(--peach-text-muted);1316    font-family: "IBM Plex Mono", monospace; font-size: 9px;1317    letter-spacing: 0.06em; cursor: pointer;1318    transition: all 130ms ease;1319  }1320  .pwgen-pill.is-on {1321    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1322    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1323    color: var(--peach-accent);1324  }1325  .pwgen-pill:not(.is-on):hover {1326    color: var(--peach-text-dim);1327    border-color: var(--peach-text-muted);1328  }1329  .pwgen-policy-hint {1330    font-size: 10px; color: var(--peach-text-muted);1331    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1332    line-height: 1.3;1333  }1334  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }13351336  /* ── Save offer (after password filled) ───────────────────── */1337  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1338  .save-offer-title {1339    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1340  }1341  .save-offer-row {1342    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1343    border-radius: 7px; background: var(--peach-input-bg);1344    border: 1px solid var(--peach-input-border);1345  }1346  .save-offer-lbl {1347    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1348    font-family: "IBM Plex Mono", monospace;1349  }1350  .save-offer-val {1351    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1352    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1353  }1354  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1355  .save-offer-save {1356    flex: 1; padding: 9px; border-radius: 8px; border: none;1357    background: var(--peach-accent); color: #fff; font-size: 13px;1358    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1359  }1360  .save-offer-save:hover { filter: brightness(1.08); }1361  .save-offer-skip {1362    flex: 1; padding: 9px; border-radius: 8px; border: none;1363    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1364    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1365    font-family: Inter, sans-serif; transition: background 100ms ease;1366  }1367  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1368`;13691370export function showAutofillSelector(1371  anchorEl: HTMLInputElement,1372  entries: SelectorEntry[],1373  onSelect: (id: string) => void,1374  options: SelectorOptions = {}1375): () => void {1376  const host = document.createElement("div");1377  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1378  // when Peach's internal inputs gain focus, immediately blurring them and closing1379  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1380  // as in-bounds (v3.6.131).1381  //1382  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1383  // A plain login page whose card uses transform/filter/backdrop-filter establishes1384  // a containing block for position:fixed, so a host mounted inside it lands offset1385  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1386  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1387  // the popup ~400px off the field and clipped it behind overflow:clip — the user1388  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1389  // everything else mounts at the document root, where fixed == viewport.1390  const modalAncestor = (1391    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1392    (() => {1393      let cur: HTMLElement | null = anchorEl.parentElement;1394      while (cur && cur !== document.body) {1395        if (window.getComputedStyle(cur).position === 'fixed') return cur;1396        cur = cur.parentElement;1397      }1398      return null;1399    })()1400  );1401  host.style.cssText = `position: fixed; z-index: 2147483647;`;1402  host.style.setProperty("--peach-accent", accentHex);1403  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1404  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1405  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1406  // Hint the compositor that top/left animate during scroll repositioning so the1407  // popup stays on the GPU layer and doesn't flicker as observeAnchorPosition1408  // re-asserts its coordinates.1409  host.style.willChange = "top, left";1410  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1411  // HOST appear focused to the outside DOM. Modal focus traps that monitor1412  // focusin then see the host (mounted inside the modal) as the focused element1413  // rather than an opaque closed-shadow node, so they don't fire their1414  // "focus escaped" handler and yank focus back. Harmless outside modals.1415  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });14161417  const style = shadow.appendChild(document.createElement("style"));1418  style.textContent = SELECTOR_STYLES;14191420  const rect = anchorEl.getBoundingClientRect();1421  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1422  // applying containing-block compensation once host.parentElement is known.1423  host.style.top = `${rect.bottom + 5}px`;1424  host.style.left = `${rect.left}px`;1425  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1426  // wide single-input fields (e.g. centered email input on signup pages).1427  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1428  // expand the host after the initial measurement.1429  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1430  host.style.width = `${popupWidth}px`;14311432  const container = shadow.appendChild(document.createElement("div"));1433  container.className = "peach-inline-popup";1434  container.setAttribute("data-theme", popupTheme);14351436  // MV-2: the vault-wide list is loaded lazily on the first search gesture,1437  // never eagerly on passive popup open. Cached for the popup's lifetime.1438  let searchableEntries: SelectorEntry[] = options.searchableEntries ?? [];1439  let searchableLoading = false;1440  let searchableLoaded = !options.loadSearchableEntries;14411442  async function ensureSearchableLoaded(rerender: () => void): Promise<void> {1443    if (searchableLoaded || searchableLoading || !options.loadSearchableEntries) {1444      return;1445    }1446    searchableLoading = true;1447    try {1448      searchableEntries = await options.loadSearchableEntries();1449    } catch {1450      searchableEntries = [];1451    } finally {1452      searchableLoaded = true;1453      searchableLoading = false;1454      rerender();1455    }1456  }1457  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();14581459  let query = "";1460  let focusedIndex = -1;1461  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" | "edit" = "list";1462  let searchInput: HTMLInputElement | null = null;1463  let identityMode: IdentityFilterMode = "both";1464  // Tracks the silver-platter entry the user pivoted away from, so the1465  // search/list header can offer a one-click way back to it. null when the1466  // popup never showed a single-match platter (e.g. multi-match list view).1467  let silverPlatterOrigin: SelectorEntry | null = null;1468  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1469  // setInterval. Add to this list — don't fan out the dismiss function.1470  const cleanupHooks: Array<() => void> = [];14711472  // Smooth height transitions whenever content changes height.1473  // ResizeObserver fires on natural height changes; we freeze the old height,1474  // then animate to the new one so the surface never jumps.1475  {1476    let prevH = 0;1477    let blocked = false;1478    const heightRo = new ResizeObserver(([entry]) => {1479      if (blocked) return;1480      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1481      if (prevH > 0 && Math.abs(h - prevH) > 1) {1482        blocked = true;1483        container.style.height = `${prevH}px`;1484        requestAnimationFrame(() => requestAnimationFrame(() => {1485          container.style.height = `${h}px`;1486          prevH = h;1487          const onEnd = (e: TransitionEvent) => {1488            if (e.propertyName !== "height") return;1489            container.style.height = "";1490            blocked = false;1491            container.removeEventListener("transitionend", onEnd);1492          };1493          container.addEventListener("transitionend", onEnd);1494        }));1495      } else {1496        prevH = h;1497      }1498    });1499    heightRo.observe(container);1500    cleanupHooks.push(() => heightRo.disconnect());1501  }15021503  // Pre-capture the anchor field value for username prefill1504  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1505  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1506  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";15071508  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1509    const seen = new Set<string>();1510    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1511  }15121513  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1514    const q = value.trim().toLowerCase();1515    const deduped = uniqueEntries(source);1516    if (!q) return deduped.slice(0, 8);1517    return deduped.filter(e =>1518      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1519    ).slice(0, 12);1520  }15211522  function activeEntries(): SelectorEntry[] {1523    // When user is typing a search, filter across all known entries (domain matches + vault)1524    if (query.trim()) {1525      const merged = uniqueEntries([...entries, ...searchableEntries]);1526      return filterEntries(merged, query);1527    }1528    // Default: show domain matches; fall back to vault search when no matches1529    if (entries.length > 0) return entries;1530    return filterEntries(searchableEntries, "").slice(0, 8);1531  }15321533  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1534    const icon = document.createElement("div");1535    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1536    if (isNew) {1537      icon.innerHTML = plusSvgStr();1538    } else {1539      // Use the generic key glyph for all entries in the page-injected selector.1540      // Avoids disclosing vault domains to any third party and avoids needing1541      // to expose the browser favicon API to page context via web_accessible_resources.1542      void url;1543      icon.innerHTML = keySvgStr();1544    }1545    return icon;1546  }15471548  function renderIdentityHelper() {1549    currentMode = "identity-helper";1550    container.innerHTML = "";1551    focusedIndex = -1;1552    searchInput = null;15531554    const fallbackKind: IdentityKind = options.identityKind ?? "username";1555    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1556    const typedQuery = query.trim();1557    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);15581559    function applyIdentity(identity: string) {1560      if (options.hasEmailField) {1561        if (options.identityKind === "email") {1562          options.onFillFields?.("", "", identity);       // fill email field now1563          renderSecondaryIdentityStep("username", identity);1564        } else {1565          options.onFillFields?.(identity, "", "");       // fill username field now1566          renderSecondaryIdentityStep("email", identity);1567        }1568      } else {1569        options.onFillFields?.(identity, "");1570        renderGenerator(identity);1571      }1572    }15731574    function applyCustomIdentity(identity: string) {1575      const trimmed = identity.trim();1576      if (!trimmed) return;1577      applyIdentity(trimmed);1578    }15791580    // Header: "NEW ACCOUNT" + domain name1581    const hdr = container.appendChild(document.createElement("div"));1582    hdr.className = "domain-header";1583    const headText = hdr.appendChild(document.createElement("div"));1584    headText.className = "domain-header-text";1585    const eyebrow = headText.appendChild(document.createElement("div"));1586    eyebrow.className = "domain-eyebrow";1587    eyebrow.textContent = "NEW ACCOUNT";1588    const domName = headText.appendChild(document.createElement("div"));1589    domName.className = "domain-name";1590    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");15911592    const actions = hdr.appendChild(document.createElement("div"));1593    actions.className = "identity-mode-toggle";1594    for (const mode of ["both", "email", "username"] as const) {1595      const btn = actions.appendChild(document.createElement("button"));1596      btn.type = "button";1597      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1598      btn.textContent = identityFilterLabel(mode);1599      btn.setAttribute("aria-pressed", String(identityMode === mode));1600      btn.addEventListener("click", () => {1601        identityMode = mode;1602        renderIdentityHelper();1603      });1604    }16051606    const searchWrap = container.appendChild(document.createElement("div"));1607    searchWrap.className = "search-wrap identity-search-wrap";1608    const search = searchWrap.appendChild(document.createElement("input"));1609    search.className = "search";1610    search.placeholder = "search identities…";1611    search.value = query;1612    search.addEventListener("input", () => {1613      query = search.value;1614      renderIdentityHelper();1615      searchInput?.focus();1616      searchInput?.setSelectionRange(query.length, query.length);1617    });1618    search.addEventListener("keydown", (e) => {1619      if (e.key === "Escape") {1620        e.preventDefault();1621        dismiss(true);1622        return;1623      }1624      if (e.key !== "Enter") return;1625      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1626      if (exact) {1627        e.preventDefault();1628        applyIdentity(exact.value);1629        return;1630      }1631      if (!typedQuery || identities.length > 0) return;1632      e.preventDefault();1633      applyCustomIdentity(typedQuery);1634    });1635    const searchTools = searchWrap.appendChild(document.createElement("div"));1636    searchTools.className = "identity-mode-toggle";1637    const sortHint = searchTools.appendChild(document.createElement("div"));1638    sortHint.className = "identity-empty";1639    sortHint.style.padding = "0";1640    sortHint.textContent = "sorted by recent use";1641    searchInput = search;1642    const customLabel = identityMode === "both"1643      ? customKind1644      : identityMode;16451646    // Identity rows1647    const list = container.appendChild(document.createElement("div"));1648    list.className = "identity-list";1649    // Bottom fade only when the list overflows its max-height and isn't scrolled1650    // to the end. A short list (1-2 identities) shows no fade, so it never looks1651    // prematurely cut off; a long list gets the affordance, which clears on1652    // reaching the bottom.1653    const updateListFade = () => {1654      const overflowing = list.scrollHeight > list.clientHeight + 1;1655      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1656      const mask = overflowing && !atBottom1657        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1658        : "none";1659      list.style.setProperty("mask-image", mask);1660      list.style.setProperty("-webkit-mask-image", mask);1661    };1662    list.addEventListener("scroll", updateListFade);1663    if (typedQuery && identities.length === 0) {1664      const empty = list.appendChild(document.createElement("div"));1665      empty.className = "identity-empty";1666      empty.textContent = identityMode === "both"1667        ? `No match for “${typedQuery}”.`1668        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1669      const custom = list.appendChild(document.createElement("div"));1670      custom.className = "identity-custom-row";1671      const customTitle = custom.appendChild(document.createElement("div"));1672      customTitle.className = "identity-custom-row-title";1673      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1674      const customSub = custom.appendChild(document.createElement("div"));1675      customSub.className = "identity-custom-row-sub";1676      customSub.textContent = "Press Enter or click to continue.";1677      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1678    }1679    for (const id of identities) {1680      const row = list.appendChild(document.createElement("div"));1681      row.className = "peach-identity-row";1682      row.setAttribute("tabindex", "-1");1683      const val = row.appendChild(document.createElement("div"));1684      val.className = "peach-identity-value";1685      val.textContent = id.value;1686      const meta = row.appendChild(document.createElement("div"));1687      meta.className = "peach-identity-meta";1688      meta.textContent = `used ${id.useCount}×`;1689      row.addEventListener("click", () => {1690        applyIdentity(id.value);1691      });1692    }16931694    updateListFade();16951696    // Divider before "Use a different email…"1697    if (identities.length > 0) {1698      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1699    }17001701    // "Use a different email/username…" expandable row1702    const altRow = container.appendChild(document.createElement("div"));1703    altRow.className = "identity-alt-row";1704    altRow.textContent = `+ Use a different ${customLabel}…`;17051706    const altInputWrap = container.appendChild(document.createElement("div"));1707    altInputWrap.className = "identity-alt-input-wrap";1708    const altInput = altInputWrap.appendChild(document.createElement("input"));1709    altInput.className = "identity-alt-input";1710    altInput.type = "text";1711    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1712    altInput.setAttribute("autocomplete", "off");1713    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1714    altConfirm.className = "identity-alt-confirm";1715    altConfirm.type = "button";1716    altConfirm.textContent = "✓";17171718    function fillCustomIdentity() {1719      const v = altInput.value.trim();1720      if (!v) return;1721      applyCustomIdentity(v);1722    }17231724    altRow.addEventListener("click", () => {1725      altRow.style.display = "none";1726      altInputWrap.classList.add("open");1727      altInput.value = typedQuery || altInput.value;1728      altInput.focus();1729      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1730    });1731    altConfirm.addEventListener("click", fillCustomIdentity);1732    altInput.addEventListener("keydown", (e) => {1733      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1734    });17351736    // Escape hatch: user already has a vault entry for this site but it1737    // wasn't detected (different domain, old entry, etc.). Tapping this1738    // switches to the full searchable list so they can find and fill it;1739    // selecting an entry there will trigger the remember-site toast if1740    // the domain isn't already associated.1741    // MV-2: with lazy loading we no longer know the vault-wide count up front,1742    // so offer the escape hatch whenever a loader (or an eager array) exists.1743    if (options.loadSearchableEntries || (options.searchableEntries?.length ?? 0) > 0) {1744      const escapeRow = container.appendChild(document.createElement("div"));1745      escapeRow.className = "identity-escape-row";1746      escapeRow.textContent = "I already have an account →";1747      escapeRow.setAttribute("tabindex", "0");1748      const toSearch = () => { void ensureSearchableLoaded(renderList); renderList(); };1749      escapeRow.addEventListener("click", toSearch);1750      escapeRow.addEventListener("keydown", (e) => {1751        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toSearch(); }1752      });1753    }17541755    requestAnimationFrame(() => {1756      search.focus();1757      search.setSelectionRange(query.length, query.length);1758    });1759  }17601761  /**1762   * Step 2 of the contextual signup wizard.1763   * `stepKind` is the identity type to collect in this step ("email" or "username").1764   * `firstValue` is what was picked in step 1 (the other type).1765   */1766  function renderSecondaryIdentityStep(stepKind: "email" | "username", firstValue: string) {1767    currentMode = "identity-helper";1768    container.innerHTML = "";17691770    const wrap = container.appendChild(document.createElement("div"));1771    wrap.className = "gen-view";17721773    // Header1774    const hdrRow = wrap.appendChild(document.createElement("div"));1775    hdrRow.className = "domain-header";1776    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1777    eyebrow2.className = "domain-eyebrow";1778    eyebrow2.textContent = "NEW ACCOUNT";1779    const domName2 = hdrRow.appendChild(document.createElement("div"));1780    domName2.className = "domain-name";1781    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");17821783    // Confirmed first step1784    const conf = wrap.appendChild(document.createElement("div"));1785    conf.className = "gen-confirmed";1786    const confCheck = conf.appendChild(document.createElement("span"));1787    confCheck.className = "gen-confirmed-check";1788    confCheck.textContent = "✓";1789    const confVal = conf.appendChild(document.createElement("div"));1790    confVal.className = "gen-confirmed-val";1791    confVal.textContent = firstValue;17921793    const stepLbl = wrap.appendChild(document.createElement("div"));1794    stepLbl.className = "gen-label";1795    stepLbl.textContent = stepKind === "email" ? "Now choose your email" : "Now choose your username";17961797    // Filter saved identities to the correct type for this step1798    const identities = (options.savedIdentities ?? [])1799      .filter(s => s.type === stepKind)1800      .sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0))1801      .slice(0, 6);18021803    const list = wrap.appendChild(document.createElement("div"));1804    list.className = "identity-list";1805    for (const id of identities) {1806      const row = list.appendChild(document.createElement("div"));1807      row.className = "peach-identity-row";1808      row.setAttribute("tabindex", "-1");1809      const val = row.appendChild(document.createElement("div"));1810      val.className = "peach-identity-value";1811      val.textContent = id.value;1812      const meta = row.appendChild(document.createElement("div"));1813      meta.className = "peach-identity-meta";1814      meta.textContent = `used ${id.useCount}×`;1815      row.addEventListener("click", () => applySecondIdentity(id.value));1816    }18171818    // Text input for a value not in the list1819    const altInputWrap = wrap.appendChild(document.createElement("div"));1820    altInputWrap.className = "identity-alt-input-wrap open";1821    const altInput = altInputWrap.appendChild(document.createElement("input"));1822    altInput.className = "identity-alt-input";1823    altInput.type = stepKind === "email" ? "email" : "text";1824    altInput.placeholder = stepKind === "email" ? "[email protected]" : "your username";1825    altInput.setAttribute("autocomplete", "off");1826    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1827    altConfirm.className = "identity-alt-confirm";1828    altConfirm.type = "button";1829    altConfirm.textContent = "→";18301831    function applySecondIdentity(value: string) {1832      const trimmed = value.trim();1833      if (!trimmed) return;1834      // Determine final email + username order before passing to the generator1835      const [email, username] = stepKind === "email"1836        ? [trimmed, firstValue]1837        : [firstValue, trimmed];1838      if (stepKind === "email") {1839        options.onFillFields?.("", "", trimmed); // fill email field1840      } else {1841        options.onFillFields?.(trimmed, "", ""); // fill username field1842      }1843      renderGenerator(email, username);1844    }18451846    altConfirm.addEventListener("click", () => applySecondIdentity(altInput.value));1847    altInput.addEventListener("keydown", (e) => {1848      if (e.key === "Enter") { e.preventDefault(); applySecondIdentity(altInput.value); }1849    });18501851    // Skip: proceed without this field1852    const skipRow = wrap.appendChild(document.createElement("div"));1853    skipRow.className = "identity-escape-row";1854    skipRow.textContent = `Skip ${stepKind} →`;1855    skipRow.setAttribute("tabindex", "0");1856    skipRow.addEventListener("click", () => {1857      const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1858      renderGenerator(email, username);1859    });1860    skipRow.addEventListener("keydown", (e) => {1861      if (e.key === "Enter" || e.key === " ") {1862        e.preventDefault();1863        const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1864        renderGenerator(email, username);1865      }1866    });18671868    requestAnimationFrame(() => { altInput.focus(); });1869  }18701871  function renderGenerator(filledEmail: string, filledUsername?: string) {1872    container.innerHTML = "";1873    const sitePolicy = detectPasswordPolicy();18741875    const wrap = container.appendChild(document.createElement("div"));1876    wrap.className = "gen-view";18771878    // Header: domain + NEW ACCOUNT1879    const hdrRow = wrap.appendChild(document.createElement("div"));1880    hdrRow.className = "domain-header";1881    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1882    eyebrow2.className = "domain-eyebrow";1883    eyebrow2.textContent = "NEW ACCOUNT";1884    const domName2 = hdrRow.appendChild(document.createElement("div"));1885    domName2.className = "domain-name";1886    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");18871888    // Confirmed identity rows — show both username and email when both were collected1889    function confirmedRow(value: string) {1890      const conf = wrap.appendChild(document.createElement("div"));1891      conf.className = "gen-confirmed";1892      const confCheck = conf.appendChild(document.createElement("span"));1893      confCheck.className = "gen-confirmed-check";1894      confCheck.textContent = "✓";1895      const confVal = conf.appendChild(document.createElement("div"));1896      confVal.className = "gen-confirmed-val";1897      confVal.textContent = value;1898    }1899    if (filledEmail) confirmedRow(filledEmail);1900    if (filledUsername && filledUsername !== filledEmail) confirmedRow(filledUsername);19011902    const lbl = wrap.appendChild(document.createElement("div"));1903    lbl.className = "gen-label";1904    lbl.textContent = "Generate a password";19051906    let currentPw = "";1907    const smartGen = createSmartGenerator({1908      policy: sitePolicy,1909      onChange: (pw) => { currentPw = pw; },1910    });1911    wrap.appendChild(smartGen.root);19121913    const fillBtn = wrap.appendChild(document.createElement("button"));1914    fillBtn.className = "gen-fill-btn";1915    fillBtn.type = "button";1916    fillBtn.textContent = "Copy & fill";1917    fillBtn.addEventListener("click", async () => {1918      if (!currentPw) return;1919      fillBtn.disabled = true;1920      fillBtn.textContent = "Saving…";1921      // Fill the page fields first — password lands immediately.1922      options.onFillFields?.("", currentPw, "");1923      // Auto-save to vault. Fall back to the save-offer form only if the save fails1924      // (vault locked, quota exceeded, etc.) so the user sees the error and can retry.1925      const saveUsername = filledUsername || filledEmail;1926      const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;1927      try {1928        const res = await chrome.runtime.sendMessage({1929          type: "ADD_ENTRY",1930          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: currentPw, type: "login" },1931        });1932        if ((res as { ok?: boolean }).ok) {1933          showSuccess(sTitle);1934        } else {1935          renderSaveOffer(filledEmail, currentPw, filledUsername);1936        }1937      } catch {1938        renderSaveOffer(filledEmail, currentPw, filledUsername);1939      }1940    });1941  }19421943  function renderSaveOffer(filledEmail: string, filledPassword: string, filledUsername?: string) {1944    container.innerHTML = "";1945    const domain = options.domain ?? location.hostname.replace(/^www\./, "");19461947    const wrap = container.appendChild(document.createElement("div"));1948    wrap.className = "save-offer";19491950    const title = wrap.appendChild(document.createElement("div"));1951    title.className = "save-offer-title";1952    title.textContent = "Save this login to Peach?";19531954    function detailRow(label: string, value: string) {1955      const row = wrap.appendChild(document.createElement("div"));1956      row.className = "save-offer-row";1957      const lbl = row.appendChild(document.createElement("div"));1958      lbl.className = "save-offer-lbl";1959      lbl.textContent = label;1960      const val = row.appendChild(document.createElement("div"));1961      val.className = "save-offer-val";1962      val.textContent = value;1963    }19641965    detailRow("site", domain);1966    // When both username and email were collected, show both; otherwise show the identity as "email"1967    if (filledUsername) {1968      detailRow("username", filledUsername);1969      if (filledEmail) detailRow("email", filledEmail);1970    } else {1971      if (filledEmail) detailRow("email", filledEmail);1972    }1973    detailRow("password", "••••••••••••••••");19741975    const btns = wrap.appendChild(document.createElement("div"));1976    btns.className = "save-offer-btns";19771978    const saveBtn = btns.appendChild(document.createElement("button"));1979    saveBtn.className = "save-offer-save";1980    saveBtn.type = "button";1981    saveBtn.textContent = "Save";1982    saveBtn.addEventListener("click", async () => {1983      saveBtn.disabled = true;1984      saveBtn.textContent = "Saving…";1985      try {1986        // When both username and email were set, save them in the correct fields.1987        // Otherwise fall back to storing the identity as the username (current behaviour).1988        const saveUsername = filledUsername || filledEmail;1989        const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;1990        const res = await chrome.runtime.sendMessage({1991          type: "ADD_ENTRY",1992          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: filledPassword, type: "login" },1993        });1994        if ((res as { ok?: boolean }).ok) {1995          showSuccess(sTitle);1996        } else {1997          saveBtn.disabled = false;1998          saveBtn.textContent = "Save";1999        }2000      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }2001    });20022003    const skipBtn = btns.appendChild(document.createElement("button"));2004    skipBtn.className = "save-offer-skip";2005    skipBtn.type = "button";2006    skipBtn.textContent = "Not now";2007    skipBtn.addEventListener("click", () => { dismiss(true); });2008  }20092010  function renderList() {2011    container.innerHTML = "";2012    focusedIndex = -1;2013    searchInput = null;2014    currentMode = "list";20152016    const current = activeEntries();20172018    // Domain header (always show) — eyebrow + domain on the left,2019    // a "+" shortcut to the create form on the right so the user is never2020    // trapped in the search list when they want to make a new entry.2021    const domHdr = document.createElement("div");2022    domHdr.className = "domain-header";2023    const headText = document.createElement("div");2024    headText.className = "domain-header-text";2025    const eyebrow = document.createElement("div");2026    eyebrow.className = "domain-eyebrow";2027    eyebrow.textContent = options.isSignup2028      ? "Sign up as"2029      : entries.length > 0 ? "Saved for this site" : "No saved login";2030    const domName = document.createElement("div");2031    domName.className = "domain-name";2032    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2033    headText.append(eyebrow, domName);2034    domHdr.appendChild(headText);20352036    if (!options.isSignup) {2037      const actions = document.createElement("div");2038      actions.className = "domain-header-actions";20392040      // Back arrow takes the place of the silver-platter's search icon when2041      // the user has pivoted away from a single-match platter — gives them2042      // a one-click way back to the original recommendation.2043      if (silverPlatterOrigin) {2044        const backBtn = document.createElement("button");2045        backBtn.className = "domain-search-btn";2046        backBtn.type = "button";2047        backBtn.setAttribute("aria-label", "Back to suggested entry");2048        backBtn.title = "Back to suggested entry";2049        backBtn.innerHTML = backSvgStr();2050        backBtn.addEventListener("click", (e) => {2051          e.stopPropagation();2052          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);2053        });2054        actions.appendChild(backBtn);2055      }20562057      const addBtn = document.createElement("button");2058      addBtn.className = "domain-add-btn";2059      addBtn.type = "button";2060      addBtn.setAttribute("aria-label", "Create new entry");2061      addBtn.title = "Create new entry";2062      addBtn.textContent = "+";2063      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2064      actions.appendChild(addBtn);20652066      domHdr.appendChild(actions);2067    }20682069    container.appendChild(domHdr);20702071    // Search — always show so user can find entries beyond the domain matches2072    const sw = document.createElement("div"); sw.className = "search-wrap";2073    searchInput = document.createElement("input");2074    searchInput.className = "search";2075    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";2076    searchInput.value = query;2077    searchInput.addEventListener("input", () => {2078      query = searchInput?.value ?? "";2079      // MV-2: typing in the search box is the explicit gesture that loads the2080      // vault-wide list (once, cached); it re-renders when it resolves.2081      void ensureSearchableLoaded(renderList);2082      renderList();2083      searchInput?.focus();2084      searchInput?.setSelectionRange(query.length, query.length);2085    });2086    sw.appendChild(searchInput);2087    container.appendChild(sw);20882089    // Results2090    const results = document.createElement("div");2091    results.className = "results";2092    container.appendChild(results);20932094    if (current.length === 0 && entries.length > 0) {2095      // Show a hint but don't render empty entries2096    }20972098    for (let i = 0; i < current.length; i++) {2099      const e = current[i]!;2100      const entryEl = document.createElement("div");2101      entryEl.className = "entry";2102      entryEl.dataset.id = e.id;2103      entryEl.dataset.index = String(i);2104      entryEl.setAttribute("tabindex", "-1");21052106      entryEl.appendChild(makeEntryIcon(e.url));21072108      const info = document.createElement("div"); info.className = "entry-info";2109      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;2110      const subEl = document.createElement("div"); subEl.className = "entry-sub";2111      const domain = e.url ? getDomainFromUrl(e.url) : "";2112      subEl.textContent = domain || e.username || "";2113      info.append(titleEl, subEl);2114      entryEl.appendChild(info);21152116      if (e.hasTotp) {2117        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";2118        entryEl.appendChild(badge);2119      }2120      if (e.hasPasskey) {2121        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";2122        entryEl.appendChild(badge);2123      }21242125      entryEl.addEventListener("click", () => {2126        if (options.isSignup && options.onFillFields) {2127          // Fill username, email, and leave password for the user to confirm2128          options.onFillFields(e.username ?? "", "", e.email);2129          dismiss();2130        } else {2131          onSelect(e.id);2132          dismiss();2133        }2134      });2135      results.appendChild(entryEl);2136    }21372138    // Divider before "New entry"2139    if (current.length > 0) {2140      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));2141    }21422143    // "New entry" row — always present2144    const newEl = document.createElement("div");2145    newEl.className = "entry";2146    newEl.setAttribute("tabindex", "-1");2147    newEl.appendChild(makeEntryIcon(undefined, true));21482149    const newInfo = document.createElement("div"); newInfo.className = "entry-info";2150    const newTitle = document.createElement("div");2151    newTitle.className = "entry-title is-new";2152    newTitle.textContent = `New entry for ${sTitle}`;2153    const newSub = document.createElement("div");2154    newSub.className = "entry-sub";2155    newSub.textContent = sOrigin;2156    newInfo.append(newTitle, newSub);2157    newEl.appendChild(newInfo);2158    newEl.addEventListener("click", showCreateForm);2159    results.appendChild(newEl);21602161    // Focus search if present2162    if (searchInput) {2163      requestAnimationFrame(() => {2164        searchInput?.focus();2165        // Seed query (from type-to-search or domain-search-btn) lands at the2166        // end so the next keystroke extends it, not overwrites.2167        searchInput?.setSelectionRange(query.length, query.length);2168      });2169    }2170  }21712172  function setFocused(idx: number) {2173    const all = container.querySelectorAll<HTMLElement>(".entry");2174    all.forEach((el, i) => el.classList.toggle("focused", i === idx));2175    focusedIndex = idx;2176    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });2177  }21782179  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {2180    const typed = identities.filter(s => s.type === fieldType);2181    if (!typed.length) return;2182    let collapsed = false;2183    let suppressNextFocus = false;21842185    const list = g.appendChild(document.createElement("div"));2186    list.className = "identity-suggest-list";2187    list.style.display = "none";21882189    // Collapse toggle — sits alone now that filter pills are gone2190    const collapseRow = list.appendChild(document.createElement("div"));2191    collapseRow.className = "identity-filter-row";2192    collapseRow.style.justifyContent = "flex-end";2193    const collapseBtn = collapseRow.appendChild(document.createElement("button"));2194    collapseBtn.type = "button";2195    collapseBtn.className = "identity-collapse-btn";2196    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>`;2197    collapseBtn.addEventListener("mousedown", (e) => {2198      e.preventDefault();2199      collapsed = !collapsed;2200      collapseBtn.classList.toggle("is-collapsed", collapsed);2201      rowsWrapper.classList.toggle("is-collapsed", collapsed);2202    });22032204    const rowsWrapper = list.appendChild(document.createElement("div"));2205    rowsWrapper.className = "identity-rows";2206    const rows = rowsWrapper.appendChild(document.createElement("div"));2207    rows.className = "identity-rows-inner";22082209    // Bottom fade only when the list actually overflows and isn't scrolled to2210    // the end — a static mask-image fades the last row even on a 1-2 item list2211    // that fits entirely, making it look cut off. Driven off live scroll state.2212    const updateRowsFade = () => {2213      const overflowing = rows.scrollHeight > rows.clientHeight + 1;2214      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;2215      const mask = overflowing && !atBottom2216        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"2217        : "none";2218      rows.style.setProperty("mask-image", mask);2219      rows.style.setProperty("-webkit-mask-image", mask);2220    };2221    rows.addEventListener("scroll", updateRowsFade);22222223    // Hides the list and removes the document-level click watcher.2224    function hideList() {2225      list.style.display = "none";2226      document.removeEventListener("mousedown", onDocMousedown, { capture: true });2227    }22282229    // Dismiss list on any mousedown that originates outside the popup's shadow2230    // DOM. This is the ONLY close trigger for the list — blur is intentionally2231    // NOT used, because modal focus traps fire blur without a mousedown (they2232    // call element.focus() programmatically in response to focusin/focusout),2233    // which caused the list to vanish before the user could pick from it.2234    function onDocMousedown(e: MouseEvent) {2235      if (e.composedPath().includes(host)) return;2236      hideList();2237    }22382239    function pick(value: string) {2240      inp.value = value;2241      hideList();2242      suppressNextFocus = true;2243      inp.focus();2244      // If a focus trap intercepts inp.focus() and redirects to anchorEl before2245      // inp ever fires its focus event, suppressNextFocus would strand the user.2246      // Clear after a short window so subsequent clicks still work.2247      setTimeout(() => { suppressNextFocus = false; }, 120);2248    }22492250    function render() {2251      const q = inp.value.toLowerCase();2252      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2253      rows.innerHTML = "";2254      if (!filtered.length) { hideList(); return; }2255      for (const s of filtered) {2256        const row = rows.appendChild(document.createElement("button"));2257        row.type = "button"; row.className = "identity-suggest-row";2258        const val = row.appendChild(document.createElement("span"));2259        val.className = "identity-suggest-val"; val.textContent = s.value;2260        const meta = row.appendChild(document.createElement("span"));2261        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2262        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2263        row.addEventListener("keydown", (e) => {2264          if (e.key === "ArrowDown") {2265            e.preventDefault();2266            (row.nextElementSibling as HTMLElement | null)?.focus();2267          } else if (e.key === "ArrowUp") {2268            e.preventDefault();2269            const prev = row.previousElementSibling as HTMLElement | null;2270            if (prev) prev.focus();2271            else inp.focus();2272          } else if (e.key === "Enter" || e.key === " ") {2273            e.preventDefault();2274            pick(s.value);2275          } else if (e.key === "Escape") {2276            e.preventDefault();2277            hideList();2278            suppressNextFocus = true;2279            inp.focus();2280          }2281        });2282        // Row blur only fires during keyboard navigation (arrow keys / Tab).2283        // Focus traps don't produce row blur events since rows aren't focused2284        // when the trap fires; this handler is therefore trap-safe.2285        row.addEventListener("blur", (e) => {2286          const rt = (e as FocusEvent).relatedTarget as Node | null;2287          if (rt && (rt === inp || list.contains(rt))) return;2288          setTimeout(() => { hideList(); }, 150);2289        });2290      }2291      list.style.display = "";2292      updateRowsFade();2293      // Register the close-on-outside-click watcher each time the list shows.2294      // addEventListener deduplicates identical (fn, options) pairs, so2295      // re-rendering on input events does not stack up listeners.2296      document.addEventListener("mousedown", onDocMousedown, { capture: true });2297    }22982299    inp.addEventListener("focus", () => {2300      if (suppressNextFocus) { suppressNextFocus = false; return; }2301      render();2302    });2303    inp.addEventListener("input", render);2304    inp.addEventListener("keydown", (e) => {2305      if (list.style.display === "none") return;2306      if (e.key === "ArrowDown" && !collapsed) {2307        e.preventDefault();2308        (rows.firstElementChild as HTMLElement | null)?.focus();2309      } else if (e.key === "Escape") {2310        e.preventDefault();2311        hideList();2312      } else if (e.key === "Tab") {2313        // Tab moves focus away intentionally — close the list.2314        hideList();2315      }2316    });2317    // No blur handler on inp. Blur fires for ANY focus movement including2318    // programmatic focus() calls from modal focus traps, which caused the list2319    // to close before the user could interact. The document mousedown listener2320    // (registered in render()) handles intentional click-outside dismissal,2321    // and the keydown handler above covers keyboard Tab/Escape.23222323    // Ensure the watcher is removed if the main popup is dismissed while the2324    // list is visible.2325    cleanupHooks.push(hideList);2326  }23272328  async function showCreateForm() {2329    currentMode = "create";2330    container.innerHTML = "";23312332    // Guard: the service worker may lock the vault between when the selector2333    // opens and when the user clicks "New entry". Show the inline unlock form2334    // instead of silently failing on save.2335    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2336    if (!statusRes?.unlocked) {2337      renderLocked();2338      return;2339    }23402341    // Detect page password policy once for this form — reused on every2342    // regenerate click so the user always gets a compliant password.2343    const sitePolicy = detectPasswordPolicy();23442345    // Fetch identities on-demand — they're passed in signup context but not2346    // in login/search context where the user still clicks "New entry".2347    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];2348    if (!formIdentities.length) {2349      try {2350        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;2351        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;2352      } catch { /* silent fallback */ }2353    }23542355    const wrap = document.createElement("div");2356    wrap.className = "create-form-wrap";23572358    // Header2359    const head = document.createElement("div"); head.className = "create-head";2360    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2361    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>`;2362    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2363    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2364    head.append(backBtn, lbl);23652366    // Body2367    const body = document.createElement("div"); body.className = "create-body";23682369    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2370      const g = document.createElement("div"); g.className = "f-group";2371      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2372      const inp = document.createElement("input"); inp.className = "f-input";2373      g.append(l, inp); return { g, inp };2374    }23752376    // Title2377    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2378    body.appendChild(tg.g);23792380    // URL2381    const ug = fGroup("website");2382    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2383    if (loginSubdomain) {2384      const h = document.createElement("div"); h.className = "url-hint";2385      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2386    }2387    body.appendChild(ug.g);23882389    // Username — pre-fill from anchor if it doesn't look like an email2390    const xg = fGroup("username");2391    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2392    xg.inp.placeholder = "johndoe";2393    xg.inp.setAttribute("autocomplete", "off");2394    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2395    body.appendChild(xg.g);23962397    // Email — pre-fill from anchor if it looks like an email2398    const eg = fGroup("email");2399    (eg.inp as HTMLInputElement).type = "email";2400    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2401    eg.inp.placeholder = "[email protected]";2402    eg.inp.setAttribute("autocomplete", "off");2403    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2404    body.appendChild(eg.g);24052406    // Password — full smart generator with charset pills + length slider +2407    // policy hint. Mirrors the main UI's compact generator so users get the2408    // same controls inline as in the popup.2409    const pg = fGroup("password");2410    pg.inp.remove(); // smartGen provides its own display — no separate input needed2411    let currentPassword = prePassword || "";2412    const smartGen = createSmartGenerator({2413      policy: sitePolicy,2414      initialPassword: prePassword || undefined,2415      onChange: (pw) => { currentPassword = pw; },2416    });2417    pg.g.appendChild(smartGen.root);2418    body.appendChild(pg.g);24192420    // Save2421    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2422    saveBtn.textContent = "Save entry";2423    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2424    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2425    saveBtn.addEventListener("click", async () => {2426      const title = tg.inp.value.trim();2427      const pw = currentPassword.trim();2428      const username = xg.inp.value.trim();2429      const email = eg.inp.value.trim();2430      if (!title) {2431        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2432        showFormError("Entry needs a title");2433        return;2434      }2435      if (!pw) {2436        showFormError("Entry needs a password — tap regen to make one");2437        return;2438      }2439      errEl.style.display = "none";2440      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2441      try {2442        const res = await chrome.runtime.sendMessage({2443          type: "ADD_ENTRY",2444          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2445        });2446        if ((res as { ok?: boolean }).ok) {2447          // Fill the detected form. onFillFields uses whichever identity the2448          // page anchored on — the vault captures both username and email.2449          options.onFillFields?.(username || email, pw);2450          showSuccess(title);2451        } else {2452          const err = (res as { error?: string })?.error;2453          const errMsg = err === "vault_locked"2454            ? "Vault locked — open Peach to save"2455            : err === "STORAGE_QUOTA_EXCEEDED"2456              ? "Out of storage — open Peach → Settings to free space"2457              : err2458                ? `Could not save: ${err}`2459                : "Could not save entry";2460          showFormError(errMsg);2461          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2462        }2463      } catch (e) {2464        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2465        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2466      }2467    });2468    body.appendChild(saveBtn);2469    body.appendChild(errEl);24702471    wrap.append(head, body);2472    container.appendChild(wrap);2473    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2474  }24752476  function showSuccess(title: string) {2477    currentMode = "success";2478    container.innerHTML = "";2479    const wrap = document.createElement("div"); wrap.className = "success-wrap";2480    const ring = document.createElement("div"); ring.className = "success-ring";2481    ring.innerHTML = checkSvgStr();2482    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2483    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2484    wrap.append(ring, t, s);2485    container.appendChild(wrap);2486    setTimeout(() => dismiss(), 1600);2487  }24882489  function flashActionBtn(btn: HTMLButtonElement) {2490    btn.classList.add("flashed");2491    setTimeout(() => btn.classList.remove("flashed"), 700);2492  }24932494  // M3/QUA-005: when both the direct clipboard write and the background COPY2495  // fallback fail, briefly show the user that the copy did not happen.2496  function flashCopyError(btn: HTMLButtonElement) {2497    const original = btn.textContent ?? "";2498    btn.textContent = "Blocked";2499    btn.classList.add("flashed");2500    setTimeout(() => {2501      btn.classList.remove("flashed");2502      if (btn.isConnected) btn.textContent = original;2503    }, 1200);2504  }25052506  function renderSilverPlatter(entry: SelectorEntry) {2507    container.innerHTML = "";2508    searchInput = null;2509    focusedIndex = -1;2510    currentMode = "silver-platter";2511    silverPlatterOrigin = entry;25122513    const domHdr = document.createElement("div");2514    domHdr.className = "domain-header";2515    const headText = document.createElement("div");2516    headText.className = "domain-header-text";2517    const eyebrow = document.createElement("div");2518    eyebrow.className = "domain-eyebrow";2519    eyebrow.textContent = "Saved for this site";2520    const domName = document.createElement("div");2521    domName.className = "domain-name";2522    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2523    headText.append(eyebrow, domName);2524    domHdr.appendChild(headText);2525    if (!options.isSignup) {2526      const actions = document.createElement("div");2527      actions.className = "domain-header-actions";25282529      // Search shortcut — same idea as type-to-search below, but visible so2530      // the user can discover that another entry is reachable from a2531      // single-match platter. Sits to the left of the create button.2532      const searchBtn = document.createElement("button");2533      searchBtn.className = "domain-search-btn";2534      searchBtn.type = "button";2535      searchBtn.setAttribute("aria-label", "Search for a different entry");2536      searchBtn.title = "Search for a different entry";2537      searchBtn.innerHTML = searchSvgStr();2538      searchBtn.addEventListener("click", (e) => {2539        e.stopPropagation();2540        query = "";2541        renderList();2542      });2543      actions.appendChild(searchBtn);25442545      const addBtn = document.createElement("button");2546      addBtn.className = "domain-add-btn";2547      addBtn.type = "button";2548      addBtn.setAttribute("aria-label", "Create new entry");2549      addBtn.title = "Create new entry";2550      addBtn.textContent = "+";2551      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2552      actions.appendChild(addBtn);25532554      domHdr.appendChild(actions);2555    }2556    container.appendChild(domHdr);25572558    const platter = document.createElement("div");2559    platter.className = "silver-platter";25602561    const titleEl = document.createElement("div");2562    titleEl.className = "sp-title";2563    titleEl.textContent = entry.title;2564    platter.appendChild(titleEl);25652566    if (entry.email) {2567      const emailEl = document.createElement("div");2568      emailEl.className = "sp-identity-row";2569      const emailLbl = document.createElement("span");2570      emailLbl.className = "sp-identity-label";2571      emailLbl.textContent = "email";2572      const emailVal = document.createElement("span");2573      emailVal.className = "sp-username";2574      emailVal.textContent = entry.email;2575      emailEl.append(emailLbl, emailVal);2576      platter.appendChild(emailEl);2577    }25782579    if (entry.username) {2580      const userEl = document.createElement("div");2581      userEl.className = "sp-identity-row";2582      const userLbl = document.createElement("span");2583      userLbl.className = "sp-identity-label";2584      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2585      const userVal = document.createElement("span");2586      userVal.className = "sp-username";2587      userVal.textContent = entry.username;2588      userEl.append(userLbl, userVal);2589      platter.appendChild(userEl);2590    }25912592    const fillBtn = document.createElement("button");2593    fillBtn.className = "sp-fill-btn";2594    fillBtn.type = "button";2595    fillBtn.textContent = "Fill credentials";2596    fillBtn.addEventListener("click", () => {2597      if (fillBtn.disabled) return;2598      fillBtn.disabled = true;2599      fillBtn.classList.add("filled");2600      fillBtn.innerHTML = checkSvgStr();2601      // Fire the fill, then exit via the standard exit animation. The fill2602      // itself is async (handled in index.ts) — by 400ms the form is filled2603      // and the popup begins its exit. Total dwell from click to host2604      // removal: 400ms + 130ms (exit animation) = 530ms.2605      onSelect(entry.id);2606      setTimeout(() => dismiss(), 400);2607    });2608    platter.appendChild(fillBtn);26092610    const actionsGroup = document.createElement("div");2611    actionsGroup.className = "sp-actions-group";2612    const actionsLabel = document.createElement("div");2613    actionsLabel.className = "sp-actions-label";2614    actionsLabel.textContent = "Copy";2615    actionsGroup.appendChild(actionsLabel);26162617    const actions = document.createElement("div");2618    actions.className = "sp-actions";2619    actionsGroup.appendChild(actions);26202621    if (entry.email) {2622      const copyEmail = document.createElement("button");2623      copyEmail.className = "sp-action-btn";2624      copyEmail.type = "button";2625      copyEmail.title = "Copy email";2626      copyEmail.textContent = "Email";2627      copyEmail.addEventListener("click", async (e) => {2628        e.stopPropagation();2629        let alreadyWritten = false;2630        try {2631          await navigator.clipboard.writeText(entry.email!);2632          alreadyWritten = true;2633        } catch (err) {2634          console.warn("[Peach] clipboard write denied:", err);2635        }2636        const resp = await chrome.runtime.sendMessage({2637          type: "COPY",2638          payload: { text: entry.email, label: "Email", alreadyWritten },2639        }).catch(() => null) as { ok?: boolean } | null;2640        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2641        else flashCopyError(copyEmail);2642      });2643      actions.appendChild(copyEmail);2644    }26452646    const copyU = document.createElement("button");2647    copyU.className = "sp-action-btn";2648    copyU.type = "button";2649    const usernameIsEmail = entry.username?.includes("@") ?? false;2650    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2651    copyU.textContent = usernameIsEmail ? "Email" : "Username";2652    copyU.disabled = !entry.username;2653    copyU.addEventListener("click", async (e) => {2654      e.stopPropagation();2655      if (!entry.username) return;2656      let alreadyWritten = false;2657      try {2658        await navigator.clipboard.writeText(entry.username);2659        alreadyWritten = true;2660      } catch (err) {2661        console.warn("[Peach] clipboard write denied:", err);2662      }2663      const resp = await chrome.runtime.sendMessage({2664        type: "COPY",2665        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2666      }).catch(() => null) as { ok?: boolean } | null;2667      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2668      else flashCopyError(copyU);2669    });2670    actions.appendChild(copyU);26712672    const copyP = document.createElement("button");2673    copyP.className = "sp-action-btn";2674    copyP.type = "button";2675    copyP.title = "Copy password";2676    copyP.textContent = "Password";2677    copyP.addEventListener("click", async (e) => {2678      e.stopPropagation();2679      const resp = await chrome.runtime.sendMessage({2680        type: "GET_ENTRY_FOR_FILL",2681        // MV-1: user explicitly picked this entry from Peach's inline summon UI.2682        payload: { id: entry.id, explicitSummon: true },2683      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2684      if (!resp?.ok || !resp.data?.password) return;2685      let alreadyWritten = false;2686      try {2687        await navigator.clipboard.writeText(resp.data.password);2688        alreadyWritten = true;2689      } catch (err) {2690        console.warn("[Peach] clipboard write denied:", err);2691      }2692      const copyResp = await chrome.runtime.sendMessage({2693        type: "COPY",2694        payload: { text: resp.data.password, label: "Password", alreadyWritten },2695      }).catch(() => null) as { ok?: boolean } | null;2696      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2697      else flashCopyError(copyP);2698    });2699    actions.appendChild(copyP);27002701    let trayEl: HTMLDivElement | null = null;2702    let trayInterval: ReturnType<typeof setInterval> | null = null;27032704    function closeTray() {2705      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2706      trayEl?.remove();2707      trayEl = null;2708    }2709    // Register so dismiss() will close the tray and clear the interval2710    // even if the user dismisses without explicitly closing the tray.2711    cleanupHooks.push(closeTray);27122713    async function openTOTPTray() {2714      // Fetch the current TOTP code from the background. The raw base32 seed2715      // never enters the content script (SEV-3-C): we receive the live 6-digit2716      // code plus the seconds remaining, count down locally, and re-fetch a2717      // fresh code only when the 30s window rolls over.2718      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2719        const r = await chrome.runtime.sendMessage({2720          type: "GET_ENTRY_FOR_FILL",2721          // MV-1: explicit user summon of this entry's live TOTP code.2722          payload: { id: entry.id, explicitSummon: true },2723        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2724        if (!r?.ok || !r.data?.totpCode) return null;2725        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2726      }2727      let current = await fetchCode();2728      if (!current) return;27292730      trayEl = document.createElement("div");2731      trayEl.className = "sp-tray";27322733      const label = document.createElement("span");2734      label.className = "sp-tray-label";2735      label.textContent = "2FA";2736      trayEl.appendChild(label);27372738      const codeEl = document.createElement("div");2739      codeEl.className = "sp-totp-code";2740      trayEl.appendChild(codeEl);27412742      const ringNs = "http://www.w3.org/2000/svg";2743      const ring = document.createElementNS(ringNs, "svg");2744      ring.setAttribute("class", "sp-totp-ring");2745      ring.setAttribute("viewBox", "0 0 24 24");2746      const trackC = document.createElementNS(ringNs, "circle");2747      trackC.setAttribute("class", "ring-track");2748      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2749      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2750      const fillC = document.createElementNS(ringNs, "circle");2751      fillC.setAttribute("class", "ring-fill");2752      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2753      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2754      fillC.setAttribute("stroke-linecap", "round");2755      fillC.setAttribute("stroke-dasharray", "62.83");2756      ring.append(trackC, fillC);2757      trayEl.appendChild(ring);27582759      const copyBtn = document.createElement("button");2760      copyBtn.className = "sp-totp-copy";2761      copyBtn.type = "button";2762      copyBtn.textContent = "Copy";2763      trayEl.appendChild(copyBtn);27642765      function render() {2766        const { code, remaining } = current!;2767        // Group as "847 291" — easier to read than "847291"2768        codeEl.textContent = code.length === 62769          ? `${code.slice(0, 3)} ${code.slice(3)}`2770          : code;2771        // Ring fills counter-clockwise as time elapses: dashoffset goes from2772        // 0 (full ring) to 62.83 (empty) over the 30s window.2773        const fraction = (30 - remaining) / 30;2774        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2775      }2776      render();2777      trayInterval = setInterval(async () => {2778        if (!current) return;2779        current = { code: current.code, remaining: current.remaining - 1 };2780        // Window rolled over — pull a fresh code from the background.2781        if (current.remaining <= 0) {2782          const next = await fetchCode();2783          current = next ?? { code: current.code, remaining: 30 };2784        }2785        render();2786      }, 1000);27872788      copyBtn.addEventListener("click", async (e) => {2789        e.stopPropagation();2790        const code = current?.code;2791        if (!code) return;2792        let alreadyWritten = false;2793        try {2794          await navigator.clipboard.writeText(code);2795          alreadyWritten = true;2796        } catch (err) {2797          console.warn("[Peach] clipboard write denied:", err);2798        }2799        const resp = await chrome.runtime.sendMessage({2800          type: "COPY",2801          payload: { text: code, label: "TOTP", alreadyWritten },2802        }).catch(() => null) as { ok?: boolean } | null;2803        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2804        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2805      });28062807      platter.appendChild(trayEl);2808    }28092810    const editBtn = document.createElement("button");2811    editBtn.className = "sp-action-btn sp-action-edit";2812    editBtn.type = "button";2813    editBtn.title = "Edit entry";2814    editBtn.textContent = "Edit";2815    editBtn.addEventListener("click", (e) => {2816      e.stopPropagation();2817      closeTray();2818      void renderInlineEdit(entry);2819    });2820    actions.appendChild(editBtn);28212822    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2823    // "···" toggle was zero-savings (the toggle button took the same space2824    // the "2FA" label needed) and made the code one extra click away.2825    if (entry.hasTotp) void openTOTPTray();28262827    platter.appendChild(actionsGroup);2828    container.appendChild(platter);2829  }28302831  /**2832   * Inline-popup edit mode. Swaps the silver platter for an editable form2833   * over the same shadow-DOM surface so the user never leaves the page.2834   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2835   * with the new fields. Cancel returns without writing.2836   */2837  async function renderInlineEdit(summary: SelectorEntry) {2838    currentMode = "edit";2839    container.innerHTML = "";2840    const wrap = document.createElement("div");2841    wrap.className = "create-form-wrap";28422843    const head = document.createElement("div");2844    head.className = "create-head";2845    const back = document.createElement("button");2846    back.className = "back-btn";2847    back.type = "button";2848    back.title = "Cancel";2849    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>`;2850    back.addEventListener("click", () => renderSilverPlatter(summary));2851    head.appendChild(back);2852    const headLbl = document.createElement("div");2853    headLbl.className = "create-label";2854    headLbl.textContent = "Edit entry";2855    head.appendChild(headLbl);2856    wrap.appendChild(head);28572858    const body = document.createElement("div");2859    body.className = "create-body";28602861    // Loading shimmer while we fetch the full entry2862    const loading = document.createElement("div");2863    loading.className = "empty-hint";2864    loading.textContent = "loading…";2865    body.appendChild(loading);2866    wrap.appendChild(body);2867    container.appendChild(wrap);28682869    const [res, idRes] = await Promise.all([2870      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2871      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2872      chrome.runtime.sendMessage({2873        type: "GET_ENTRY_FOR_EDIT",2874        payload: { id: summary.id },2875      }).catch(() => null),2876      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2877    ]);2878    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string; passwordHistory?: PasswordHistoryItem[] } } | null;2879    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];28802881    if (!entryRes || !entryRes.ok || !entryRes.data) {2882      loading.textContent = "couldn't load this entry. try again from the popup.";2883      return;2884    }2885    body.innerHTML = "";28862887    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2888      const group = document.createElement("div");2889      group.className = "f-group";2890      const lbl = document.createElement("div");2891      lbl.className = "f-label";2892      lbl.textContent = label;2893      const input = document.createElement("input");2894      input.className = "f-input";2895      input.type = type;2896      input.value = value;2897      input.autocomplete = "off";2898      group.append(lbl, input);2899      body.appendChild(group);2900      return { g: group, inp: input };2901    }29022903    const titleInput = field("title", entryRes.data.title ?? "").inp;2904    const urlInput = field("url", entryRes.data.url ?? "").inp;2905    urlInput.classList.add("url-f");2906    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2907    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2908    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2909    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2910    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");29112912    // Password row with reveal toggle + generator2913    const pwGroup = document.createElement("div");2914    pwGroup.className = "f-group";2915    const pwLbl = document.createElement("div");2916    pwLbl.className = "f-label";2917    pwLbl.textContent = "password";2918    const pwRow = document.createElement("div");2919    pwRow.className = "f-row";2920    const pwInput = document.createElement("input");2921    pwInput.className = "f-input";2922    pwInput.type = "password";2923    pwInput.value = entryRes.data.password ?? "";2924    pwInput.autocomplete = "new-password";2925    const revealBtn = document.createElement("button");2926    revealBtn.className = "gen-btn";2927    revealBtn.type = "button";2928    revealBtn.textContent = "show";2929    revealBtn.addEventListener("click", () => {2930      const reveal = pwInput.type === "password";2931      pwInput.type = reveal ? "text" : "password";2932      revealBtn.textContent = reveal ? "hide" : "show";2933    });2934    pwRow.append(pwInput, revealBtn);2935    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2936    editSmartGen.root.style.display = "none";2937    let editGenVisible = false;2938    const genToggleBtn = document.createElement("button");2939    genToggleBtn.className = "gen-toggle-link";2940    genToggleBtn.type = "button";2941    genToggleBtn.textContent = "⚙ generate";2942    genToggleBtn.addEventListener("click", () => {2943      editGenVisible = !editGenVisible;2944      pwRow.style.display = editGenVisible ? "none" : "";2945      editSmartGen.root.style.display = editGenVisible ? "" : "none";2946      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2947    });2948    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);29492950    // Past-password history: reveal, copy, or restore a previously-used value.2951    // Rows are masked by default; "use" loads the old value into the editor so2952    // the standard save flow records the swap (no separate write path). The2953    // toggle is always present (matching the main popup) so the affordance is2954    // discoverable — even before any history exists it explains how it fills.2955    const history = entryRes.data.passwordHistory ?? [];2956    {2957      const histList = document.createElement("div");2958      histList.className = "pw-history";2959      histList.style.display = "none";2960      let histVisible = false;29612962      const restLabel = history.length ? `↺ history (${history.length})` : "↺ history";2963      const histToggle = document.createElement("button");2964      histToggle.className = "gen-toggle-link";2965      histToggle.type = "button";2966      histToggle.textContent = restLabel;2967      histToggle.addEventListener("click", () => {2968        histVisible = !histVisible;2969        histList.style.display = histVisible ? "" : "none";2970        histToggle.textContent = histVisible ? "↺ hide history" : restLabel;2971      });29722973      if (history.length === 0) {2974        const empty = document.createElement("div");2975        empty.className = "pw-history-empty";2976        empty.textContent = "No earlier passwords yet. When you change this password, the old one is saved here so you can copy or restore it.";2977        histList.appendChild(empty);2978      }29792980      for (const item of history) {2981        const row = document.createElement("div");2982        row.className = "pw-history-row";2983        const main = document.createElement("div");2984        main.className = "pw-history-main";2985        const pwText = document.createElement("div");2986        pwText.className = "pw-history-pw";2987        let revealed = false;2988        const mask = "••••••••••••";2989        pwText.textContent = mask;2990        const age = document.createElement("div");2991        age.className = "pw-history-age";2992        age.textContent = timeSince(item.changedAt);2993        main.append(pwText, age);29942995        const acts = document.createElement("div");2996        acts.className = "pw-history-actions";2997        const revealBtn2 = document.createElement("button");2998        revealBtn2.className = "pw-history-btn";2999        revealBtn2.type = "button";3000        revealBtn2.textContent = "show";3001        revealBtn2.addEventListener("click", () => {3002          revealed = !revealed;3003          pwText.textContent = revealed ? item.password : mask;3004          revealBtn2.textContent = revealed ? "hide" : "show";3005        });3006        const copyBtn2 = document.createElement("button");3007        copyBtn2.className = "pw-history-btn";3008        copyBtn2.type = "button";3009        copyBtn2.textContent = "copy";3010        copyBtn2.addEventListener("click", async () => {3011          let alreadyWritten = false;3012          try {3013            await navigator.clipboard.writeText(item.password);3014            alreadyWritten = true;3015          } catch (err) {3016            console.warn("[Peach] clipboard write denied:", err);3017          }3018          await chrome.runtime.sendMessage({3019            type: "COPY",3020            payload: { text: item.password, label: "Password", alreadyWritten },3021          }).catch(() => null);3022          copyBtn2.textContent = "copied";3023          setTimeout(() => { if (copyBtn2.isConnected) copyBtn2.textContent = "copy"; }, 1200);3024        });3025        const useBtn = document.createElement("button");3026        useBtn.className = "pw-history-btn";3027        useBtn.type = "button";3028        useBtn.textContent = "use";3029        useBtn.title = "Use this password again";3030        useBtn.addEventListener("click", () => {3031          pwInput.value = item.password;3032          pwInput.type = "text";3033          revealBtn.textContent = "hide";3034          if (editGenVisible) {3035            editGenVisible = false;3036            pwRow.style.display = "";3037            editSmartGen.root.style.display = "none";3038            genToggleBtn.textContent = "⚙ generate";3039          }3040          histVisible = false;3041          histList.style.display = "none";3042          histToggle.textContent = `↺ history (${history.length})`;3043        });3044        acts.append(revealBtn2, copyBtn2, useBtn);3045        row.append(main, acts);3046        histList.appendChild(row);3047      }30483049      pwGroup.append(histToggle, histList);3050    }30513052    body.appendChild(pwGroup);30533054    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;30553056    // Notes3057    const notesGroup = document.createElement("div");3058    notesGroup.className = "f-group";3059    const notesLbl = document.createElement("div");3060    notesLbl.className = "f-label";3061    notesLbl.textContent = "notes";3062    const notesInput = document.createElement("textarea");3063    notesInput.className = "f-input";3064    notesInput.rows = 3;3065    notesInput.value = entryRes.data.notes ?? "";3066    notesInput.style.fontFamily = "Inter, sans-serif";3067    notesInput.style.resize = "vertical";3068    notesGroup.append(notesLbl, notesInput);3069    body.appendChild(notesGroup);30703071    // Save / Cancel row3072    const actionsRow = document.createElement("div");3073    actionsRow.className = "f-row";3074    const saveBtn = document.createElement("button");3075    saveBtn.className = "save-btn";3076    saveBtn.type = "button";3077    saveBtn.textContent = "Save changes";3078    saveBtn.style.flex = "1";3079    const cancelBtn = document.createElement("button");3080    cancelBtn.className = "gen-btn";3081    cancelBtn.type = "button";3082    cancelBtn.textContent = "cancel";3083    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));3084    actionsRow.append(saveBtn, cancelBtn);3085    body.appendChild(actionsRow);30863087    saveBtn.addEventListener("click", async () => {3088      saveBtn.disabled = true;3089      const originalLabel = saveBtn.textContent;3090      saveBtn.textContent = "Saving…";3091      const patch: Record<string, unknown> = {3092        title: titleInput.value.trim(),3093        url: urlInput.value.trim(),3094        username: usernameInput.value.trim(),3095        email: emailInput.value.trim() || undefined,3096        password: pwInput.value,3097        totp: totpInput.value.trim(),3098        notes: notesInput.value,3099      };3100      const updateRes = (await chrome.runtime.sendMessage({3101        type: "UPDATE_ENTRY",3102        payload: { id: summary.id, patch },3103      }).catch(() => null)) as { ok: boolean; error?: string } | null;3104      if (!updateRes?.ok) {3105        saveBtn.disabled = false;3106        saveBtn.textContent = originalLabel;3107        const err = document.createElement("div");3108        err.className = "empty-hint";3109        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";3110        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";3111        body.appendChild(err);3112        setTimeout(() => err.remove(), 3000);3113        return;3114      }3115      // Refresh the platter with updated summary fields3116      const refreshed: SelectorEntry = {3117        id: summary.id,3118        title: patch.title as string,3119        username: patch.username as string,3120        email: patch.email as string | undefined,3121        url: patch.url as string,3122        hasTotp: Boolean(patch.totp),3123        hasPasskey: summary.hasPasskey,3124      };3125      renderSilverPlatter(refreshed);3126    });31273128    queueMicrotask(() => titleInput.focus());3129  }31303131  function renderLocked() {3132    container.innerHTML = "";31333134    // Domain header (same as list view)3135    const domHdr = document.createElement("div");3136    domHdr.className = "domain-header";3137    const eyebrow = document.createElement("div");3138    eyebrow.className = "domain-eyebrow";3139    eyebrow.textContent = "vault locked";3140    const domName = document.createElement("div");3141    domName.className = "domain-name";3142    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3143    domHdr.append(eyebrow, domName);3144    container.appendChild(domHdr);31453146    const wrap = document.createElement("div");3147    wrap.className = "locked-wrap";31483149    // Icon + label row3150    const head = document.createElement("div"); head.className = "locked-head";3151    const icon = document.createElement("div"); icon.className = "locked-icon";3152    icon.innerHTML = keySvgStr();3153    const title = document.createElement("div"); title.className = "locked-title";3154    title.textContent = "unlock to autofill";3155    head.append(icon, title);31563157    // The master password is NEVER collected in page-hosted DOM. A malicious3158    // page can observe keystrokes on the shared DOM event stream (a capture-3159    // phase listener registered before Peach injects sees every key before any3160    // stopImmediatePropagation), which would leak the vault's root secret3161    // (audit HIGH). Instead, route unlocking to the trusted extension popup,3162    // where keystrokes are isolated from the page. After the user unlocks3163    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill3164    // automatically (see content/index.ts), so the flow resumes on its own.3165    const sub = document.createElement("div");3166    sub.className = "locked-sub";3167    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";31683169    const openBtn = document.createElement("button");3170    openBtn.className = "locked-btn";3171    openBtn.type = "button";3172    openBtn.textContent = "Open Peach to unlock";3173    openBtn.addEventListener("click", () => {3174      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});3175      openBtn.textContent = "opening Peach…";3176      openBtn.disabled = true;3177      // openPopup() can't always open programmatically (browser/version/gesture3178      // limits); reset so the user can retry or click the toolbar icon.3179      setTimeout(() => {3180        if (openBtn.isConnected) {3181          openBtn.textContent = "Open Peach to unlock";3182          openBtn.disabled = false;3183        }3184      }, 2500);3185    });31863187    wrap.append(head, sub, openBtn);3188    container.appendChild(wrap);3189  }31903191  function handleKeyDown(e: KeyboardEvent) {3192    if (options.locked) {3193      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3194      return;3195    }3196    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {3197      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3198      return;3199    }3200    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");3201    const count = allEntryEls.length;3202    const activeElement = shadow.activeElement ?? document.activeElement;3203    if (activeElement === searchInput) {3204      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }3205      if (count === 0) return;3206      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;3207    }3208    if (count === 0) return;3209    switch (e.key) {3210      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3211      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3212      case "Enter": {3213        if (focusedIndex >= 0) {3214          const el = allEntryEls[focusedIndex] as HTMLElement;3215          const id = el.dataset.id;3216          if (id) { onSelect(id); dismiss(); }3217          else if (el.classList.contains("is-new") || !id) {3218            // "New entry" row (last item, no data-id)3219            showCreateForm();3220          }3221        }3222        break;3223      }3224      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3225    }3226  }32273228  document.addEventListener("keydown", handleKeyDown);32293230  // Type-to-search from the silver platter. A printable single-character3231  // keystroke (no modifier) seeds the search query and switches into the3232  // list view, so the user can pivot to a different entry without first3233  // clicking the search icon. Capture phase so the anchor input does not3234  // receive the character before we hijack it.3235  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3236    if (currentMode !== "silver-platter") return;3237    if (e.ctrlKey || e.metaKey || e.altKey) return;3238    if (e.key.length !== 1) return;3239    e.preventDefault();3240    e.stopImmediatePropagation();3241    query = e.key;3242    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3243    void ensureSearchableLoaded(renderList);3244    renderList();3245  };3246  document.addEventListener("keydown", silverPlatterTypeHandler, true);3247  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));32483249  const identityHelperTypeHandler = (e: KeyboardEvent) => {3250    if (currentMode !== "identity-helper") return;3251    if (e.ctrlKey || e.metaKey || e.altKey) return;3252    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3253    if (active === searchInput) return;3254    if (3255      active instanceof HTMLInputElement ||3256      active instanceof HTMLTextAreaElement ||3257      (active instanceof HTMLElement && active.isContentEditable)3258    ) {3259      return;3260    }3261    if (e.key.length !== 1) return;3262    e.preventDefault();3263    e.stopImmediatePropagation();3264    query = e.key;3265    renderIdentityHelper();3266  };3267  document.addEventListener("keydown", identityHelperTypeHandler, true);3268  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));32693270  (modalAncestor ?? document.body).appendChild(host);32713272  // position:fixed normally resolves to the viewport, but an ancestor with3273  // transform / filter / backdrop-filter / perspective / contain / will-change3274  // establishes a containing block, so "fixed" then resolves to that ancestor's3275  // padding box instead. When the host is mounted inside such an ancestor (a3276  // modal) we subtract its border-box origin so the popup still lands at the3277  // field's true viewport position. At the document root there is no such3278  // ancestor and the offset is zero.3279  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3280    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3281    return (3282      has("transform") || has("perspective") || has("translate") ||3283      has("rotate") || has("scale") || has("filter") ||3284      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3285      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3286      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3287    );3288  }3289  function containingBlockOffset(): { dx: number; dy: number } {3290    let el: HTMLElement | null = host.parentElement;3291    while (el && el !== document.documentElement) {3292      const s = getComputedStyle(el);3293      if (establishesFixedContainingBlock(s)) {3294        const r = el.getBoundingClientRect();3295        return {3296          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3297          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3298        };3299      }3300      el = el.parentElement;3301    }3302    return { dx: 0, dy: 0 };3303  }33043305  function updatePosition() {3306    const r = anchorEl.getBoundingClientRect();3307    const { dx, dy } = containingBlockOffset();3308    host.style.top = `${r.bottom - dy + 5}px`;3309    host.style.left = `${r.left - dx}px`;3310    host.style.width = `${popupWidth}px`;3311  }3312  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3313  updatePosition();33143315  // observeAnchorPosition listens on window scroll, but a modal with its own3316  // internal scroll container doesn't move the window — track the modal's scroll3317  // too so the popup follows the field inside it.3318  if (modalAncestor) {3319    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3320    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3321  }33223323  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3324  // swap) removes the field without firing blur/click, so none of the normal3325  // dismiss triggers fire and the popup would otherwise linger over nothing.3326  const removalObserver = new MutationObserver(() => {3327    if (!document.contains(anchorEl)) dismiss();3328  });3329  removalObserver.observe(document.body, { childList: true, subtree: true });3330  cleanupHooks.push(() => removalObserver.disconnect());33313332  if (options.locked) {3333    renderLocked();3334  } else if (options.isSignup && options.savedIdentities) {3335    // State 10: identity helper — signup form detected, show derived3336    // identity list (emails then usernames) instead of vault entry list.3337    renderIdentityHelper();3338  } else if (entries.length === 1 && !options.isSignup) {3339    // Silver platter (State 1): single domain match → focused fill view.3340    // Multi-match goes through renderList instead.3341    renderSilverPlatter(entries[0]!);3342  } else {3343    renderList();3344  }33453346  let exitScheduled = false;3347  function dismiss(userAction = false) {3348    // Idempotent: dismiss() can be called from multiple paths (Escape,3349    // outside click, entry select, fill success, host page nav). The exit3350    // animation must only play once and host.remove() must run exactly once.3351    if (exitScheduled) return;3352    exitScheduled = true;3353    // Detach listeners synchronously so nothing can re-trigger during the3354    // 130ms exit window (a focusin firing here would race against the3355    // dismiss-lock work in Pass 2).3356    stopObserving();3357    document.removeEventListener("click", outsideClick, { capture: true });3358    document.removeEventListener("keydown", handleKeyDown);3359    for (const cleanup of cleanupHooks) {3360      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3361    }3362    if (userAction) options.onDismiss?.();3363    container.classList.add("is-exiting");3364    setTimeout(() => host.remove(), 130);3365  }33663367  function outsideClick(ev: MouseEvent) {3368    const path = ev.composedPath();3369    // Never dismiss when clicking the anchor field itself — that click is3370    // what triggered the selector to open, and the user may click the field3371    // again to re-focus it without intending to close the selector.3372    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3373  }3374  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3375  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33763377  return dismiss;3378}33793380export function showTOTPSelector(3381  anchorEl: HTMLInputElement,3382  entries: SelectorEntry[],3383  onFill: (id: string) => void,3384  options: { domain?: string; onDismiss?: () => void } = {}3385): () => void {3386  const host = document.createElement("div");3387  host.style.cssText = "position: absolute; z-index: 2147483647;";3388  host.style.setProperty("--peach-accent", accentHex);3389  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3390  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3391  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3392  const shadow = host.attachShadow({ mode: "closed" });33933394  const style = shadow.appendChild(document.createElement("style"));3395  style.textContent = SELECTOR_STYLES;33963397  const rect = anchorEl.getBoundingClientRect();3398  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3399  host.style.left = `${rect.left + window.scrollX}px`;3400  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3401  host.style.width = `${popupWidth}px`;34023403  const container = shadow.appendChild(document.createElement("div"));3404  container.className = "peach-inline-popup";3405  container.setAttribute("data-theme", popupTheme);34063407  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3408  const current = entries.filter((entry) => entry.hasTotp);3409  let focusedIndex = current.length === 1 ? 0 : -1;34103411  function updatePosition() {3412    const r = anchorEl.getBoundingClientRect();3413    host.style.top = `${r.bottom + window.scrollY + 5}px`;3414    host.style.left = `${r.left + window.scrollX}px`;3415    host.style.width = `${popupWidth}px`;3416  }34173418  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);34193420  function choose(entry: SelectorEntry) {3421    onFill(entry.id);3422    dismiss();3423  }34243425  function render() {3426    container.innerHTML = "";34273428    const domHdr = document.createElement("div");3429    domHdr.className = "domain-header";3430    const headText = document.createElement("div");3431    headText.className = "domain-header-text";3432    const eyebrow = document.createElement("div");3433    eyebrow.className = "domain-eyebrow";3434    eyebrow.textContent = "2FA code";3435    const domName = document.createElement("div");3436    domName.className = "domain-name";3437    domName.textContent = domain;3438    headText.append(eyebrow, domName);3439    domHdr.appendChild(headText);3440    container.appendChild(domHdr);34413442    if (current.length === 1) {3443      const entry = current[0]!;3444      const platter = document.createElement("div");3445      platter.className = "silver-platter";34463447      const title = document.createElement("div");3448      title.className = "sp-title";3449      title.textContent = entry.title;3450      platter.appendChild(title);34513452      const sub = document.createElement("div");3453      sub.className = "sp-username";3454      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3455      platter.appendChild(sub);34563457      const fill = document.createElement("button");3458      fill.className = "sp-fill-btn";3459      fill.type = "button";3460      fill.textContent = "Fill 2FA code";3461      fill.addEventListener("click", () => choose(entry));3462      platter.appendChild(fill);34633464      container.appendChild(platter);3465      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3466      return;3467    }34683469    const results = document.createElement("div");3470    results.className = "results";3471    container.appendChild(results);34723473    for (let i = 0; i < current.length; i++) {3474      const entry = current[i]!;3475      const row = document.createElement("div");3476      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3477      row.dataset.index = String(i);3478      row.setAttribute("tabindex", "-1");34793480      const icon = document.createElement("div");3481      icon.className = "entry-icon";3482      icon.innerHTML = keySvgStr();3483      row.appendChild(icon);3484      const info = document.createElement("div");3485      info.className = "entry-info";3486      const title = document.createElement("div");3487      title.className = "entry-title";3488      title.textContent = entry.title;3489      const sub = document.createElement("div");3490      sub.className = "entry-sub";3491      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3492      info.append(title, sub);3493      row.appendChild(info);34943495      const badge = document.createElement("span");3496      badge.className = "totp-badge";3497      badge.textContent = "Fill";3498      row.appendChild(badge);3499      row.addEventListener("click", () => choose(entry));3500      results.appendChild(row);3501    }3502  }35033504  function setFocused(index: number) {3505    focusedIndex = index;3506    container.querySelectorAll(".entry").forEach((el, i) => {3507      el.classList.toggle("focused", i === focusedIndex);3508      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3509    });3510  }35113512  function handleKeyDown(e: KeyboardEvent) {3513    if (e.key === "Escape" || e.key === "Tab") {3514      e.preventDefault();3515      dismiss(true);3516      return;3517    }3518    if (current.length === 0) return;3519    if (e.key === "Enter") {3520      e.preventDefault();3521      choose(current[Math.max(0, focusedIndex)]!);3522      return;3523    }3524    if (current.length === 1) return;3525    if (e.key === "ArrowDown") {3526      e.preventDefault();3527      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3528    } else if (e.key === "ArrowUp") {3529      e.preventDefault();3530      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3531    }3532  }35333534  let exitScheduled = false;3535  function dismiss(userAction = false) {3536    if (exitScheduled) return;3537    exitScheduled = true;3538    stopObserving();3539    document.removeEventListener("click", outsideClick, { capture: true });3540    document.removeEventListener("keydown", handleKeyDown);3541    if (userAction) options.onDismiss?.();3542    container.classList.add("is-exiting");3543    setTimeout(() => host.remove(), 130);3544  }35453546  function outsideClick(ev: MouseEvent) {3547    const path = ev.composedPath();3548    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3549  }35503551  document.addEventListener("keydown", handleKeyDown);3552  document.body.appendChild(host);3553  render();3554  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);35553556  return dismiss;3557}35583559export interface CardSelectorEntry {3560  id: string;3561  title: string;3562  cardholderName?: string;3563  last4?: string;3564  expMonth?: string;3565  expYear?: string;3566  network?: import("../shared/types").CardNetwork;3567}35683569interface CardSelectorOptions {3570  domain?: string;3571  /** Caller-provided fill — receives the full CardEntry payload from the SW. */3572  onFill: (entry: import("../shared/types").VaultEntry) => void;3573  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3574  onDismiss?: () => void;3575}35763577/**3578 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3579 * passkey create or get. Renders as a fixed-position floating popup (no3580 * field anchor needed — passkeys don't require a focused input). Uses the3581 * same theme tokens and entrance animation as all other inline popup states.3582 */3583export function showPasskeyProGate(): void {3584  const domain = location.hostname.replace(/^www\./, "");35853586  const host = document.createElement("div");3587  host.setAttribute("data-peach-passkey-gate", "1");3588  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3589  const shadow = host.attachShadow({ mode: "closed" });35903591  const style = document.createElement("style");3592  style.textContent = `3593    :host { all: initial; }3594    .gate-wrap {3595      position: fixed;3596      top: 50%;3597      left: 50%;3598      transform: translate(-50%, -50%);3599      width: 280px;3600      pointer-events: auto;3601      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3602    }3603    @keyframes g-in {3604      from { opacity:0; transform: translate(-50%,-52%); }3605      to   { opacity:1; transform: translate(-50%,-50%); }3606    }3607    .gate-wrap.is-exiting {3608      animation: g-out 130ms ease-in forwards;3609    }3610    @keyframes g-out {3611      to { opacity:0; transform: translate(-50%,-52%); }3612    }3613    .gate {3614      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3615      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3616      border-radius: 12px;3617      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3618      padding: 16px;3619      font-family: Inter, sans-serif;3620    }3621    .gate-header {3622      display: flex;3623      align-items: center;3624      gap: 7px;3625      margin-bottom: 12px;3626      padding-bottom: 10px;3627      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3628    }3629    .gate-domain {3630      font-size: 12px;3631      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3632      font-family: "IBM Plex Mono", monospace;3633      overflow: hidden;3634      text-overflow: ellipsis;3635      white-space: nowrap;3636    }3637    .gate-title {3638      font-size: 14px;3639      font-weight: 500;3640      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3641      margin-bottom: 6px;3642    }3643    .gate-subtitle {3644      font-size: 12px;3645      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3646      line-height: 1.5;3647      margin-bottom: 14px;3648    }3649    .gate-btn {3650      display: block;3651      width: 100%;3652      padding: 9px 0;3653      border-radius: 8px;3654      border: none;3655      cursor: pointer;3656      font-size: 13px;3657      font-family: Inter, sans-serif;3658      font-weight: 500;3659      transition: opacity 100ms;3660      margin-bottom: 7px;3661      text-align: center;3662    }3663    .gate-btn:last-child { margin-bottom: 0; }3664    .gate-btn--accent {3665      background: ${accentHex};3666      color: #fff;3667    }3668    .gate-btn--accent:hover { opacity: 0.88; }3669    .gate-btn--ghost {3670      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3671      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3672    }3673    .gate-btn--ghost:hover { opacity: 0.75; }3674    .backdrop {3675      position: fixed;3676      inset: 0;3677      pointer-events: auto;3678    }3679  `;3680  shadow.appendChild(style);36813682  const backdrop = document.createElement("div");3683  backdrop.className = "backdrop";3684  shadow.appendChild(backdrop);36853686  const wrap = document.createElement("div");3687  wrap.className = "gate-wrap";3688  shadow.appendChild(wrap);36893690  const gate = document.createElement("div");3691  gate.className = "gate";3692  wrap.appendChild(gate);36933694  // Header: peach icon + domain3695  const header = document.createElement("div");3696  header.className = "gate-header";3697  const icon = document.createElement("span");3698  icon.innerHTML = peachIconSvg();3699  const domainEl = document.createElement("span");3700  domainEl.className = "gate-domain";3701  domainEl.textContent = domain;3702  header.append(icon, domainEl);3703  gate.appendChild(header);37043705  const title = document.createElement("div");3706  title.className = "gate-title";3707  title.textContent = "Passkeys are part of Peach Pro.";3708  gate.appendChild(title);37093710  const subtitle = document.createElement("div");3711  subtitle.className = "gate-subtitle";3712  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3713  gate.appendChild(subtitle);37143715  const upgradeBtn = document.createElement("button");3716  upgradeBtn.className = "gate-btn gate-btn--accent";3717  upgradeBtn.type = "button";3718  upgradeBtn.textContent = "Upgrade to Pro";3719  gate.appendChild(upgradeBtn);37203721  const laterBtn = document.createElement("button");3722  laterBtn.className = "gate-btn gate-btn--ghost";3723  laterBtn.type = "button";3724  laterBtn.textContent = "Not right now";3725  gate.appendChild(laterBtn);37263727  function dismiss() {3728    wrap.classList.add("is-exiting");3729    setTimeout(() => host.remove(), 130);3730  }37313732  upgradeBtn.addEventListener("click", () => {3733    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3734    dismiss();3735  });3736  laterBtn.addEventListener("click", dismiss);3737  backdrop.addEventListener("click", dismiss);37383739  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3740    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3741  });37423743  document.body.appendChild(host);3744}37453746/**3747 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3748 * detector sees the page invoke navigator.credentials.create(); content/index.ts3749 * checks vault + decline state then calls this. "Save passkey to Peach"3750 * initiates the popup-context credential flow; "Not now" records a 30-day3751 * decline for the domain so we don't re-show on every page reload.3752 */3753export function showPasskeyRegistrationOffer(args: {3754  rpId: string;3755  rpName?: string;3756  userName?: string;3757  userDisplayName?: string;3758}): void {3759  const domain = location.hostname.replace(/^www\./, "");3760  const displayName = args.rpName || domain;37613762  const host = document.createElement("div");3763  host.setAttribute("data-peach-passkey-offer", "1");3764  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3765  const shadow = host.attachShadow({ mode: "closed" });37663767  const style = document.createElement("style");3768  style.textContent = `3769    :host { all: initial; }3770    .offer-wrap {3771      position: fixed;3772      top: 16px;3773      right: 16px;3774      width: 320px;3775      pointer-events: auto;3776      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3777    }3778    @keyframes o-in {3779      from { opacity: 0; transform: translateY(-6px); }3780      to   { opacity: 1; transform: translateY(0); }3781    }3782    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3783    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3784    .offer {3785      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3786      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3787      border-radius: 12px;3788      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3789      padding: 14px 14px 12px;3790      font-family: Inter, sans-serif;3791      position: relative;3792    }3793    .offer-close {3794      position: absolute;3795      top: 8px;3796      right: 8px;3797      width: 18px;3798      height: 18px;3799      border: none;3800      background: transparent;3801      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3802      cursor: pointer;3803      font-size: 14px;3804      line-height: 1;3805      padding: 0;3806    }3807    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3808    .offer-header {3809      display: flex;3810      align-items: center;3811      gap: 7px;3812      margin-bottom: 8px;3813      padding-bottom: 8px;3814      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3815    }3816    .offer-domain {3817      font-size: 12px;3818      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3819      font-family: "IBM Plex Mono", monospace;3820      overflow: hidden;3821      text-overflow: ellipsis;3822      white-space: nowrap;3823    }3824    .offer-title {3825      font-size: 13px;3826      font-weight: 500;3827      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3828      margin-bottom: 4px;3829    }3830    .offer-subtitle {3831      font-size: 11px;3832      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3833      line-height: 1.45;3834      margin-bottom: 12px;3835    }3836    .offer-btn {3837      display: block;3838      width: 100%;3839      padding: 8px 0;3840      border-radius: 7px;3841      border: none;3842      cursor: pointer;3843      font-size: 12px;3844      font-family: Inter, sans-serif;3845      font-weight: 500;3846      transition: opacity 100ms;3847      margin-bottom: 6px;3848      text-align: center;3849    }3850    .offer-btn:last-child { margin-bottom: 0; }3851    .offer-btn--accent { background: ${accentHex}; color: #fff; }3852    .offer-btn--accent:hover { opacity: 0.88; }3853    .offer-btn--ghost {3854      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3855      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3856    }3857    .offer-btn--ghost:hover { opacity: 0.75; }3858  `;3859  shadow.appendChild(style);38603861  const wrap = document.createElement("div");3862  wrap.className = "offer-wrap";3863  shadow.appendChild(wrap);38643865  const offer = document.createElement("div");3866  offer.className = "offer";3867  wrap.appendChild(offer);38683869  const closeBtn = document.createElement("button");3870  closeBtn.className = "offer-close";3871  closeBtn.type = "button";3872  closeBtn.setAttribute("aria-label", "Dismiss");3873  closeBtn.textContent = "✕";3874  offer.appendChild(closeBtn);38753876  const header = document.createElement("div");3877  header.className = "offer-header";3878  const icon = document.createElement("span");3879  icon.innerHTML = peachIconSvg();3880  const domainEl = document.createElement("span");3881  domainEl.className = "offer-domain";3882  domainEl.textContent = domain;3883  header.append(icon, domainEl);3884  offer.appendChild(header);38853886  const title = document.createElement("div");3887  title.className = "offer-title";3888  title.textContent = "This site supports passkeys.";3889  offer.appendChild(title);38903891  const subtitle = document.createElement("div");3892  subtitle.className = "offer-subtitle";3893  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3894  offer.appendChild(subtitle);38953896  const saveBtn = document.createElement("button");3897  saveBtn.className = "offer-btn offer-btn--accent";3898  saveBtn.type = "button";3899  saveBtn.textContent = "Save passkey to Peach";3900  offer.appendChild(saveBtn);39013902  const laterBtn = document.createElement("button");3903  laterBtn.className = "offer-btn offer-btn--ghost";3904  laterBtn.type = "button";3905  laterBtn.textContent = "Not now";3906  offer.appendChild(laterBtn);39073908  function dismiss(decline: boolean) {3909    if (decline) {3910      chrome.runtime.sendMessage({3911        type: "PASSKEY_OFFER_DECLINE",3912        payload: { domain },3913      }).catch(() => {});3914    }3915    wrap.classList.add("is-exiting");3916    setTimeout(() => host.remove(), 130);3917  }39183919  saveBtn.addEventListener("click", () => {3920    chrome.runtime.sendMessage({3921      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3922      payload: {3923        rpId: args.rpId,3924        rpName: args.rpName ?? displayName,3925        userName: args.userName ?? "user",3926        userDisplayName: args.userDisplayName,3927      },3928    }).catch(() => {});3929    dismiss(false);3930  });3931  laterBtn.addEventListener("click", () => dismiss(true));3932  closeBtn.addEventListener("click", () => dismiss(true));39333934  document.body.appendChild(host);3935}39363937/**3938 * State 11 — passkey available indicator. Shown when the user lands on a3939 * domain for which they already have a stored passkey. Tells them where to3940 * find it (the entry already shows in the vault list); the "Sign in with3941 * passkey" button opens the popup so they can use the platform authenticator3942 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3943 * the actual sign-in transparently, so this banner is informational only.3944 */3945export function showPasskeyAvailable(args: {3946  rpId: string;3947  userName: string;3948  fromBrowser?: "chrome" | "firefox";3949  currentBrowser?: "chrome" | "firefox" | "unknown";3950}): void {3951  const domain = location.hostname.replace(/^www\./, "");3952  const crossBrowser =3953    args.fromBrowser &&3954    args.currentBrowser &&3955    args.currentBrowser !== "unknown" &&3956    args.fromBrowser !== args.currentBrowser;39573958  const host = document.createElement("div");3959  host.setAttribute("data-peach-passkey-available", "1");3960  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3961  const shadow = host.attachShadow({ mode: "closed" });39623963  const style = document.createElement("style");3964  style.textContent = `3965    :host { all: initial; }3966    .avail-wrap {3967      position: fixed;3968      top: 16px;3969      right: 16px;3970      width: 320px;3971      pointer-events: auto;3972      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3973    }3974    @keyframes a-in {3975      from { opacity: 0; transform: translateY(-6px); }3976      to   { opacity: 1; transform: translateY(0); }3977    }3978    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3979    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3980    .avail {3981      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3982      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3983      border-radius: 12px;3984      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3985      padding: 14px 14px 12px;3986      font-family: Inter, sans-serif;3987      position: relative;3988    }3989    .avail-close {3990      position: absolute;3991      top: 8px;3992      right: 8px;3993      width: 18px;3994      height: 18px;3995      border: none;3996      background: transparent;3997      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3998      cursor: pointer;3999      font-size: 14px;4000      line-height: 1;4001      padding: 0;4002    }4003    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }4004    .avail-header {4005      display: flex;4006      align-items: center;4007      gap: 7px;4008      margin-bottom: 8px;4009      padding-bottom: 8px;4010      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};4011    }4012    .avail-domain {4013      font-size: 12px;4014      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};4015      font-family: "IBM Plex Mono", monospace;4016    }4017    .avail-label {4018      font-size: 9px;4019      letter-spacing: 0.16em;4020      text-transform: uppercase;4021      color: ${accentHex};4022      margin-bottom: 4px;4023    }4024    .avail-user {4025      font-size: 13px;4026      font-weight: 500;4027      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};4028      margin-bottom: 12px;4029      overflow: hidden;4030      text-overflow: ellipsis;4031      white-space: nowrap;4032    }4033    .avail-cross {4034      font-size: 11px;4035      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};4036      line-height: 1.45;4037      margin-bottom: 12px;4038      padding: 8px;4039      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};4040      border-radius: 6px;4041    }4042    .avail-btn {4043      display: block;4044      width: 100%;4045      padding: 8px 0;4046      border-radius: 7px;4047      border: none;4048      cursor: pointer;4049      font-size: 12px;4050      font-family: Inter, sans-serif;4051      font-weight: 500;4052      transition: opacity 100ms;4053      margin-bottom: 6px;4054      text-align: center;4055    }4056    .avail-btn:last-child { margin-bottom: 0; }4057    .avail-btn--accent { background: ${accentHex}; color: #fff; }4058    .avail-btn--accent:hover { opacity: 0.88; }4059    .avail-btn--ghost {4060      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};4061      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};4062    }4063    .avail-btn--ghost:hover { opacity: 0.75; }4064  `;4065  shadow.appendChild(style);40664067  const wrap = document.createElement("div");4068  wrap.className = "avail-wrap";4069  shadow.appendChild(wrap);40704071  const avail = document.createElement("div");4072  avail.className = "avail";4073  wrap.appendChild(avail);40744075  const closeBtn = document.createElement("button");4076  closeBtn.className = "avail-close";4077  closeBtn.type = "button";4078  closeBtn.setAttribute("aria-label", "Dismiss");4079  closeBtn.textContent = "✕";4080  avail.appendChild(closeBtn);40814082  const header = document.createElement("div");4083  header.className = "avail-header";4084  const icon = document.createElement("span");4085  icon.innerHTML = peachIconSvg();4086  const domainEl = document.createElement("span");4087  domainEl.className = "avail-domain";4088  domainEl.textContent = domain;4089  header.append(icon, domainEl);4090  avail.appendChild(header);40914092  const label = document.createElement("div");4093  label.className = "avail-label";4094  label.textContent = "PASSKEY";4095  avail.appendChild(label);40964097  const user = document.createElement("div");4098  user.className = "avail-user";4099  user.textContent = args.userName;4100  avail.appendChild(user);41014102  if (crossBrowser) {4103    const cross = document.createElement("div");4104    cross.className = "avail-cross";4105    cross.textContent =4106      args.fromBrowser === "chrome"4107        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."4108        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";4109    avail.appendChild(cross);4110  }41114112  const signInBtn = document.createElement("button");4113  signInBtn.className = "avail-btn avail-btn--accent";4114  signInBtn.type = "button";4115  signInBtn.textContent = "Sign in with passkey";4116  avail.appendChild(signInBtn);41174118  const passwordBtn = document.createElement("button");4119  passwordBtn.className = "avail-btn avail-btn--ghost";4120  passwordBtn.type = "button";4121  passwordBtn.textContent = "Use password instead";4122  avail.appendChild(passwordBtn);41234124  function dismiss() {4125    wrap.classList.add("is-exiting");4126    setTimeout(() => host.remove(), 130);4127  }41284129  signInBtn.addEventListener("click", () => {4130    // On Chrome: the user clicking the page's own Sign-in button is what4131    //   triggers webAuthenticationProxy → existing background flow handles it.4132    //   Our button just dismisses since the page itself drives auth.4133    // On Firefox: cross-browser passkeys can't be used, so we just dismiss4134    //   and surface the entry for manual reference (popup view).4135    dismiss();4136    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});4137  });4138  passwordBtn.addEventListener("click", dismiss);4139  closeBtn.addEventListener("click", dismiss);41404141  document.body.appendChild(host);4142}41434144/**4145 * State 7 — card silver platter. Single-card focused fill view rendered4146 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the4147 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes4148 * so card and login flows render identically. Multi-card list view is a4149 * follow-up; today this picks the first card.4150 */4151export function showCardSelector(4152  anchorEl: HTMLInputElement,4153  cards: CardSelectorEntry[],4154  options: CardSelectorOptions4155): () => void {4156  if (cards.length === 0) return () => {};4157  const card = cards[0]!;41584159  const host = document.createElement("div");4160  host.style.cssText = "position: absolute; z-index: 2147483647;";4161  host.style.setProperty("--peach-accent", accentHex);4162  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));4163  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));4164  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));4165  const shadow = host.attachShadow({ mode: "closed" });41664167  const style = shadow.appendChild(document.createElement("style"));4168  style.textContent = SELECTOR_STYLES;41694170  const rect = anchorEl.getBoundingClientRect();4171  host.style.top = `${rect.bottom + window.scrollY + 5}px`;4172  host.style.left = `${rect.left + window.scrollX}px`;4173  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;41744175  const container = shadow.appendChild(document.createElement("div"));4176  container.className = "peach-inline-popup";4177  container.setAttribute("data-theme", popupTheme);41784179  // Domain header — eyebrow communicates the card context, not the site4180  const domHdr = document.createElement("div");4181  domHdr.className = "domain-header";4182  const eyebrow = document.createElement("div");4183  eyebrow.className = "domain-eyebrow";4184  eyebrow.textContent = "Pay with Peach";4185  const domName = document.createElement("div");4186  domName.className = "domain-name";4187  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");4188  domHdr.append(eyebrow, domName);4189  container.appendChild(domHdr);41904191  const platter = document.createElement("div");4192  platter.className = "card-platter";41934194  if (card.network && card.network !== "unknown") {4195    const net = document.createElement("div");4196    net.className = "cp-network";4197    net.textContent = card.network;4198    platter.appendChild(net);4199  }42004201  const nick = document.createElement("div");4202  nick.className = "cp-nickname";4203  nick.textContent = card.title;4204  platter.appendChild(nick);42054206  if (card.last4) {4207    const l4 = document.createElement("div");4208    l4.className = "cp-last4";4209    l4.textContent = `•••• ${card.last4}`;4210    platter.appendChild(l4);4211  }42124213  const meta = document.createElement("div");4214  meta.className = "cp-meta";4215  if (card.cardholderName) {4216    const name = document.createElement("span");4217    name.textContent = card.cardholderName;4218    meta.appendChild(name);4219  }4220  if (card.expMonth && card.expYear) {4221    if (card.cardholderName) {4222      const sep = document.createElement("span");4223      sep.className = "cp-meta-sep";4224      sep.textContent = "·";4225      meta.appendChild(sep);4226    }4227    const exp = document.createElement("span");4228    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4229    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4230    meta.appendChild(exp);4231  }4232  if (meta.childElementCount > 0) platter.appendChild(meta);42334234  const fillWrap = document.createElement("div");4235  fillWrap.className = "cp-fill-wrap";4236  const fillBtn = document.createElement("button");4237  fillBtn.className = "sp-fill-btn";4238  fillBtn.type = "button";4239  fillBtn.textContent = "Fill card details";4240  fillBtn.addEventListener("click", async () => {4241    if (fillBtn.disabled) return;4242    fillBtn.disabled = true;4243    fillBtn.classList.add("filled");4244    fillBtn.innerHTML = checkSvgStr();4245    const resp = await chrome.runtime.sendMessage({4246      type: "GET_ENTRY_FOR_FILL",4247      // MV-1: explicit user click to fill this card's details.4248      payload: { id: card.id, explicitSummon: true },4249    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4250    if (resp?.ok && resp.data) options.onFill(resp.data);4251    setTimeout(() => dismiss(), 400);4252  });4253  fillWrap.appendChild(fillBtn);4254  platter.appendChild(fillWrap);42554256  // Secondary actions — copy number, copy CVC, dismiss4257  const actions = document.createElement("div");4258  actions.className = "sp-actions";42594260  function flashBtn(b: HTMLButtonElement) {4261    b.classList.add("flashed");4262    setTimeout(() => b.classList.remove("flashed"), 700);4263  }42644265  // M3/QUA-005: clipboard + background COPY both failed — show user.4266  function flashCopyError(b: HTMLButtonElement) {4267    const original = b.textContent ?? "";4268    b.textContent = "Blocked";4269    b.classList.add("flashed");4270    setTimeout(() => {4271      b.classList.remove("flashed");4272      if (b.isConnected) b.textContent = original;4273    }, 1200);4274  }42754276  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4277    const resp = await chrome.runtime.sendMessage({4278      type: "GET_ENTRY_FOR_FILL",4279      // MV-1: explicit user action on a card the user opened in Peach's UI.4280      payload: { id: card.id, explicitSummon: true },4281    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4282    return resp?.ok && resp.data ? resp.data : null;4283  }42844285  const copyNum = document.createElement("button");4286  copyNum.className = "sp-action-btn";4287  copyNum.type = "button";4288  copyNum.title = "Copy card number";4289  copyNum.textContent = "Copy number";4290  copyNum.addEventListener("click", async (e) => {4291    e.stopPropagation();4292    const full = await fetchFullCard();4293    if (!full?.cardNumber) return;4294    let alreadyWritten = false;4295    try {4296      await navigator.clipboard.writeText(full.cardNumber);4297      alreadyWritten = true;4298    } catch (err) {4299      console.warn("[Peach] clipboard write denied:", err);4300    }4301    const resp = await chrome.runtime.sendMessage({4302      type: "COPY",4303      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4304    }).catch(() => null) as { ok?: boolean } | null;4305    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4306    else flashCopyError(copyNum);4307  });4308  actions.appendChild(copyNum);43094310  const copyCvc = document.createElement("button");4311  copyCvc.className = "sp-action-btn";4312  copyCvc.type = "button";4313  copyCvc.title = "Copy CVC";4314  copyCvc.textContent = "Copy CVC";4315  copyCvc.addEventListener("click", async (e) => {4316    e.stopPropagation();4317    const full = await fetchFullCard();4318    if (!full?.cvc) return;4319    let alreadyWritten = false;4320    try {4321      await navigator.clipboard.writeText(full.cvc);4322      alreadyWritten = true;4323    } catch (err) {4324      console.warn("[Peach] clipboard write denied:", err);4325    }4326    const resp = await chrome.runtime.sendMessage({4327      type: "COPY",4328      payload: { text: full.cvc, label: "CVC", alreadyWritten },4329    }).catch(() => null) as { ok?: boolean } | null;4330    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4331    else flashCopyError(copyCvc);4332  });4333  actions.appendChild(copyCvc);43344335  const closeBtn = document.createElement("button");4336  closeBtn.className = "sp-action-btn";4337  closeBtn.type = "button";4338  closeBtn.title = "Dismiss";4339  closeBtn.textContent = "✕";4340  closeBtn.addEventListener("click", (e) => {4341    e.stopPropagation();4342    dismiss(true);4343  });4344  actions.appendChild(closeBtn);43454346  platter.appendChild(actions);4347  container.appendChild(platter);43484349  document.body.appendChild(host);4350  function updatePosition() {4351    const r = anchorEl.getBoundingClientRect();4352    host.style.top = `${r.bottom + window.scrollY + 5}px`;4353    host.style.left = `${r.left + window.scrollX}px`;4354  }4355  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);43564357  function onKeyDown(e: KeyboardEvent) {4358    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4359  }4360  document.addEventListener("keydown", onKeyDown);43614362  let exitScheduled = false;4363  function dismiss(userAction = false) {4364    if (exitScheduled) return;4365    exitScheduled = true;4366    stopObserving();4367    document.removeEventListener("click", outsideClick, { capture: true });4368    document.removeEventListener("keydown", onKeyDown);4369    if (userAction) options.onDismiss?.();4370    container.classList.add("is-exiting");4371    setTimeout(() => host.remove(), 130);4372  }43734374  function outsideClick(ev: MouseEvent) {4375    const path = ev.composedPath();4376    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4377  }4378  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);43794380  return dismiss;4381}