inject.ts

171.5 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import {14  DEFAULT_PASSPHRASE_WORDS,15  generatePassphrase,16  generatePassword,17  MAX_PASSPHRASE_WORDS,18  MIN_PASSPHRASE_WORDS,19  type PassphraseSeparator,20} from "../shared/generate";21import { detectPasswordPolicy } from "./policy";22import {23  filterSavedIdentities,24  identityFilterLabel,25  resolveCustomIdentityKind,26  type IdentityFilterMode,27  type IdentityKind,28} from "./identity-helper";2930let accentHex = "#E8956D";31let popupTheme: "dark" | "light" = "dark";32chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {33  const data = resp?.data;34  const name = data?.accentColor ?? "peach";35  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";36  popupTheme = data?.theme === "light" ? "light" : "dark";37});3839// 8-digit hex alpha helpers for the accent-derived shadow tokens.40// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing41// two hex digits as the alpha channel.42function withAlpha(hex: string, alpha: string): string {43  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS44  // always exposes 6-digit hex, so this is a guard against future changes45  // shipping shorthand colors that would silently break the var injection.46  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;47}4849export interface SelectorEntry {50  id: string;51  title: string;52  username?: string;53  email?: string;54  url?: string;55  hasTotp?: boolean;56  /** True when the entry also has a passkey credential attached. */57  hasPasskey?: boolean;58}5960interface SelectorOptions {61  domain?: string;62  /** Browser-issued one-shot authorization for a user-summoned cross-origin selection. */63  capability?: string;64  searchableEntries?: SelectorEntry[];65  /**66   * MV-2: lazy loader for the vault-wide searchable list. Invoked only on an67   * explicit user search gesture, never on passive popup open, so the full68   * account inventory never ships into the page world unless the user asks.69   * Result is cached for the popup's lifetime.70   */71  loadSearchableEntries?: () => Promise<SelectorEntry[]>;72  /** True when shown on a signup form — changes header label and entry-click behaviour */73  isSignup?: boolean;74  /**75   * Identity kind the current signup field is expecting. Used to avoid76   * assuming email when the user is actually filling a username.77   */78  identityKind?: IdentityKind;79  /**80   * Derived identity list (emails then usernames) for signup mode (State 10).81   * When present, renderIdentityHelper() is used instead of renderList().82   */83  savedIdentities?: SavedIdentity[];84  /**85   * Called after the user picks a saved identity (signup mode only) or86   * after successfully saving a new entry on a signup form.87   * Lets the caller fill the visible username + password fields.88   */89  onFillFields?: (username: string, password: string, email?: string) => void;90  /**91   * True when the form has both a distinct username field AND a distinct email92   * field (e.g. Name / Username / Email / Password signup forms). Enables the93   * two-step identity wizard: first pick the field type the user clicked on,94   * then pick the other, then generate a password.95   */96  hasEmailField?: boolean;97  /**98   * When true, show an inline unlock form instead of the entries list.99   * Used when the vault is locked so the user can unlock without opening100   * the popup.101   */102  locked?: boolean;103  /**104   * Called after a successful inline unlock — the caller should re-query105   * entries and re-open the selector with real data.106   */107  onUnlocked?: () => void;108  /**109   * Called when the user explicitly dismisses the selector (Escape, Tab, or110   * click outside) — NOT when an entry is selected or on auto-close.111   * Used by the caller to suppress spurious reopens on the same field.112   */113  onDismiss?: () => void;114}115116function getDomainFromUrl(url: string): string {117  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }118}119120function keySvgStr(): string {121  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>`;122}123124function plusSvgStr(): string {125  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>`;126}127128function searchSvgStr(): string {129  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>`;130}131132function backSvgStr(): string {133  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>`;134}135136function peachIconSvg(): string {137  // Peach body stays brand-peach regardless of `accentHex` — a sage or138  // sky accent must not turn the autofill icon green or blue. Accent139  // color still tints surrounding glow/hover halos below.140  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>`;141}142143function checkSvgStr(): string {144  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>`;145}146147function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {148  const { hostname, origin } = location;149  const parts = hostname.split(".");150  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",151    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",152    "oidc", "federation", "saml", "cas", "ldap"];153  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());154  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;155  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);156  return { origin, title, loginSubdomain };157}158159/**160 * Shows a bottom-of-page toast after filling credentials when the entry has161 * never matched the current site — offering to add the current origin to the162 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.163 */164export function showRememberSiteToast(165  pageDomain: string,166  entryId: string,167): void {168  const host = document.createElement("div");169  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";170  host.style.setProperty("--peach-accent", accentHex);171  const shadow = host.attachShadow({ mode: "closed" });172173  const style = document.createElement("style");174  style.textContent = `175    .bar {176      display:flex;align-items:center;gap:10px;padding:10px 14px;177      background:#131109;border:1px solid rgba(240,232,216,0.09);178      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);179      font-family:Inter,sans-serif;white-space:nowrap;180      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;181    }182    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }183    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }184    .yes {185      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;186      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;187    }188    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }189    .no {190      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;191      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;192    }193  `;194  shadow.appendChild(style);195196  const bar = document.createElement("div"); bar.className = "bar";197  const txt = document.createElement("span"); txt.className = "txt";198  txt.textContent = `Remember ${pageDomain} for this entry?`;199  const yesBtn = document.createElement("button"); yesBtn.className = "yes";200  yesBtn.textContent = "Remember";201  yesBtn.addEventListener("click", async () => {202    // The write itself is popup-confirmed: growing an entry's domain set is203    // the one autofill decision a page must not make for itself, because the204    // domain set is what gates future fills (PB-26-106).205    await chrome.runtime.sendMessage({206      type: "REQUEST_REMEMBER_SITE",207      payload: { id: entryId, url: location.origin },208    });209    host.remove();210  });211  const noBtn = document.createElement("button"); noBtn.className = "no";212  noBtn.textContent = "Not now";213  noBtn.addEventListener("click", () => host.remove());214  bar.append(txt, yesBtn, noBtn);215  shadow.appendChild(bar);216  document.body.appendChild(host);217  setTimeout(() => host.remove(), 9000);218}219220// Module handle so a second auto-copy resets the dismiss timer rather than221// letting the first toast's teardown race the replacement.222let totpToastDismissTimer: ReturnType<typeof setTimeout> | null = null;223224/**225 * Shows a brief top-right toast when Peach automatically copies a TOTP code,226 * telling the user how long until the clipboard self-clears. Auto-dismisses227 * after 3s; a second call while visible replaces the toast and resets the timer.228 * Rendered in the light DOM (not a closed shadow) so the copy is announced to229 * assistive tech via aria-live — the code itself is never placed in the DOM.230 */231export function showTotpCopyToast(secondsUntilClear: number): void {232  document.getElementById("peach-totp-toast")?.remove();233  if (totpToastDismissTimer) {234    clearTimeout(totpToastDismissTimer);235    totpToastDismissTimer = null;236  }237238  const toast = document.createElement("div");239  toast.id = "peach-totp-toast";240  toast.className = "peach-totp-toast";241  toast.setAttribute("data-peach-toast", "totp-copy");242  toast.setAttribute("aria-live", "polite");243244  // Inline styles — matches the passkey toast family (warm, minimal, top right).245  Object.assign(toast.style, {246    position: "fixed",247    top: "16px",248    right: "16px",249    zIndex: "2147483647",250    padding: "10px 14px",251    borderRadius: "8px",252    background: "rgba(30, 20, 10, 0.92)",253    border: "1px solid rgba(210, 140, 60, 0.3)",254    color: "#e8d5b0",255    fontFamily: '"IBM Plex Mono", monospace',256    fontSize: "11px",257    lineHeight: "1.5",258    boxShadow: "0 4px 24px rgba(0,0,0,0.4)",259    pointerEvents: "none",260  });261262  // secondsUntilClear is a typed number — safe to interpolate; no page-derived263  // string ever reaches this markup.264  toast.innerHTML = `265    <div style="font-style: italic; font-family: 'Cormorant Garamond', serif; font-size: 13px; margin-bottom: 2px;">266      2FA code copied267    </div>268    <div style="opacity: 0.6; font-size: 10px;">269      clears in ${secondsUntilClear}s270    </div>271  `;272273  document.body.appendChild(toast);274275  totpToastDismissTimer = setTimeout(() => {276    totpToastDismissTimer = null;277    toast.style.transition = "opacity 0.3s ease";278    toast.style.opacity = "0";279    setTimeout(() => toast.remove(), 300);280  }, 3000);281}282283interface SmartGenerator {284  root: HTMLElement;285  getPassword: () => string;286  /** Copy the current password to the clipboard with the standard pulse UX. */287  copy: () => Promise<void>;288}289290interface SmartGeneratorOptions {291  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */292  policy: PasswordPolicy;293  /**294   * Seed value: used as the displayed password without regenerating, e.g. the295   * password the user already typed into the page. The generator still296   * regenerates the moment any control changes.297   */298  initialPassword?: string;299  /** Fires every time the password regenerates (initial + on changes). */300  onChange?: (pw: string) => void;301}302303/**304 * Build the inline-popup smart-password generator. Mirrors the main popup's305 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset306 * pills + a policy hint that names the constraints Peach detected on the307 * page. Writing this in pure DOM rather than reusing the Solid component308 * keeps the content-script bundle small.309 */310export function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {311  const policy = opts.policy ?? {};312  let mode: "password" | "passphrase" = "password";313  let wordCount = DEFAULT_PASSPHRASE_WORDS;314  let separator: PassphraseSeparator = "-";315316  // Start at site max (strongest password the site accepts), fall back to 64317  let length = policy.maxLength ?? 64;318  if (policy.minLength) length = Math.max(length, policy.minLength);319  if (length < 8) length = 8;320  if (length > 256) length = 256;321322  let upper = true;323  let lower = true;324  let numbers = true;325  let symbols = !policy.forbidsSymbols;326  if (policy.requiresSymbols) symbols = true;327  const forbiddenChars = policy.forbiddenChars ?? "";328329  let password = "";330331  const root = document.createElement("div");332  root.className = "pwgen-block";333334  const modePills = root.appendChild(document.createElement("div"));335  modePills.className = "pwgen-pills";336  modePills.setAttribute("aria-label", "Generator type");337  const passwordModeBtn = modePills.appendChild(document.createElement("button"));338  passwordModeBtn.type = "button";339  passwordModeBtn.className = "pwgen-pill is-on";340  passwordModeBtn.textContent = "password";341  passwordModeBtn.setAttribute("aria-pressed", "true");342  const passphraseModeBtn = modePills.appendChild(document.createElement("button"));343  passphraseModeBtn.type = "button";344  passphraseModeBtn.className = "pwgen-pill";345  passphraseModeBtn.textContent = "passphrase";346  passphraseModeBtn.setAttribute("aria-pressed", "false");347348  const displayRow = root.appendChild(document.createElement("div"));349  displayRow.className = "pwgen-display-row";350  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;351  output.type = "text";352  output.className = "pwgen-output";353  output.setAttribute("autocomplete", "off");354  output.setAttribute("spellcheck", "false");355  output.setAttribute("autocorrect", "off");356  output.setAttribute("autocapitalize", "off");357358  const regenBtn = displayRow.appendChild(document.createElement("button"));359  regenBtn.className = "pwgen-icon-btn";360  regenBtn.type = "button";361  regenBtn.setAttribute("aria-label", "Regenerate password");362  regenBtn.title = "Regenerate";363  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>`;364365  const copyBtn = displayRow.appendChild(document.createElement("button"));366  copyBtn.className = "pwgen-icon-btn";367  copyBtn.type = "button";368  copyBtn.setAttribute("aria-label", "Copy password");369  copyBtn.title = "Copy";370  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>`;371372  const controls = root.appendChild(document.createElement("div"));373  controls.className = "pwgen-controls-row";374  const slider = controls.appendChild(document.createElement("input"));375  slider.type = "range";376  slider.className = "pwgen-slider";377  slider.min = "8";378  slider.max = "256";379  slider.value = String(length);380  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));381  if (policy.maxLength) slider.max = String(Math.min(256, policy.maxLength));382  slider.setAttribute("aria-label", "Password length");383  const amountLabel = controls.appendChild(document.createElement("span"));384  amountLabel.className = "pwgen-amount-label";385  amountLabel.textContent = "characters";386  const lenNum = controls.appendChild(document.createElement("span"));387  lenNum.className = "pwgen-len-num pwgen-len-num--edit";388  lenNum.textContent = String(length);389  lenNum.addEventListener("click", () => {390    const li = document.createElement("input");391    li.type = "text"; li.inputMode = "numeric";392    li.className = "pwgen-len-input"; li.value = String(length);393    lenNum.replaceWith(li);394    requestAnimationFrame(() => li.select());395    function commitLenEdit() {396      const n = parseInt(li.value, 10);397      if (!Number.isNaN(n)) {398        const clamped = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));399        if (mode === "passphrase") wordCount = clamped;400        else length = clamped;401        slider.value = String(mode === "passphrase" ? wordCount : length);402        regenerate();403      }404      lenNum.textContent = String(mode === "passphrase" ? wordCount : length);405      li.replaceWith(lenNum);406    }407    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });408    li.addEventListener("blur", commitLenEdit);409  });410411  const pills = root.appendChild(document.createElement("div"));412  pills.className = "pwgen-pills";413414  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {415    const b = document.createElement("button");416    b.type = "button";417    b.className = `pwgen-pill ${on ? "is-on" : ""}`;418    b.textContent = label;419    b.addEventListener("click", () => {420      const next = !b.classList.contains("is-on");421      b.classList.toggle("is-on", next);422      onToggle(next);423    });424    return b;425  }426  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));427  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));428  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));429  pills.appendChild(makePill("!@#", symbols, (next) => {430    // The site forbids symbols — UI lets the user override but still warn.431    symbols = next;432    regenerate();433  }));434435  const separatorPills = root.appendChild(document.createElement("div"));436  separatorPills.className = "pwgen-pills";437  separatorPills.hidden = true;438  for (const value of ["-", " ", ".", "_"] as PassphraseSeparator[]) {439    const button = separatorPills.appendChild(document.createElement("button"));440    button.type = "button";441    button.className = `pwgen-pill ${value === separator ? "is-on" : ""}`;442    button.textContent = value === " " ? "space" : value;443    button.setAttribute("aria-label", value === " " ? "Space separator" : `${value} separator`);444    button.setAttribute("aria-pressed", String(value === separator));445    button.addEventListener("click", () => {446      separator = value;447      for (const sibling of separatorPills.querySelectorAll("button")) {448        const selected = sibling === button;449        sibling.classList.toggle("is-on", selected);450        sibling.setAttribute("aria-pressed", String(selected));451      }452      regenerate();453    });454  }455456  // Policy hint — surfaces what Peach read off the site so the user knows the457  // generator is already tuned to it. Only shows when something interesting458  // was detected.459  const hintParts: string[] = [];460  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);461  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);462  if (policy.requiresSymbols) hintParts.push("requires symbols");463  if (policy.forbidsSymbols) hintParts.push("no symbols");464  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);465  let policyHint: HTMLDivElement | null = null;466  if (hintParts.length > 0) {467    const hint = root.appendChild(document.createElement("div"));468    policyHint = hint;469    hint.className = "pwgen-policy-hint";470    const accent = document.createElement("span");471    accent.className = "pwgen-hint-accent";472    accent.textContent = "site rules · ";473    const text = document.createTextNode(hintParts.join(" · "));474    hint.appendChild(accent);475    hint.appendChild(text);476  }477478  function regenerate() {479    // Falls back gracefully when the user toggles every charset off — the480    // shared generator forces lowercase in that case rather than throwing.481    password = mode === "passphrase"482      ? generatePassphrase({ wordCount, separator })483      : generatePassword({484          length,485          includeUppercase: upper,486          includeLowercase: lower,487          includeNumbers: numbers,488          includeSymbols: symbols,489          forbiddenChars,490        });491    output.value = password;492    opts.onChange?.(password);493  }494495  output.addEventListener("input", () => {496    password = output.value;497    if (mode === "password") {498      length = password.length;499      slider.value = String(Math.max(8, Math.min(256, length)));500      lenNum.textContent = String(length);501    }502    opts.onChange?.(password);503  });504505  slider.addEventListener("input", () => {506    if (mode === "passphrase") wordCount = parseInt(slider.value, 10);507    else length = parseInt(slider.value, 10);508    lenNum.textContent = String(mode === "passphrase" ? wordCount : length);509    regenerate();510  });511  regenBtn.addEventListener("click", regenerate);512513  function selectMode(nextMode: "password" | "passphrase") {514    mode = nextMode;515    const isPassphrase = mode === "passphrase";516    passwordModeBtn.classList.toggle("is-on", !isPassphrase);517    passwordModeBtn.setAttribute("aria-pressed", String(!isPassphrase));518    passphraseModeBtn.classList.toggle("is-on", isPassphrase);519    passphraseModeBtn.setAttribute("aria-pressed", String(isPassphrase));520    pills.hidden = isPassphrase;521    separatorPills.hidden = !isPassphrase;522    if (policyHint) policyHint.hidden = isPassphrase;523    slider.min = String(isPassphrase ? MIN_PASSPHRASE_WORDS : Math.max(8, policy.minLength ?? 8));524    slider.max = String(isPassphrase ? MAX_PASSPHRASE_WORDS : Math.min(256, policy.maxLength ?? 256));525    slider.value = String(isPassphrase ? wordCount : length);526    slider.setAttribute("aria-label", isPassphrase ? "Word count" : "Password length");527    amountLabel.textContent = isPassphrase ? "words" : "characters";528    lenNum.textContent = String(isPassphrase ? wordCount : length);529    regenerate();530  }531  passwordModeBtn.addEventListener("click", () => selectMode("password"));532  passphraseModeBtn.addEventListener("click", () => selectMode("passphrase"));533534  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;535  async function copy(): Promise<void> {536    try {537      await navigator.clipboard.writeText(password);538      copyBtn.classList.add("is-copied");539      if (copyResetTimer) clearTimeout(copyResetTimer);540      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);541    } catch {542      // Clipboard API may be denied — silently no-op; user still has regen UI.543    }544  }545  copyBtn.addEventListener("click", () => { void copy(); });546547  if (opts.initialPassword) {548    password = opts.initialPassword;549    output.value = password;550    opts.onChange?.(password);551  } else {552    regenerate();553  }554555  return {556    root,557    getPassword: () => password,558    copy,559  };560}561562export function observeAnchorPosition(563  anchorEl: HTMLElement,564  onUpdate: () => void565): () => void {566  let rafId = 0;567  let burstUntil = 0;568569  const runUpdate = () => {570    rafId = 0;571    onUpdate();572    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);573  };574  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };575  const scheduleBurst = (ms = 220) => {576    burstUntil = Math.max(burstUntil, performance.now() + ms);577    scheduleUpdate();578  };579580  const resizeObserver = new ResizeObserver(() => scheduleBurst());581  resizeObserver.observe(anchorEl);582  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);583584  const mutationObserver = new MutationObserver(() => scheduleBurst());585  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });586  if (anchorEl.parentElement) {587    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });588  }589590  const onScroll = () => scheduleUpdate();591  window.addEventListener("scroll", onScroll, true);592  window.addEventListener("resize", onScroll);593  window.visualViewport?.addEventListener("resize", onScroll);594  window.visualViewport?.addEventListener("scroll", onScroll);595  anchorEl.addEventListener("focus", () => scheduleBurst());596  anchorEl.addEventListener("input", () => scheduleBurst());597598  scheduleBurst(260);599600  return () => {601    if (rafId) cancelAnimationFrame(rafId);602    resizeObserver.disconnect();603    mutationObserver.disconnect();604    window.removeEventListener("scroll", onScroll, true);605    window.removeEventListener("resize", onScroll);606    window.visualViewport?.removeEventListener("resize", onScroll);607    window.visualViewport?.removeEventListener("scroll", onScroll);608  };609}610611export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {612  const button = document.createElement("button");613  button.type = "button";614  button.setAttribute("aria-label", "Peach autofill");615  button.title = "Fill with Peach";616  button.innerHTML = peachIconSvg();617  // position: fixed is load-bearing — not absolute. Absolute positioning618  // inherits the nearest positioned ancestor's box, which on sites with619  // overflow:hidden or sticky parents clips or offsets the icon. Fixed620  // anchors to the viewport and escapes all parent layout.621  button.style.cssText = `622    position: fixed; z-index: 2147483646;623    width: 26px; height: 26px; cursor: pointer;624    pointer-events: auto; border: none; padding: 3px;625    display: inline-flex; align-items: center; justify-content: center;626    background: transparent; border-radius: 999px;627    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;628    opacity: 0;629  `;630  button.addEventListener("mouseenter", () => {631    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;632    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;633    button.style.transform = "scale(1.08)";634  });635  button.addEventListener("mouseleave", () => {636    button.style.background = "transparent";637    button.style.boxShadow = "none";638    button.style.transform = "none";639  });640  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });641  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });642643  document.body.appendChild(button);644645  function updatePosition() {646    const rect = field.getBoundingClientRect();647    if (rect.width === 0 || rect.height === 0) {648      button.style.opacity = "0"; button.style.pointerEvents = "none";649      return;650    }651    const sz = 26;652    const inset = Math.max(5, Math.min(10, rect.height * 0.22));653    const top = rect.top + rect.height / 2 - sz / 2;654    // Clamp left so the icon stays fully inside the field's right edge, never655    // spilling onto an adjacent sibling button.656    const minLeft = rect.left + 4;657    const left = Math.max(minLeft, rect.right - sz - inset);658    // Hide if the field is too narrow to fit the icon cleanly (< 40px)659    if (rect.width < 40) {660      button.style.opacity = "0"; button.style.pointerEvents = "none";661      return;662    }663    button.style.top = `${top}px`;664    button.style.left = `${left}px`;665    button.style.opacity = "1"; button.style.pointerEvents = "auto";666  }667  updatePosition();668  requestAnimationFrame(() => { button.style.opacity = "1"; });669  const stopObserving = observeAnchorPosition(field, updatePosition);670  return () => { stopObserving(); button.remove(); };671}672673// All theme-dependent values resolve through tokens scoped to674// .peach-inline-popup[data-theme="dark|light"]. Accent variables675// (--peach-accent, --peach-glow, --peach-border-accent)676// are identical in both themes — only surface tokens differ. See677// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the678// theme switch — only literal brand-peach in peachIconSvg may stay raw.679const SELECTOR_STYLES = `680  :host { all: initial; }681  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }682683  .peach-inline-popup[data-theme="dark"] {684    --peach-bg:           #1a1410;685    --peach-bg-card:      #221c16;686    --peach-text:         #f5f0ea;687    --peach-text-dim:     #8a7a6a;688    --peach-text-muted:   #4a3a2a;689    --peach-border:       rgba(255,255,255,0.07);690    --peach-input-bg:     rgba(255,255,255,0.05);691    --peach-input-border: rgba(255,255,255,0.08);692  }693  .peach-inline-popup[data-theme="light"] {694    --peach-bg:           #fdf8f4;695    --peach-bg-card:      #f5ede4;696    --peach-text:         #1c1310;697    --peach-text-dim:     #6b5a4a;698    --peach-text-muted:   #a89080;699    --peach-border:       rgba(0,0,0,0.08);700    --peach-input-bg:     rgba(0,0,0,0.04);701    --peach-input-border: rgba(0,0,0,0.10);702  }703704  .peach-inline-popup {705    background: var(--peach-bg);706    border: 1px solid var(--peach-border-accent, var(--peach-border));707    border-radius: 14px;708    overflow: hidden;709    box-shadow:710      0 8px 40px var(--peach-glow, transparent),711      0 2px 12px rgba(0,0,0,0.5);712    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;713    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;714    transition: height 220ms cubic-bezier(0.16,1,0.3,1);715  }716  /* Light theme: shadow against a light page is too strong otherwise — drop both717     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */718  .peach-inline-popup[data-theme="light"] {719    box-shadow:720      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),721      0 2px 12px rgba(0,0,0,0.12);722  }723  .peach-inline-popup.is-exiting {724    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;725    pointer-events: none;726  }727728  @keyframes peach-enter {729    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }730    65%  { opacity: 1; filter: blur(0); }731    100% { opacity: 1; transform: translateY(0) scale(1); }732  }733  @keyframes peach-exit {734    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }735    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }736  }737  @keyframes peach-slide-in {738    from { opacity: 0; transform: translateX(12px); }739    to   { opacity: 1; transform: translateX(0); }740  }741  @keyframes peach-slide-back {742    from { opacity: 0; transform: translateX(-12px); }743    to   { opacity: 1; transform: translateX(0); }744  }745  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }746  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }747748  /* Domain header */749  .domain-header {750    padding: 9px 13px 7px;751    border-bottom: 1px solid var(--peach-border);752    display: flex; align-items: center; justify-content: space-between;753    gap: 8px;754  }755  .domain-header-text {756    display: flex; flex-direction: column; gap: 2px;757    min-width: 0; flex: 1;758  }759  .domain-eyebrow {760    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;761    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;762  }763  .domain-name {764    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);765    font-family: "IBM Plex Mono", monospace;766    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;767  }768  .domain-header-actions {769    display: inline-flex; align-items: center; gap: 5px;770    flex-shrink: 0;771  }772  .domain-add-btn,773  .domain-search-btn {774    flex-shrink: 0;775    width: 22px; height: 22px;776    display: inline-flex; align-items: center; justify-content: center;777    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);778    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);779    border-radius: 6px;780    color: var(--peach-accent);781    cursor: pointer; padding: 0;782    transition: background 120ms, border-color 120ms, transform 80ms;783    font-family: "IBM Plex Mono", monospace;784    font-size: 14px; line-height: 1;785  }786  .domain-add-btn:hover,787  .domain-search-btn:hover {788    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);789    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);790    transform: scale(1.06);791  }792  .domain-add-btn:active,793  .domain-search-btn:active { transform: scale(0.96); }794795  /* Search */796  .search-wrap {797    padding: 9px 12px 7px;798    border-bottom: 1px solid var(--peach-border);799  }800  /* UI-2 / MV-2: brief loading hint while the vault-wide list lazy-loads. */801  .search-loading {802    display: block;803    margin-top: 5px;804    font-size: 10px;805    color: var(--peach-text-dim);806    font-family: "IBM Plex Mono", monospace;807    animation: search-loading-pulse 1s ease-in-out infinite;808  }809  @keyframes search-loading-pulse { 0%,100% { opacity: 0.45; } 50% { opacity: 0.9; } }810  .search {811    width: 100%; background: var(--peach-input-bg);812    border: 1px solid var(--peach-input-border);813    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;814    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;815    transition: border-color 120ms, box-shadow 120ms;816  }817  .search:focus {818    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);819    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);820  }821  .search::placeholder { color: var(--peach-text-muted); }822823  /* Results */824  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }825  .results::-webkit-scrollbar { display: none; }826827  /* Entry rows */828  .entry {829    display: flex; align-items: center; padding: 8px 12px;830    cursor: pointer; border-bottom: 1px solid var(--peach-border);831    transition: background 70ms; position: relative; outline: none;832  }833  .entry:last-child { border-bottom: none; }834  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }835  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }836  .entry.focused::before {837    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;838    width: 2px; border-radius: 2px;839    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);840  }841842  .entry-icon {843    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;844    background: var(--peach-input-bg); border: 1px solid var(--peach-border);845    display: flex; align-items: center; justify-content: center;846    overflow: hidden; margin-right: 10px;847  }848  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }849  .entry-icon.is-new {850    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);851    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);852    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);853  }854855  .entry-info { flex: 1; min-width: 0; }856  .entry-title {857    font-size: 12.5px; color: var(--peach-text);858    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;859    line-height: 1.3;860  }861  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }862  .entry-sub {863    font-size: 10px; color: var(--peach-text-dim);864    font-family: "IBM Plex Mono", monospace;865    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;866    margin-top: 1px;867  }868869  .totp-badge {870    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;871    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);872    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);873    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;874  }875  .passkey-badge {876    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;877    border-radius: 4px;878    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);879    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);880    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);881    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;882  }883884  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }885886  .empty-hint {887    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);888    font-family: "IBM Plex Mono", monospace;889  }890891  /* Create form */892  .create-form-wrap {893    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;894  }895  .create-head {896    display: flex; align-items: center; gap: 8px;897    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);898  }899  .back-btn {900    background: transparent; border: none; cursor: pointer;901    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;902    display: flex; align-items: center; line-height: 0;903    transition: color 100ms, background 100ms;904  }905  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }906  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }907  /* minmax(0, 1fr) caps the grid track at the popup width — without it,908     long monospace content (e.g. a 60-char generated password) would909     auto-size the track wider than the popup and overflow the right edge. */910  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }911  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }912  .f-label {913    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;914    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;915  }916  .f-input {917    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);918    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;919    font-size: 11px; font-family: "IBM Plex Mono", monospace;920    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;921  }922  .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); }923  .f-input::placeholder { color: var(--peach-text-muted); }924  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }925  .f-row { display: flex; gap: 6px; }926  .f-row .f-input { flex: 1; min-width: 0; }927  .gen-btn {928    padding: 0 10px; border-radius: 7px; border: none;929    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);930    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);931    font-size: 10px; font-family: "IBM Plex Mono", monospace;932    cursor: pointer; white-space: nowrap; flex-shrink: 0;933    display: flex; align-items: center; gap: 4px;934    transition: background 100ms;935  }936  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }937  .gen-toggle-link {938    background: none; border: none; padding: 2px 0;939    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);940    font-size: 10px; font-family: "IBM Plex Mono", monospace;941    cursor: pointer; text-align: left; transition: color 100ms;942  }943  .gen-toggle-link:hover { color: var(--peach-accent); }944  .pw-history {945    display: grid; gap: 4px; margin-top: 4px;946    max-height: 150px; overflow-y: auto; scrollbar-width: thin;947  }948  .pw-history-row {949    display: flex; align-items: center; justify-content: space-between; gap: 6px;950    padding: 5px 7px; border-radius: 7px;951    background: color-mix(in srgb, var(--peach-accent) 6%, transparent);952    border: 1px solid color-mix(in srgb, var(--peach-accent) 10%, transparent);953  }954  .pw-history-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }955  .pw-history-pw {956    font-family: "IBM Plex Mono", monospace; font-size: 11px;957    color: var(--peach-t1, #eee); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;958  }959  .pw-history-age {960    font-family: "IBM Plex Mono", monospace; font-size: 9px;961    color: color-mix(in srgb, var(--peach-accent) 55%, transparent); letter-spacing: 0.03em;962  }963  .pw-history-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }964  .pw-history-btn {965    background: none; border: none; padding: 2px 5px; border-radius: 5px;966    color: color-mix(in srgb, var(--peach-accent) 65%, transparent);967    font-size: 9px; font-family: "IBM Plex Mono", monospace; cursor: pointer;968    transition: color 100ms, background 100ms;969  }970  .pw-history-btn:hover {971    color: var(--peach-accent);972    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);973  }974  .pw-history-empty {975    font-family: "IBM Plex Mono", monospace; font-size: 10px; line-height: 1.45;976    color: color-mix(in srgb, var(--peach-accent) 55%, transparent);977    padding: 6px 8px; border-radius: 7px;978    background: color-mix(in srgb, var(--peach-accent) 5%, transparent);979    border: 1px solid color-mix(in srgb, var(--peach-accent) 9%, transparent);980  }981  .save-btn {982    width: 100%; padding: 8px; border-radius: 8px; border: none;983    background: var(--peach-accent); color: #fff; font-size: 12px;984    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;985    transition: background 120ms, box-shadow 120ms, transform 80ms;986    letter-spacing: 0.01em;987  }988  .save-btn:hover {989    background: color-mix(in srgb, var(--peach-accent) 82%, #000);990    box-shadow: 0 4px 20px var(--peach-glow, transparent);991  }992  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }993  .url-hint {994    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);995    font-family: "IBM Plex Mono", monospace; font-style: italic;996  }997998  /* Success */999  .success-wrap {1000    display: flex; flex-direction: column; align-items: center;1001    padding: 24px 16px 20px; gap: 8px;1002    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;1003  }1004  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }1005  .success-ring {1006    width: 40px; height: 40px; border-radius: 50%;1007    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);1008    display: flex; align-items: center; justify-content: center;1009  }1010  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }1011  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }10121013  /* Silver platter (State 1 — single match) */1014  .silver-platter {1015    padding: 14px 14px 12px;1016    display: flex; flex-direction: column; gap: 6px;1017  }1018  .sp-title {1019    font-size: 14px; font-weight: 500; color: var(--peach-text);1020    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1021    line-height: 1.25;1022  }1023  .sp-identity-row {1024    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;1025  }1026  .sp-identity-label {1027    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;1028    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;1029  }1030  .sp-username {1031    font-size: 12px; color: var(--peach-text-dim);1032    font-family: "IBM Plex Mono", monospace;1033    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1034    margin-bottom: 0;1035  }1036  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }1037  .sp-fill-btn {1038    width: 100%; padding: 11px; border-radius: 9px; border: none;1039    background: var(--peach-accent); color: #fff;1040    font-size: 13px; font-weight: 500; cursor: pointer;1041    font-family: Inter, sans-serif; letter-spacing: 0.01em;1042    display: flex; align-items: center; justify-content: center; min-height: 38px;1043    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;1044  }1045  .sp-fill-btn:hover {1046    filter: brightness(1.1);1047    box-shadow: 0 4px 20px var(--peach-glow, transparent);1048    transform: translateY(-1px);1049  }1050  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }1051  .sp-fill-btn.filled {1052    background: #16a34a; transform: none; filter: none;1053    box-shadow: 0 4px 16px rgba(22,163,74,0.35);1054    cursor: default;1055  }1056  .sp-fill-btn:disabled { cursor: default; }1057  .sp-actions-group {1058    margin-top: 6px;1059    display: flex; flex-direction: column; gap: 4px;1060  }1061  .sp-actions-label {1062    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;1063    color: var(--peach-text-muted);1064    font-family: "IBM Plex Mono", monospace;1065    text-align: center;1066  }1067  .sp-actions {1068    display: flex; gap: 4px; justify-content: space-between; align-items: center;1069  }1070  .sp-action-btn {1071    flex: 1; height: 28px; border: none; border-radius: 6px;1072    background: transparent; color: var(--peach-text-dim);1073    font-size: 12px; cursor: pointer;1074    transition: background 120ms ease, color 120ms ease;1075    font-family: Inter, sans-serif; letter-spacing: 0.04em;1076    display: inline-flex; align-items: center; justify-content: center; gap: 4px;1077    white-space: nowrap; overflow: hidden;1078  }1079  .sp-action-btn:hover:not(:disabled) {1080    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1081    color: var(--peach-text);1082  }1083  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }1084  .sp-action-btn.flashed {1085    color: var(--peach-accent);1086    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1087  }10881089  /* TOTP tray — shown below the silver-platter secondary actions */1090  .sp-tray {1091    margin-top: 8px;1092    padding: 10px 12px;1093    border-radius: 9px;1094    background: var(--peach-input-bg);1095    border: 1px solid var(--peach-input-border);1096    display: flex; align-items: center; gap: 12px;1097    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;1098  }1099  .sp-tray-label {1100    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;1101    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;1102    flex-shrink: 0;1103  }1104  .sp-totp-code {1105    font-size: 18px; font-weight: 500;1106    color: var(--peach-text);1107    font-family: "IBM Plex Mono", monospace;1108    letter-spacing: 0.12em;1109    flex: 1;1110    text-align: center;1111  }1112  .sp-totp-ring {1113    width: 22px; height: 22px; flex-shrink: 0;1114  }1115  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }1116  .sp-totp-ring .ring-fill {1117    stroke: var(--peach-accent);1118    transition: stroke-dashoffset 1s linear;1119    transform: rotate(-90deg);1120    transform-origin: center;1121  }1122  .sp-totp-copy {1123    background: transparent; border: none; cursor: pointer;1124    padding: 4px 8px; border-radius: 5px;1125    color: var(--peach-text-dim); font-size: 11px;1126    font-family: Inter, sans-serif;1127    transition: background 120ms, color 120ms;1128  }1129  .sp-totp-copy:hover {1130    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1131    color: var(--peach-text);1132  }11331134  /* Card silver platter (State 7) — reuses .sp-* primary action classes */1135  .card-platter {1136    padding: 12px 14px 10px;1137    display: flex; flex-direction: column; gap: 4px;1138  }1139  .cp-network {1140    font-size: 10px; font-weight: 600;1141    color: var(--peach-accent);1142    letter-spacing: 0.08em; text-transform: uppercase;1143    font-family: Inter, sans-serif;1144  }1145  .cp-nickname {1146    font-size: 14px; font-weight: 500; color: var(--peach-text);1147    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1148    line-height: 1.2;1149  }1150  .cp-last4 {1151    font-size: 12px; color: var(--peach-text-dim);1152    font-family: "IBM Plex Mono", monospace;1153    letter-spacing: 0.04em;1154    margin-top: 2px;1155  }1156  .cp-meta {1157    font-size: 11px; color: var(--peach-text-dim);1158    font-family: "IBM Plex Mono", monospace;1159    margin-top: 2px;1160    display: flex; gap: 10px; align-items: center;1161  }1162  .cp-meta-sep { opacity: 0.5; }1163  .cp-fill-wrap { margin-top: 10px; }11641165  /* Locked state */1166  .locked-wrap {1167    display: flex; flex-direction: column; align-items: stretch;1168    padding: 14px 13px 13px; gap: 9px;1169  }1170  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }1171  .locked-icon {1172    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;1173    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1174    display: flex; align-items: center; justify-content: center;1175  }1176  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }1177  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }1178  .locked-input {1179    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1180    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;1181    font-size: 11px; font-family: "IBM Plex Mono", monospace;1182    outline: none; transition: border-color 120ms, box-shadow 120ms;1183  }1184  .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); }1185  .locked-input::placeholder { color: var(--peach-text-muted); }1186  .locked-btn {1187    width: 100%; padding: 8px; border-radius: 8px; border: none;1188    background: var(--peach-accent); color: #fff; font-size: 12px;1189    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;1190    transition: background 120ms;1191    letter-spacing: 0.01em;1192    box-shadow: 0 2px 16px var(--peach-glow, transparent);1193    animation: peach-pulse-glow 2.4s ease-in-out infinite;1194  }1195  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }1196  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }1197  .locked-error {1198    font-size: 10px; color: rgba(220,80,60,0.85);1199    font-family: "IBM Plex Mono", monospace;1200  }12011202  @keyframes peach-pulse-glow {1203    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }1204    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),1205                            0 0 48px var(--peach-glow, transparent); }1206  }12071208  /* ── State 10: identity helper ─────────────────────────────── */1209  .identity-list {1210    max-height: 192px; overflow-y: auto; padding: 4px 0;1211    scrollbar-width: none;1212  }1213  .identity-list::-webkit-scrollbar { display: none; }1214  .peach-identity-row {1215    display: flex; align-items: center; gap: 10px;1216    padding: 9px 12px; cursor: pointer; border-radius: 8px;1217    transition: background 100ms ease;1218  }1219  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1220  .peach-identity-value {1221    font-family: "IBM Plex Mono", monospace; font-size: 13px;1222    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1223  }1224  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1225  .identity-search-wrap {1226    display: flex; flex-direction: column; gap: 6px;1227  }1228  .identity-mode-toggle {1229    display: inline-flex; gap: 4px; flex-wrap: wrap;1230  }1231  .identity-mode-btn {1232    border: 1px solid var(--peach-input-border);1233    background: var(--peach-input-bg);1234    color: var(--peach-text-dim);1235    border-radius: 999px;1236    padding: 4px 9px;1237    cursor: pointer;1238    font-family: "IBM Plex Mono", monospace;1239    font-size: 9px;1240    letter-spacing: 0.03em;1241    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1242  }1243  .identity-mode-btn:hover {1244    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1245    color: var(--peach-text);1246  }1247  .identity-mode-btn.is-active {1248    color: var(--peach-accent);1249    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1250    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1251  }1252  .identity-mode-btn:active { transform: translateY(1px); }1253  .identity-custom-row {1254    display: flex; flex-direction: column; gap: 2px;1255    padding: 9px 12px; cursor: pointer; border-radius: 8px;1256    transition: background 100ms ease;1257  }1258  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1259  .identity-custom-row-title {1260    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1261  }1262  .identity-custom-row-sub {1263    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1264  }1265  .identity-empty {1266    padding: 10px 12px 2px; color: var(--peach-text-dim);1267    font-size: 10px; font-family: "IBM Plex Mono", monospace;1268  }1269  .identity-alt-row {1270    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1271    border-radius: 8px; transition: background 100ms ease;1272    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1273  }1274  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1275  .identity-escape-row {1276    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1277    border-radius: 8px; transition: background 100ms ease; outline: none;1278    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1279    margin-top: 2px;1280  }1281  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1282  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1283  .identity-alt-input-wrap.open { display: flex; }1284  .identity-alt-input {1285    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1286    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1287    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1288    outline: none; transition: border-color 120ms;1289  }1290  .identity-alt-input:focus {1291    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1292    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1293  }1294  .identity-alt-confirm {1295    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1296    background: var(--peach-accent); color: #fff; font-size: 12px;1297    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1298  }1299  /* ── Generator view (after identity picked) ────────────────── */1300  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1301  .gen-confirmed {1302    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1303    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1304    border-radius: 8px;1305  }1306  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1307  .gen-confirmed-val {1308    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1309    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1310  }1311  .gen-label {1312    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1313    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1314  }1315  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1316  .gen-pw-val {1317    flex: 1; padding: 8px 10px; border-radius: 7px;1318    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1319    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1320    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1321  }1322  .gen-regen-btn {1323    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1324    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1325    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1326    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1327  }1328  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1329  .gen-fill-btn {1330    padding: 10px; border-radius: 8px; border: none;1331    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1332    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1333    transition: filter 120ms ease, transform 80ms ease;1334  }1335  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1336  .gen-fill-btn:active { transform: translateY(0); }13371338  /* ── Smart password generator (parity with main UI compact mode) ─── */1339  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1340  .pwgen-display-row {1341    display: flex; align-items: center; gap: 6px;1342    padding: 8px 10px; border-radius: 7px;1343    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1344  }1345  .pwgen-output {1346    flex: 1; min-width: 0; width: 0;1347    font-family: "IBM Plex Mono", monospace; font-size: 12px;1348    color: var(--peach-text);1349    background: transparent; border: none; outline: none; padding: 0;1350  }1351  .pwgen-icon-btn {1352    flex-shrink: 0;1353    width: 26px; height: 26px;1354    display: inline-flex; align-items: center; justify-content: center;1355    background: transparent; border: 1px solid var(--peach-input-border);1356    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1357    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1358  }1359  .pwgen-icon-btn:hover {1360    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1361    color: var(--peach-accent);1362    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1363  }1364  .pwgen-icon-btn.is-copied {1365    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1366    color: var(--peach-accent);1367    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1368  }1369  .pwgen-controls-row {1370    display: flex; align-items: center; gap: 8px;1371    flex-wrap: wrap;1372  }1373  .pwgen-slider {1374    flex: 1; min-width: 110px;1375    accent-color: var(--peach-accent);1376    cursor: pointer; height: 2px; background: transparent;1377  }1378  .pwgen-len-num {1379    font-family: "IBM Plex Mono", monospace; font-size: 11px;1380    color: var(--peach-accent); min-width: 22px; text-align: right;1381  }1382  .pwgen-amount-label {1383    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1384    font-size: 9px; min-width: 50px;1385  }1386  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1387  .pwgen-len-input {1388    font-family: "IBM Plex Mono", monospace; font-size: 11px;1389    color: var(--peach-accent); width: 28px; text-align: right;1390    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1391    outline: none; padding: 0; min-width: 22px;1392  }1393  @keyframes identity-suggest-in {1394    from { opacity: 0; transform: translateY(-4px); }1395    to   { opacity: 1; transform: none; }1396  }1397  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1398    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1399  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1400  .identity-collapse-btn {1401    margin-left: auto; background: transparent; border: none; cursor: pointer;1402    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1403    line-height: 0; border-radius: 3px;1404    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1405  }1406  .identity-collapse-btn:hover { color: var(--peach-text); }1407  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1408  .identity-rows { display: grid; grid-template-rows: 1fr;1409    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1410  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1411  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1412    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1413  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1414  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1415  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1416  .identity-filter-pill {1417    padding: 2px 7px; border-radius: 999px;1418    border: 1px solid var(--peach-input-border);1419    background: transparent; color: var(--peach-text-muted);1420    font-family: "IBM Plex Mono", monospace; font-size: 9px;1421    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1422  }1423  .identity-filter-pill.is-on {1424    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1425    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1426    color: var(--peach-accent);1427  }1428  .identity-suggest-row {1429    display: flex; align-items: center; gap: 5px;1430    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1431    background: transparent; cursor: pointer; text-align: left;1432    transition: background 80ms;1433  }1434  .identity-suggest-row:hover,1435  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1436  .identity-suggest-val {1437    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1438    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1439  }1440  .identity-suggest-type {1441    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1442    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1443  }1444  .identity-suggest-type--email {1445    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1446    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1447  }1448  .identity-suggest-type--username {1449    color: var(--peach-text-muted);1450    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1451  }1452  .identity-suggest-meta {1453    font-family: "IBM Plex Mono", monospace; font-size: 9px;1454    color: var(--peach-text-muted); flex-shrink: 0;1455  }1456  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1457  .pwgen-pill {1458    padding: 3px 8px; border-radius: 999px;1459    border: 1px solid var(--peach-input-border);1460    background: transparent; color: var(--peach-text-muted);1461    font-family: "IBM Plex Mono", monospace; font-size: 9px;1462    letter-spacing: 0.06em; cursor: pointer;1463    transition: all 130ms ease;1464  }1465  .pwgen-pill.is-on {1466    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1467    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1468    color: var(--peach-accent);1469  }1470  .pwgen-pill:not(.is-on):hover {1471    color: var(--peach-text-dim);1472    border-color: var(--peach-text-muted);1473  }1474  .pwgen-policy-hint {1475    font-size: 10px; color: var(--peach-text-muted);1476    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1477    line-height: 1.3;1478  }1479  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }14801481  /* ── Save offer (after password filled) ───────────────────── */1482  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1483  .save-offer-title {1484    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1485  }1486  .save-offer-row {1487    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1488    border-radius: 7px; background: var(--peach-input-bg);1489    border: 1px solid var(--peach-input-border);1490  }1491  .save-offer-lbl {1492    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1493    font-family: "IBM Plex Mono", monospace;1494  }1495  .save-offer-val {1496    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1497    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1498  }1499  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1500  .save-offer-save {1501    flex: 1; padding: 9px; border-radius: 8px; border: none;1502    background: var(--peach-accent); color: #fff; font-size: 13px;1503    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1504  }1505  .save-offer-save:hover { filter: brightness(1.08); }1506  .save-offer-skip {1507    flex: 1; padding: 9px; border-radius: 8px; border: none;1508    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1509    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1510    font-family: Inter, sans-serif; transition: background 100ms ease;1511  }1512  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1513`;15141515export function showAutofillSelector(1516  anchorEl: HTMLInputElement,1517  entries: SelectorEntry[],1518  onSelect: (id: string) => void,1519  options: SelectorOptions = {}1520): () => void {1521  const host = document.createElement("div");1522  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1523  // when Peach's internal inputs gain focus, immediately blurring them and closing1524  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1525  // as in-bounds (v3.6.131).1526  //1527  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1528  // A plain login page whose card uses transform/filter/backdrop-filter establishes1529  // a containing block for position:fixed, so a host mounted inside it lands offset1530  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1531  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1532  // the popup ~400px off the field and clipped it behind overflow:clip — the user1533  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1534  // everything else mounts at the document root, where fixed == viewport.1535  const modalAncestor = (1536    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1537    (() => {1538      let cur: HTMLElement | null = anchorEl.parentElement;1539      while (cur && cur !== document.body) {1540        if (window.getComputedStyle(cur).position === 'fixed') return cur;1541        cur = cur.parentElement;1542      }1543      return null;1544    })()1545  );1546  host.style.cssText = `position: fixed; z-index: 2147483647;`;1547  host.style.setProperty("--peach-accent", accentHex);1548  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1549  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1550  // Hint the compositor that top/left animate during scroll repositioning so the1551  // popup stays on the GPU layer and doesn't flicker as observeAnchorPosition1552  // re-asserts its coordinates.1553  host.style.willChange = "top, left";1554  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1555  // HOST appear focused to the outside DOM. Modal focus traps that monitor1556  // focusin then see the host (mounted inside the modal) as the focused element1557  // rather than an opaque closed-shadow node, so they don't fire their1558  // "focus escaped" handler and yank focus back. Harmless outside modals.1559  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });15601561  const style = shadow.appendChild(document.createElement("style"));1562  style.textContent = SELECTOR_STYLES;15631564  const rect = anchorEl.getBoundingClientRect();1565  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1566  // applying containing-block compensation once host.parentElement is known.1567  host.style.top = `${rect.bottom + 5}px`;1568  host.style.left = `${rect.left}px`;1569  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1570  // wide single-input fields (e.g. centered email input on signup pages).1571  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1572  // expand the host after the initial measurement.1573  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1574  host.style.width = `${popupWidth}px`;15751576  const container = shadow.appendChild(document.createElement("div"));1577  container.className = "peach-inline-popup";1578  container.setAttribute("data-theme", popupTheme);15791580  // MV-2: the vault-wide list is loaded lazily on the first search gesture,1581  // never eagerly on passive popup open. Cached for the popup's lifetime.1582  let searchableEntries: SelectorEntry[] = options.searchableEntries ?? [];1583  let searchableLoading = false;1584  let searchableLoaded = !options.loadSearchableEntries;15851586  async function ensureSearchableLoaded(rerender: () => void): Promise<void> {1587    if (searchableLoaded || searchableLoading || !options.loadSearchableEntries) {1588      return;1589    }1590    searchableLoading = true;1591    try {1592      searchableEntries = await options.loadSearchableEntries();1593    } catch {1594      searchableEntries = [];1595    } finally {1596      searchableLoaded = true;1597      searchableLoading = false;1598      rerender();1599    }1600  }1601  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();16021603  let query = "";1604  let focusedIndex = -1;1605  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" | "edit" = "list";1606  let searchInput: HTMLInputElement | null = null;1607  let identityMode: IdentityFilterMode = "both";1608  // Tracks the silver-platter entry the user pivoted away from, so the1609  // search/list header can offer a one-click way back to it. null when the1610  // popup never showed a single-match platter (e.g. multi-match list view).1611  let silverPlatterOrigin: SelectorEntry | null = null;1612  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1613  // setInterval. Add to this list — don't fan out the dismiss function.1614  const cleanupHooks: Array<() => void> = [];16151616  // Smooth height transitions whenever content changes height.1617  // ResizeObserver fires on natural height changes; we freeze the old height,1618  // then animate to the new one so the surface never jumps.1619  {1620    let prevH = 0;1621    let blocked = false;1622    const heightRo = new ResizeObserver(([entry]) => {1623      if (blocked) return;1624      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1625      if (prevH > 0 && Math.abs(h - prevH) > 1) {1626        blocked = true;1627        container.style.height = `${prevH}px`;1628        requestAnimationFrame(() => requestAnimationFrame(() => {1629          container.style.height = `${h}px`;1630          prevH = h;1631          const onEnd = (e: TransitionEvent) => {1632            if (e.propertyName !== "height") return;1633            container.style.height = "";1634            blocked = false;1635            container.removeEventListener("transitionend", onEnd);1636          };1637          container.addEventListener("transitionend", onEnd);1638        }));1639      } else {1640        prevH = h;1641      }1642    });1643    heightRo.observe(container);1644    cleanupHooks.push(() => heightRo.disconnect());1645  }16461647  // Pre-capture the anchor field value for username prefill1648  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1649  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1650  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";16511652  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1653    const seen = new Set<string>();1654    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1655  }16561657  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1658    const q = value.trim().toLowerCase();1659    const deduped = uniqueEntries(source);1660    if (!q) return deduped.slice(0, 8);1661    return deduped.filter(e =>1662      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1663    ).slice(0, 12);1664  }16651666  function activeEntries(): SelectorEntry[] {1667    // When user is typing a search, filter across all known entries (domain matches + vault)1668    if (query.trim()) {1669      const merged = uniqueEntries([...entries, ...searchableEntries]);1670      return filterEntries(merged, query);1671    }1672    // Default: show domain matches; fall back to vault search when no matches1673    if (entries.length > 0) return entries;1674    return filterEntries(searchableEntries, "").slice(0, 8);1675  }16761677  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1678    const icon = document.createElement("div");1679    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1680    if (isNew) {1681      icon.innerHTML = plusSvgStr();1682    } else {1683      // Use the generic key glyph for all entries in the page-injected selector.1684      // Avoids disclosing vault domains to any third party and avoids needing1685      // to expose the browser favicon API to page context via web_accessible_resources.1686      void url;1687      icon.innerHTML = keySvgStr();1688    }1689    return icon;1690  }16911692  function renderIdentityHelper() {1693    currentMode = "identity-helper";1694    container.innerHTML = "";1695    focusedIndex = -1;1696    searchInput = null;16971698    const fallbackKind: IdentityKind = options.identityKind ?? "username";1699    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1700    const typedQuery = query.trim();1701    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);17021703    function applyIdentity(identity: string) {1704      if (options.hasEmailField) {1705        if (options.identityKind === "email") {1706          options.onFillFields?.("", "", identity);       // fill email field now1707          renderSecondaryIdentityStep("username", identity);1708        } else {1709          options.onFillFields?.(identity, "", "");       // fill username field now1710          renderSecondaryIdentityStep("email", identity);1711        }1712      } else {1713        options.onFillFields?.(identity, "");1714        renderGenerator(identity);1715      }1716    }17171718    function applyCustomIdentity(identity: string) {1719      const trimmed = identity.trim();1720      if (!trimmed) return;1721      applyIdentity(trimmed);1722    }17231724    // Header: "NEW ACCOUNT" + domain name1725    const hdr = container.appendChild(document.createElement("div"));1726    hdr.className = "domain-header";1727    const headText = hdr.appendChild(document.createElement("div"));1728    headText.className = "domain-header-text";1729    const eyebrow = headText.appendChild(document.createElement("div"));1730    eyebrow.className = "domain-eyebrow";1731    eyebrow.textContent = "NEW ACCOUNT";1732    const domName = headText.appendChild(document.createElement("div"));1733    domName.className = "domain-name";1734    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");17351736    const actions = hdr.appendChild(document.createElement("div"));1737    actions.className = "identity-mode-toggle";1738    for (const mode of ["both", "email", "username"] as const) {1739      const btn = actions.appendChild(document.createElement("button"));1740      btn.type = "button";1741      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1742      btn.textContent = identityFilterLabel(mode);1743      btn.setAttribute("aria-pressed", String(identityMode === mode));1744      btn.addEventListener("click", () => {1745        identityMode = mode;1746        renderIdentityHelper();1747      });1748    }17491750    const searchWrap = container.appendChild(document.createElement("div"));1751    searchWrap.className = "search-wrap identity-search-wrap";1752    const search = searchWrap.appendChild(document.createElement("input"));1753    search.className = "search";1754    search.placeholder = "search identities…";1755    search.value = query;1756    search.addEventListener("input", () => {1757      query = search.value;1758      renderIdentityHelper();1759      searchInput?.focus();1760      searchInput?.setSelectionRange(query.length, query.length);1761    });1762    search.addEventListener("keydown", (e) => {1763      if (e.key === "Escape") {1764        e.preventDefault();1765        dismiss(true);1766        return;1767      }1768      if (e.key !== "Enter") return;1769      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1770      if (exact) {1771        e.preventDefault();1772        applyIdentity(exact.value);1773        return;1774      }1775      if (!typedQuery || identities.length > 0) return;1776      e.preventDefault();1777      applyCustomIdentity(typedQuery);1778    });1779    const searchTools = searchWrap.appendChild(document.createElement("div"));1780    searchTools.className = "identity-mode-toggle";1781    const sortHint = searchTools.appendChild(document.createElement("div"));1782    sortHint.className = "identity-empty";1783    sortHint.style.padding = "0";1784    sortHint.textContent = "sorted by recent use";1785    searchInput = search;1786    const customLabel = identityMode === "both"1787      ? customKind1788      : identityMode;17891790    // Identity rows1791    const list = container.appendChild(document.createElement("div"));1792    list.className = "identity-list";1793    // Bottom fade only when the list overflows its max-height and isn't scrolled1794    // to the end. A short list (1-2 identities) shows no fade, so it never looks1795    // prematurely cut off; a long list gets the affordance, which clears on1796    // reaching the bottom.1797    const updateListFade = () => {1798      const overflowing = list.scrollHeight > list.clientHeight + 1;1799      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1800      const mask = overflowing && !atBottom1801        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1802        : "none";1803      list.style.setProperty("mask-image", mask);1804      list.style.setProperty("-webkit-mask-image", mask);1805    };1806    list.addEventListener("scroll", updateListFade);1807    if (typedQuery && identities.length === 0) {1808      const empty = list.appendChild(document.createElement("div"));1809      empty.className = "identity-empty";1810      empty.textContent = identityMode === "both"1811        ? `No match for “${typedQuery}”.`1812        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1813      const custom = list.appendChild(document.createElement("div"));1814      custom.className = "identity-custom-row";1815      const customTitle = custom.appendChild(document.createElement("div"));1816      customTitle.className = "identity-custom-row-title";1817      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1818      const customSub = custom.appendChild(document.createElement("div"));1819      customSub.className = "identity-custom-row-sub";1820      customSub.textContent = "Press Enter or click to continue.";1821      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1822    }1823    for (const id of identities) {1824      const row = list.appendChild(document.createElement("div"));1825      row.className = "peach-identity-row";1826      row.setAttribute("tabindex", "-1");1827      const val = row.appendChild(document.createElement("div"));1828      val.className = "peach-identity-value";1829      val.textContent = id.value;1830      const meta = row.appendChild(document.createElement("div"));1831      meta.className = "peach-identity-meta";1832      meta.textContent = `used ${id.useCount}×`;1833      row.addEventListener("click", () => {1834        applyIdentity(id.value);1835      });1836    }18371838    updateListFade();18391840    // Divider before "Use a different email…"1841    if (identities.length > 0) {1842      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1843    }18441845    // "Use a different email/username…" expandable row1846    const altRow = container.appendChild(document.createElement("div"));1847    altRow.className = "identity-alt-row";1848    altRow.textContent = `+ Use a different ${customLabel}…`;18491850    const altInputWrap = container.appendChild(document.createElement("div"));1851    altInputWrap.className = "identity-alt-input-wrap";1852    const altInput = altInputWrap.appendChild(document.createElement("input"));1853    altInput.className = "identity-alt-input";1854    altInput.type = "text";1855    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1856    altInput.setAttribute("autocomplete", "off");1857    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1858    altConfirm.className = "identity-alt-confirm";1859    altConfirm.type = "button";1860    altConfirm.textContent = "✓";18611862    function fillCustomIdentity() {1863      const v = altInput.value.trim();1864      if (!v) return;1865      applyCustomIdentity(v);1866    }18671868    altRow.addEventListener("click", () => {1869      altRow.style.display = "none";1870      altInputWrap.classList.add("open");1871      altInput.value = typedQuery || altInput.value;1872      altInput.focus();1873      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1874    });1875    altConfirm.addEventListener("click", fillCustomIdentity);1876    altInput.addEventListener("keydown", (e) => {1877      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1878    });18791880    // Escape hatch: user already has a vault entry for this site but it1881    // wasn't detected (different domain, old entry, etc.). Tapping this1882    // switches to the full searchable list so they can find and fill it;1883    // selecting an entry there will trigger the remember-site toast if1884    // the domain isn't already associated.1885    // MV-2: with lazy loading we no longer know the vault-wide count up front,1886    // so offer the escape hatch whenever a loader (or an eager array) exists.1887    if (options.loadSearchableEntries || (options.searchableEntries?.length ?? 0) > 0) {1888      const escapeRow = container.appendChild(document.createElement("div"));1889      escapeRow.className = "identity-escape-row";1890      escapeRow.textContent = "I already have an account →";1891      escapeRow.setAttribute("tabindex", "0");1892      const toSearch = () => { void ensureSearchableLoaded(renderList); renderList(); };1893      escapeRow.addEventListener("click", toSearch);1894      escapeRow.addEventListener("keydown", (e) => {1895        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toSearch(); }1896      });1897    }18981899    requestAnimationFrame(() => {1900      search.focus();1901      search.setSelectionRange(query.length, query.length);1902    });1903  }19041905  /**1906   * Step 2 of the contextual signup wizard.1907   * `stepKind` is the identity type to collect in this step ("email" or "username").1908   * `firstValue` is what was picked in step 1 (the other type).1909   */1910  function renderSecondaryIdentityStep(stepKind: "email" | "username", firstValue: string) {1911    currentMode = "identity-helper";1912    container.innerHTML = "";19131914    const wrap = container.appendChild(document.createElement("div"));1915    wrap.className = "gen-view";19161917    // Header1918    const hdrRow = wrap.appendChild(document.createElement("div"));1919    hdrRow.className = "domain-header";1920    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1921    eyebrow2.className = "domain-eyebrow";1922    eyebrow2.textContent = "NEW ACCOUNT";1923    const domName2 = hdrRow.appendChild(document.createElement("div"));1924    domName2.className = "domain-name";1925    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");19261927    // Confirmed first step1928    const conf = wrap.appendChild(document.createElement("div"));1929    conf.className = "gen-confirmed";1930    const confCheck = conf.appendChild(document.createElement("span"));1931    confCheck.className = "gen-confirmed-check";1932    confCheck.textContent = "✓";1933    const confVal = conf.appendChild(document.createElement("div"));1934    confVal.className = "gen-confirmed-val";1935    confVal.textContent = firstValue;19361937    const stepLbl = wrap.appendChild(document.createElement("div"));1938    stepLbl.className = "gen-label";1939    stepLbl.textContent = stepKind === "email" ? "Now choose your email" : "Now choose your username";19401941    // Filter saved identities to the correct type for this step1942    const identities = (options.savedIdentities ?? [])1943      .filter(s => s.type === stepKind)1944      .sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0))1945      .slice(0, 6);19461947    const list = wrap.appendChild(document.createElement("div"));1948    list.className = "identity-list";1949    for (const id of identities) {1950      const row = list.appendChild(document.createElement("div"));1951      row.className = "peach-identity-row";1952      row.setAttribute("tabindex", "-1");1953      const val = row.appendChild(document.createElement("div"));1954      val.className = "peach-identity-value";1955      val.textContent = id.value;1956      const meta = row.appendChild(document.createElement("div"));1957      meta.className = "peach-identity-meta";1958      meta.textContent = `used ${id.useCount}×`;1959      row.addEventListener("click", () => applySecondIdentity(id.value));1960    }19611962    // Text input for a value not in the list1963    const altInputWrap = wrap.appendChild(document.createElement("div"));1964    altInputWrap.className = "identity-alt-input-wrap open";1965    const altInput = altInputWrap.appendChild(document.createElement("input"));1966    altInput.className = "identity-alt-input";1967    altInput.type = stepKind === "email" ? "email" : "text";1968    altInput.placeholder = stepKind === "email" ? "[email protected]" : "your username";1969    altInput.setAttribute("autocomplete", "off");1970    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1971    altConfirm.className = "identity-alt-confirm";1972    altConfirm.type = "button";1973    altConfirm.textContent = "→";19741975    function applySecondIdentity(value: string) {1976      const trimmed = value.trim();1977      if (!trimmed) return;1978      // Determine final email + username order before passing to the generator1979      const [email, username] = stepKind === "email"1980        ? [trimmed, firstValue]1981        : [firstValue, trimmed];1982      if (stepKind === "email") {1983        options.onFillFields?.("", "", trimmed); // fill email field1984      } else {1985        options.onFillFields?.(trimmed, "", ""); // fill username field1986      }1987      renderGenerator(email, username);1988    }19891990    altConfirm.addEventListener("click", () => applySecondIdentity(altInput.value));1991    altInput.addEventListener("keydown", (e) => {1992      if (e.key === "Enter") { e.preventDefault(); applySecondIdentity(altInput.value); }1993    });19941995    // Skip: proceed without this field1996    const skipRow = wrap.appendChild(document.createElement("div"));1997    skipRow.className = "identity-escape-row";1998    skipRow.textContent = `Skip ${stepKind} →`;1999    skipRow.setAttribute("tabindex", "0");2000    skipRow.addEventListener("click", () => {2001      const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];2002      renderGenerator(email, username);2003    });2004    skipRow.addEventListener("keydown", (e) => {2005      if (e.key === "Enter" || e.key === " ") {2006        e.preventDefault();2007        const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];2008        renderGenerator(email, username);2009      }2010    });20112012    requestAnimationFrame(() => { altInput.focus(); });2013  }20142015  function renderGenerator(filledEmail: string, filledUsername?: string) {2016    container.innerHTML = "";2017    const sitePolicy = detectPasswordPolicy();20182019    const wrap = container.appendChild(document.createElement("div"));2020    wrap.className = "gen-view";20212022    // Header: domain + NEW ACCOUNT2023    const hdrRow = wrap.appendChild(document.createElement("div"));2024    hdrRow.className = "domain-header";2025    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));2026    eyebrow2.className = "domain-eyebrow";2027    eyebrow2.textContent = "NEW ACCOUNT";2028    const domName2 = hdrRow.appendChild(document.createElement("div"));2029    domName2.className = "domain-name";2030    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");20312032    // Confirmed identity rows — show both username and email when both were collected2033    function confirmedRow(value: string) {2034      const conf = wrap.appendChild(document.createElement("div"));2035      conf.className = "gen-confirmed";2036      const confCheck = conf.appendChild(document.createElement("span"));2037      confCheck.className = "gen-confirmed-check";2038      confCheck.textContent = "✓";2039      const confVal = conf.appendChild(document.createElement("div"));2040      confVal.className = "gen-confirmed-val";2041      confVal.textContent = value;2042    }2043    if (filledEmail) confirmedRow(filledEmail);2044    if (filledUsername && filledUsername !== filledEmail) confirmedRow(filledUsername);20452046    const lbl = wrap.appendChild(document.createElement("div"));2047    lbl.className = "gen-label";2048    lbl.textContent = "Generate a password";20492050    let currentPw = "";2051    const smartGen = createSmartGenerator({2052      policy: sitePolicy,2053      onChange: (pw) => { currentPw = pw; },2054    });2055    wrap.appendChild(smartGen.root);20562057    const fillBtn = wrap.appendChild(document.createElement("button"));2058    fillBtn.className = "gen-fill-btn";2059    fillBtn.type = "button";2060    fillBtn.textContent = "Copy & fill";2061    fillBtn.addEventListener("click", async () => {2062      if (!currentPw) return;2063      fillBtn.disabled = true;2064      fillBtn.textContent = "Saving…";2065      // Fill the page fields first — password lands immediately.2066      options.onFillFields?.("", currentPw, "");2067      // Auto-save to vault. Fall back to the save-offer form only if the save fails2068      // (vault locked, quota exceeded, etc.) so the user sees the error and can retry.2069      const saveUsername = filledUsername || filledEmail;2070      const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;2071      try {2072        const res = await chrome.runtime.sendMessage({2073          type: "ADD_ENTRY",2074          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: currentPw, type: "login" },2075        });2076        if ((res as { ok?: boolean }).ok) {2077          showSuccess(sTitle);2078        } else {2079          renderSaveOffer(filledEmail, currentPw, filledUsername);2080        }2081      } catch {2082        renderSaveOffer(filledEmail, currentPw, filledUsername);2083      }2084    });2085  }20862087  function renderSaveOffer(filledEmail: string, filledPassword: string, filledUsername?: string) {2088    container.innerHTML = "";2089    const domain = options.domain ?? location.hostname.replace(/^www\./, "");20902091    const wrap = container.appendChild(document.createElement("div"));2092    wrap.className = "save-offer";20932094    const title = wrap.appendChild(document.createElement("div"));2095    title.className = "save-offer-title";2096    title.textContent = "Save this login to Peach?";20972098    function detailRow(label: string, value: string) {2099      const row = wrap.appendChild(document.createElement("div"));2100      row.className = "save-offer-row";2101      const lbl = row.appendChild(document.createElement("div"));2102      lbl.className = "save-offer-lbl";2103      lbl.textContent = label;2104      const val = row.appendChild(document.createElement("div"));2105      val.className = "save-offer-val";2106      val.textContent = value;2107    }21082109    detailRow("site", domain);2110    // When both username and email were collected, show both; otherwise show the identity as "email"2111    if (filledUsername) {2112      detailRow("username", filledUsername);2113      if (filledEmail) detailRow("email", filledEmail);2114    } else {2115      if (filledEmail) detailRow("email", filledEmail);2116    }2117    detailRow("password", "••••••••••••••••");21182119    const btns = wrap.appendChild(document.createElement("div"));2120    btns.className = "save-offer-btns";21212122    const saveBtn = btns.appendChild(document.createElement("button"));2123    saveBtn.className = "save-offer-save";2124    saveBtn.type = "button";2125    saveBtn.textContent = "Save";2126    saveBtn.addEventListener("click", async () => {2127      saveBtn.disabled = true;2128      saveBtn.textContent = "Saving…";2129      try {2130        // When both username and email were set, save them in the correct fields.2131        // Otherwise fall back to storing the identity as the username (current behaviour).2132        const saveUsername = filledUsername || filledEmail;2133        const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;2134        const res = await chrome.runtime.sendMessage({2135          type: "ADD_ENTRY",2136          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: filledPassword, type: "login" },2137        });2138        if ((res as { ok?: boolean }).ok) {2139          showSuccess(sTitle);2140        } else {2141          saveBtn.disabled = false;2142          saveBtn.textContent = "Save";2143        }2144      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }2145    });21462147    const skipBtn = btns.appendChild(document.createElement("button"));2148    skipBtn.className = "save-offer-skip";2149    skipBtn.type = "button";2150    skipBtn.textContent = "Not now";2151    skipBtn.addEventListener("click", () => { dismiss(true); });2152  }21532154  function renderList() {2155    container.innerHTML = "";2156    focusedIndex = -1;2157    searchInput = null;2158    currentMode = "list";21592160    const current = activeEntries();21612162    // Domain header (always show) — eyebrow + domain on the left,2163    // a "+" shortcut to the create form on the right so the user is never2164    // trapped in the search list when they want to make a new entry.2165    const domHdr = document.createElement("div");2166    domHdr.className = "domain-header";2167    const headText = document.createElement("div");2168    headText.className = "domain-header-text";2169    const eyebrow = document.createElement("div");2170    eyebrow.className = "domain-eyebrow";2171    eyebrow.textContent = options.isSignup2172      ? "Sign up as"2173      : entries.length > 0 ? "Saved for this site" : "No saved login";2174    const domName = document.createElement("div");2175    domName.className = "domain-name";2176    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2177    headText.append(eyebrow, domName);2178    domHdr.appendChild(headText);21792180    if (!options.isSignup) {2181      const actions = document.createElement("div");2182      actions.className = "domain-header-actions";21832184      // Back arrow takes the place of the silver-platter's search icon when2185      // the user has pivoted away from a single-match platter — gives them2186      // a one-click way back to the original recommendation.2187      if (silverPlatterOrigin) {2188        const backBtn = document.createElement("button");2189        backBtn.className = "domain-search-btn";2190        backBtn.type = "button";2191        backBtn.setAttribute("aria-label", "Back to suggested entry");2192        backBtn.title = "Back to suggested entry";2193        backBtn.innerHTML = backSvgStr();2194        backBtn.addEventListener("click", (e) => {2195          e.stopPropagation();2196          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);2197        });2198        actions.appendChild(backBtn);2199      }22002201      const addBtn = document.createElement("button");2202      addBtn.className = "domain-add-btn";2203      addBtn.type = "button";2204      addBtn.setAttribute("aria-label", "Create new entry");2205      addBtn.title = "Create new entry";2206      addBtn.textContent = "+";2207      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2208      actions.appendChild(addBtn);22092210      domHdr.appendChild(actions);2211    }22122213    container.appendChild(domHdr);22142215    // Search — always show so user can find entries beyond the domain matches2216    const sw = document.createElement("div"); sw.className = "search-wrap";2217    searchInput = document.createElement("input");2218    searchInput.className = "search";2219    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";2220    searchInput.value = query;2221    searchInput.addEventListener("input", () => {2222      query = searchInput?.value ?? "";2223      // MV-2: typing in the search box is the explicit gesture that loads the2224      // vault-wide list (once, cached); it re-renders when it resolves.2225      void ensureSearchableLoaded(renderList);2226      renderList();2227      searchInput?.focus();2228      searchInput?.setSelectionRange(query.length, query.length);2229    });2230    sw.appendChild(searchInput);2231    // UI-2 / MV-2: show a brief loading hint while the vault-wide list loads2232    // on the first search gesture (cached afterwards, so only the first time).2233    if (searchableLoading) {2234      const loadingHint = document.createElement("span");2235      loadingHint.className = "search-loading";2236      loadingHint.textContent = "searching…";2237      sw.appendChild(loadingHint);2238    }2239    container.appendChild(sw);22402241    // Results2242    const results = document.createElement("div");2243    results.className = "results";2244    container.appendChild(results);22452246    if (current.length === 0 && entries.length > 0) {2247      // Show a hint but don't render empty entries2248    }22492250    for (let i = 0; i < current.length; i++) {2251      const e = current[i]!;2252      const entryEl = document.createElement("div");2253      entryEl.className = "entry";2254      entryEl.dataset.id = e.id;2255      entryEl.dataset.index = String(i);2256      entryEl.setAttribute("tabindex", "-1");22572258      entryEl.appendChild(makeEntryIcon(e.url));22592260      const info = document.createElement("div"); info.className = "entry-info";2261      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;2262      const subEl = document.createElement("div"); subEl.className = "entry-sub";2263      const domain = e.url ? getDomainFromUrl(e.url) : "";2264      subEl.textContent = domain || e.username || "";2265      info.append(titleEl, subEl);2266      entryEl.appendChild(info);22672268      if (e.hasTotp) {2269        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";2270        entryEl.appendChild(badge);2271      }2272      if (e.hasPasskey) {2273        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";2274        entryEl.appendChild(badge);2275      }22762277      entryEl.addEventListener("click", () => {2278        if (options.isSignup && options.onFillFields) {2279          // Fill username, email, and leave password for the user to confirm2280          options.onFillFields(e.username ?? "", "", e.email);2281          dismiss();2282        } else {2283          onSelect(e.id);2284          dismiss();2285        }2286      });2287      results.appendChild(entryEl);2288    }22892290    // Divider before "New entry"2291    if (current.length > 0) {2292      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));2293    }22942295    // "New entry" row — always present2296    const newEl = document.createElement("div");2297    newEl.className = "entry";2298    newEl.setAttribute("tabindex", "-1");2299    newEl.appendChild(makeEntryIcon(undefined, true));23002301    const newInfo = document.createElement("div"); newInfo.className = "entry-info";2302    const newTitle = document.createElement("div");2303    newTitle.className = "entry-title is-new";2304    newTitle.textContent = `New entry for ${sTitle}`;2305    const newSub = document.createElement("div");2306    newSub.className = "entry-sub";2307    newSub.textContent = sOrigin;2308    newInfo.append(newTitle, newSub);2309    newEl.appendChild(newInfo);2310    newEl.addEventListener("click", showCreateForm);2311    results.appendChild(newEl);23122313    // Focus search if present2314    if (searchInput) {2315      requestAnimationFrame(() => {2316        searchInput?.focus();2317        // Seed query (from type-to-search or domain-search-btn) lands at the2318        // end so the next keystroke extends it, not overwrites.2319        searchInput?.setSelectionRange(query.length, query.length);2320      });2321    }2322  }23232324  function setFocused(idx: number) {2325    const all = container.querySelectorAll<HTMLElement>(".entry");2326    all.forEach((el, i) => el.classList.toggle("focused", i === idx));2327    focusedIndex = idx;2328    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });2329  }23302331  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {2332    const typed = identities.filter(s => s.type === fieldType);2333    if (!typed.length) return;2334    let collapsed = false;2335    let suppressNextFocus = false;23362337    const list = g.appendChild(document.createElement("div"));2338    list.className = "identity-suggest-list";2339    list.style.display = "none";23402341    // Collapse toggle — sits alone now that filter pills are gone2342    const collapseRow = list.appendChild(document.createElement("div"));2343    collapseRow.className = "identity-filter-row";2344    collapseRow.style.justifyContent = "flex-end";2345    const collapseBtn = collapseRow.appendChild(document.createElement("button"));2346    collapseBtn.type = "button";2347    collapseBtn.className = "identity-collapse-btn";2348    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>`;2349    collapseBtn.addEventListener("mousedown", (e) => {2350      e.preventDefault();2351      collapsed = !collapsed;2352      collapseBtn.classList.toggle("is-collapsed", collapsed);2353      rowsWrapper.classList.toggle("is-collapsed", collapsed);2354    });23552356    const rowsWrapper = list.appendChild(document.createElement("div"));2357    rowsWrapper.className = "identity-rows";2358    const rows = rowsWrapper.appendChild(document.createElement("div"));2359    rows.className = "identity-rows-inner";23602361    // Bottom fade only when the list actually overflows and isn't scrolled to2362    // the end — a static mask-image fades the last row even on a 1-2 item list2363    // that fits entirely, making it look cut off. Driven off live scroll state.2364    const updateRowsFade = () => {2365      const overflowing = rows.scrollHeight > rows.clientHeight + 1;2366      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;2367      const mask = overflowing && !atBottom2368        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"2369        : "none";2370      rows.style.setProperty("mask-image", mask);2371      rows.style.setProperty("-webkit-mask-image", mask);2372    };2373    rows.addEventListener("scroll", updateRowsFade);23742375    // Hides the list and removes the document-level click watcher.2376    function hideList() {2377      list.style.display = "none";2378      document.removeEventListener("mousedown", onDocMousedown, { capture: true });2379    }23802381    // Dismiss list on any mousedown that originates outside the popup's shadow2382    // DOM. This is the ONLY close trigger for the list — blur is intentionally2383    // NOT used, because modal focus traps fire blur without a mousedown (they2384    // call element.focus() programmatically in response to focusin/focusout),2385    // which caused the list to vanish before the user could pick from it.2386    function onDocMousedown(e: MouseEvent) {2387      if (e.composedPath().includes(host)) return;2388      hideList();2389    }23902391    function pick(value: string) {2392      inp.value = value;2393      hideList();2394      suppressNextFocus = true;2395      inp.focus();2396      // If a focus trap intercepts inp.focus() and redirects to anchorEl before2397      // inp ever fires its focus event, suppressNextFocus would strand the user.2398      // Clear after a short window so subsequent clicks still work.2399      setTimeout(() => { suppressNextFocus = false; }, 120);2400    }24012402    function render() {2403      const q = inp.value.toLowerCase();2404      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2405      rows.innerHTML = "";2406      if (!filtered.length) { hideList(); return; }2407      for (const s of filtered) {2408        const row = rows.appendChild(document.createElement("button"));2409        row.type = "button"; row.className = "identity-suggest-row";2410        const val = row.appendChild(document.createElement("span"));2411        val.className = "identity-suggest-val"; val.textContent = s.value;2412        const meta = row.appendChild(document.createElement("span"));2413        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2414        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2415        row.addEventListener("keydown", (e) => {2416          if (e.key === "ArrowDown") {2417            e.preventDefault();2418            (row.nextElementSibling as HTMLElement | null)?.focus();2419          } else if (e.key === "ArrowUp") {2420            e.preventDefault();2421            const prev = row.previousElementSibling as HTMLElement | null;2422            if (prev) prev.focus();2423            else inp.focus();2424          } else if (e.key === "Enter" || e.key === " ") {2425            e.preventDefault();2426            pick(s.value);2427          } else if (e.key === "Escape") {2428            e.preventDefault();2429            hideList();2430            suppressNextFocus = true;2431            inp.focus();2432          }2433        });2434        // Row blur only fires during keyboard navigation (arrow keys / Tab).2435        // Focus traps don't produce row blur events since rows aren't focused2436        // when the trap fires; this handler is therefore trap-safe.2437        row.addEventListener("blur", (e) => {2438          const rt = (e as FocusEvent).relatedTarget as Node | null;2439          if (rt && (rt === inp || list.contains(rt))) return;2440          setTimeout(() => { hideList(); }, 150);2441        });2442      }2443      list.style.display = "";2444      updateRowsFade();2445      // Register the close-on-outside-click watcher each time the list shows.2446      // addEventListener deduplicates identical (fn, options) pairs, so2447      // re-rendering on input events does not stack up listeners.2448      document.addEventListener("mousedown", onDocMousedown, { capture: true });2449    }24502451    inp.addEventListener("focus", () => {2452      if (suppressNextFocus) { suppressNextFocus = false; return; }2453      render();2454    });2455    inp.addEventListener("input", render);2456    inp.addEventListener("keydown", (e) => {2457      if (list.style.display === "none") return;2458      if (e.key === "ArrowDown" && !collapsed) {2459        e.preventDefault();2460        (rows.firstElementChild as HTMLElement | null)?.focus();2461      } else if (e.key === "Escape") {2462        e.preventDefault();2463        hideList();2464      } else if (e.key === "Tab") {2465        // Tab moves focus away intentionally — close the list.2466        hideList();2467      }2468    });2469    // No blur handler on inp. Blur fires for ANY focus movement including2470    // programmatic focus() calls from modal focus traps, which caused the list2471    // to close before the user could interact. The document mousedown listener2472    // (registered in render()) handles intentional click-outside dismissal,2473    // and the keydown handler above covers keyboard Tab/Escape.24742475    // Ensure the watcher is removed if the main popup is dismissed while the2476    // list is visible.2477    cleanupHooks.push(hideList);2478  }24792480  async function showCreateForm() {2481    currentMode = "create";2482    container.innerHTML = "";24832484    // Guard: the service worker may lock the vault between when the selector2485    // opens and when the user clicks "New entry". Show the inline unlock form2486    // instead of silently failing on save.2487    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2488    if (!statusRes?.unlocked) {2489      renderLocked();2490      return;2491    }24922493    // Detect page password policy once for this form — reused on every2494    // regenerate click so the user always gets a compliant password.2495    const sitePolicy = detectPasswordPolicy();24962497    const formIdentities = options.savedIdentities ?? [];24982499    const wrap = document.createElement("div");2500    wrap.className = "create-form-wrap";25012502    // Header2503    const head = document.createElement("div"); head.className = "create-head";2504    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2505    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>`;2506    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2507    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2508    head.append(backBtn, lbl);25092510    // Body2511    const body = document.createElement("div"); body.className = "create-body";25122513    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2514      const g = document.createElement("div"); g.className = "f-group";2515      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2516      const inp = document.createElement("input"); inp.className = "f-input";2517      g.append(l, inp); return { g, inp };2518    }25192520    // Title2521    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2522    body.appendChild(tg.g);25232524    // URL2525    const ug = fGroup("website");2526    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2527    if (loginSubdomain) {2528      const h = document.createElement("div"); h.className = "url-hint";2529      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2530    }2531    body.appendChild(ug.g);25322533    // Username — pre-fill from anchor if it doesn't look like an email2534    const xg = fGroup("username");2535    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2536    xg.inp.placeholder = "johndoe";2537    xg.inp.setAttribute("autocomplete", "off");2538    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2539    body.appendChild(xg.g);25402541    // Email — pre-fill from anchor if it looks like an email2542    const eg = fGroup("email");2543    (eg.inp as HTMLInputElement).type = "email";2544    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2545    eg.inp.placeholder = "[email protected]";2546    eg.inp.setAttribute("autocomplete", "off");2547    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2548    body.appendChild(eg.g);25492550    // Password — full smart generator with charset pills + length slider +2551    // policy hint. Mirrors the main UI's compact generator so users get the2552    // same controls inline as in the popup.2553    const pg = fGroup("password");2554    pg.inp.remove(); // smartGen provides its own display — no separate input needed2555    let currentPassword = prePassword || "";2556    const smartGen = createSmartGenerator({2557      policy: sitePolicy,2558      initialPassword: prePassword || undefined,2559      onChange: (pw) => { currentPassword = pw; },2560    });2561    pg.g.appendChild(smartGen.root);2562    body.appendChild(pg.g);25632564    // Save2565    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2566    saveBtn.textContent = "Save entry";2567    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2568    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2569    saveBtn.addEventListener("click", async () => {2570      const title = tg.inp.value.trim();2571      const pw = currentPassword.trim();2572      const username = xg.inp.value.trim();2573      const email = eg.inp.value.trim();2574      if (!title) {2575        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2576        showFormError("Entry needs a title");2577        return;2578      }2579      if (!pw) {2580        showFormError("Entry needs a password — tap regen to make one");2581        return;2582      }2583      errEl.style.display = "none";2584      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2585      try {2586        const res = await chrome.runtime.sendMessage({2587          type: "ADD_ENTRY",2588          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2589        });2590        if ((res as { ok?: boolean }).ok) {2591          // Fill the detected form. onFillFields uses whichever identity the2592          // page anchored on — the vault captures both username and email.2593          options.onFillFields?.(username || email, pw);2594          showSuccess(title);2595        } else {2596          const err = (res as { error?: string })?.error;2597          const errMsg = err === "vault_locked"2598            ? "Vault locked — open Peach to save"2599            : err === "STORAGE_QUOTA_EXCEEDED"2600              ? "Out of storage — open Peach → Settings to free space"2601              : err2602                ? `Could not save: ${err}`2603                : "Could not save entry";2604          showFormError(errMsg);2605          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2606        }2607      } catch (e) {2608        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2609        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2610      }2611    });2612    body.appendChild(saveBtn);2613    body.appendChild(errEl);26142615    wrap.append(head, body);2616    container.appendChild(wrap);2617    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2618  }26192620  function showSuccess(title: string) {2621    currentMode = "success";2622    container.innerHTML = "";2623    const wrap = document.createElement("div"); wrap.className = "success-wrap";2624    const ring = document.createElement("div"); ring.className = "success-ring";2625    ring.innerHTML = checkSvgStr();2626    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2627    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2628    wrap.append(ring, t, s);2629    container.appendChild(wrap);2630    setTimeout(() => dismiss(), 1600);2631  }26322633  function flashActionBtn(btn: HTMLButtonElement) {2634    btn.classList.add("flashed");2635    setTimeout(() => btn.classList.remove("flashed"), 700);2636  }26372638  // M3/QUA-005: when both the direct clipboard write and the background COPY2639  // fallback fail, briefly show the user that the copy did not happen.2640  function flashCopyError(btn: HTMLButtonElement) {2641    const original = btn.textContent ?? "";2642    btn.textContent = "Blocked";2643    btn.classList.add("flashed");2644    setTimeout(() => {2645      btn.classList.remove("flashed");2646      if (btn.isConnected) btn.textContent = original;2647    }, 1200);2648  }26492650  function renderSilverPlatter(entry: SelectorEntry) {2651    container.innerHTML = "";2652    searchInput = null;2653    focusedIndex = -1;2654    currentMode = "silver-platter";2655    silverPlatterOrigin = entry;26562657    const domHdr = document.createElement("div");2658    domHdr.className = "domain-header";2659    const headText = document.createElement("div");2660    headText.className = "domain-header-text";2661    const eyebrow = document.createElement("div");2662    eyebrow.className = "domain-eyebrow";2663    eyebrow.textContent = "Saved for this site";2664    const domName = document.createElement("div");2665    domName.className = "domain-name";2666    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2667    headText.append(eyebrow, domName);2668    domHdr.appendChild(headText);2669    if (!options.isSignup) {2670      const actions = document.createElement("div");2671      actions.className = "domain-header-actions";26722673      // Search shortcut — same idea as type-to-search below, but visible so2674      // the user can discover that another entry is reachable from a2675      // single-match platter. Sits to the left of the create button.2676      const searchBtn = document.createElement("button");2677      searchBtn.className = "domain-search-btn";2678      searchBtn.type = "button";2679      searchBtn.setAttribute("aria-label", "Search for a different entry");2680      searchBtn.title = "Search for a different entry";2681      searchBtn.innerHTML = searchSvgStr();2682      searchBtn.addEventListener("click", (e) => {2683        e.stopPropagation();2684        query = "";2685        renderList();2686      });2687      actions.appendChild(searchBtn);26882689      const addBtn = document.createElement("button");2690      addBtn.className = "domain-add-btn";2691      addBtn.type = "button";2692      addBtn.setAttribute("aria-label", "Create new entry");2693      addBtn.title = "Create new entry";2694      addBtn.textContent = "+";2695      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2696      actions.appendChild(addBtn);26972698      domHdr.appendChild(actions);2699    }2700    container.appendChild(domHdr);27012702    const platter = document.createElement("div");2703    platter.className = "silver-platter";2704    let capabilityActionClaimed = false;2705    const claimCapabilityAction = () => {2706      if (!options.capability) return true;2707      if (capabilityActionClaimed) return false;2708      capabilityActionClaimed = true;2709      return true;2710    };27112712    const titleEl = document.createElement("div");2713    titleEl.className = "sp-title";2714    titleEl.textContent = entry.title;2715    platter.appendChild(titleEl);27162717    if (entry.email) {2718      const emailEl = document.createElement("div");2719      emailEl.className = "sp-identity-row";2720      const emailLbl = document.createElement("span");2721      emailLbl.className = "sp-identity-label";2722      emailLbl.textContent = "email";2723      const emailVal = document.createElement("span");2724      emailVal.className = "sp-username";2725      emailVal.textContent = entry.email;2726      emailEl.append(emailLbl, emailVal);2727      platter.appendChild(emailEl);2728    }27292730    if (entry.username) {2731      const userEl = document.createElement("div");2732      userEl.className = "sp-identity-row";2733      const userLbl = document.createElement("span");2734      userLbl.className = "sp-identity-label";2735      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2736      const userVal = document.createElement("span");2737      userVal.className = "sp-username";2738      userVal.textContent = entry.username;2739      userEl.append(userLbl, userVal);2740      platter.appendChild(userEl);2741    }27422743    const fillBtn = document.createElement("button");2744    fillBtn.className = "sp-fill-btn";2745    fillBtn.type = "button";2746    fillBtn.textContent = "Fill credentials";2747    fillBtn.addEventListener("click", () => {2748      if (fillBtn.disabled || !claimCapabilityAction()) return;2749      fillBtn.disabled = true;2750      fillBtn.classList.add("filled");2751      fillBtn.innerHTML = checkSvgStr();2752      // Fire the fill, then exit via the standard exit animation. The fill2753      // itself is async (handled in index.ts) — by 400ms the form is filled2754      // and the popup begins its exit. Total dwell from click to host2755      // removal: 400ms + 130ms (exit animation) = 530ms.2756      onSelect(entry.id);2757      setTimeout(() => dismiss(), 400);2758    });2759    platter.appendChild(fillBtn);27602761    const actionsGroup = document.createElement("div");2762    actionsGroup.className = "sp-actions-group";2763    const actionsLabel = document.createElement("div");2764    actionsLabel.className = "sp-actions-label";2765    actionsLabel.textContent = "Copy";2766    actionsGroup.appendChild(actionsLabel);27672768    const actions = document.createElement("div");2769    actions.className = "sp-actions";2770    actionsGroup.appendChild(actions);27712772    if (entry.email) {2773      const copyEmail = document.createElement("button");2774      copyEmail.className = "sp-action-btn";2775      copyEmail.type = "button";2776      copyEmail.title = "Copy email";2777      copyEmail.textContent = "Email";2778      copyEmail.addEventListener("click", async (e) => {2779        e.stopPropagation();2780        let alreadyWritten = false;2781        try {2782          await navigator.clipboard.writeText(entry.email!);2783          alreadyWritten = true;2784        } catch (err) {2785          console.warn("[Peach] clipboard write denied:", err);2786        }2787        const resp = await chrome.runtime.sendMessage({2788          type: "COPY",2789          payload: { text: entry.email, label: "Email", alreadyWritten },2790        }).catch(() => null) as { ok?: boolean } | null;2791        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2792        else flashCopyError(copyEmail);2793      });2794      actions.appendChild(copyEmail);2795    }27962797    const copyU = document.createElement("button");2798    copyU.className = "sp-action-btn";2799    copyU.type = "button";2800    const usernameIsEmail = entry.username?.includes("@") ?? false;2801    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2802    copyU.textContent = usernameIsEmail ? "Email" : "Username";2803    copyU.disabled = !entry.username;2804    copyU.addEventListener("click", async (e) => {2805      e.stopPropagation();2806      if (!entry.username) return;2807      let alreadyWritten = false;2808      try {2809        await navigator.clipboard.writeText(entry.username);2810        alreadyWritten = true;2811      } catch (err) {2812        console.warn("[Peach] clipboard write denied:", err);2813      }2814      const resp = await chrome.runtime.sendMessage({2815        type: "COPY",2816        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2817      }).catch(() => null) as { ok?: boolean } | null;2818      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2819      else flashCopyError(copyU);2820    });2821    actions.appendChild(copyU);28222823    const copyP = document.createElement("button");2824    copyP.className = "sp-action-btn";2825    copyP.type = "button";2826    copyP.title = "Copy password";2827    copyP.textContent = "Password";2828    copyP.addEventListener("click", async (e) => {2829      e.stopPropagation();2830      if (!claimCapabilityAction()) return;2831      const resp = await chrome.runtime.sendMessage({2832        type: "GET_ENTRY_FOR_FILL",2833        payload: { id: entry.id, capability: options.capability },2834      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2835      if (!resp?.ok || !resp.data?.password) {2836        if (options.capability) dismiss();2837        return;2838      }2839      let alreadyWritten = false;2840      try {2841        await navigator.clipboard.writeText(resp.data.password);2842        alreadyWritten = true;2843      } catch (err) {2844        console.warn("[Peach] clipboard write denied:", err);2845      }2846      const copyResp = await chrome.runtime.sendMessage({2847        type: "COPY",2848        payload: { text: resp.data.password, label: "Password", alreadyWritten },2849      }).catch(() => null) as { ok?: boolean } | null;2850      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2851      else flashCopyError(copyP);2852      if (options.capability) dismiss();2853    });2854    actions.appendChild(copyP);28552856    let trayEl: HTMLDivElement | null = null;2857    let trayInterval: ReturnType<typeof setInterval> | null = null;28582859    function closeTray() {2860      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2861      trayEl?.remove();2862      trayEl = null;2863    }2864    // Register so dismiss() will close the tray and clear the interval2865    // even if the user dismisses without explicitly closing the tray.2866    cleanupHooks.push(closeTray);28672868    async function openTOTPTray() {2869      // Fetch the current TOTP code from the background. The raw base32 seed2870      // never enters the content script (SEV-3-C): we receive the live 6-digit2871      // code plus the seconds remaining, count down locally, and re-fetch a2872      // fresh code only when the 30s window rolls over.2873      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2874        const r = await chrome.runtime.sendMessage({2875          type: "GET_ENTRY_FOR_FILL",2876          payload: { id: entry.id, capability: options.capability },2877        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2878        if (!r?.ok || !r.data?.totpCode) return null;2879        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2880      }2881      let current = await fetchCode();2882      if (!current) return;28832884      trayEl = document.createElement("div");2885      trayEl.className = "sp-tray";28862887      const label = document.createElement("span");2888      label.className = "sp-tray-label";2889      label.textContent = "2FA";2890      trayEl.appendChild(label);28912892      const codeEl = document.createElement("div");2893      codeEl.className = "sp-totp-code";2894      trayEl.appendChild(codeEl);28952896      const ringNs = "http://www.w3.org/2000/svg";2897      const ring = document.createElementNS(ringNs, "svg");2898      ring.setAttribute("class", "sp-totp-ring");2899      ring.setAttribute("viewBox", "0 0 24 24");2900      const trackC = document.createElementNS(ringNs, "circle");2901      trackC.setAttribute("class", "ring-track");2902      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2903      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2904      const fillC = document.createElementNS(ringNs, "circle");2905      fillC.setAttribute("class", "ring-fill");2906      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2907      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2908      fillC.setAttribute("stroke-linecap", "round");2909      fillC.setAttribute("stroke-dasharray", "62.83");2910      ring.append(trackC, fillC);2911      trayEl.appendChild(ring);29122913      const copyBtn = document.createElement("button");2914      copyBtn.className = "sp-totp-copy";2915      copyBtn.type = "button";2916      copyBtn.textContent = "Copy";2917      trayEl.appendChild(copyBtn);29182919      function render() {2920        const { code, remaining } = current!;2921        // Group as "847 291" — easier to read than "847291"2922        codeEl.textContent = code.length === 62923          ? `${code.slice(0, 3)} ${code.slice(3)}`2924          : code;2925        // Ring fills counter-clockwise as time elapses: dashoffset goes from2926        // 0 (full ring) to 62.83 (empty) over the 30s window.2927        const fraction = (30 - remaining) / 30;2928        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2929      }2930      render();2931      trayInterval = setInterval(async () => {2932        if (!current) return;2933        current = { code: current.code, remaining: current.remaining - 1 };2934        // Window rolled over — pull a fresh code from the background.2935        if (current.remaining <= 0) {2936          const next = await fetchCode();2937          current = next ?? { code: current.code, remaining: 30 };2938        }2939        render();2940      }, 1000);29412942      copyBtn.addEventListener("click", async (e) => {2943        e.stopPropagation();2944        const code = current?.code;2945        if (!code) return;2946        let alreadyWritten = false;2947        try {2948          await navigator.clipboard.writeText(code);2949          alreadyWritten = true;2950        } catch (err) {2951          console.warn("[Peach] clipboard write denied:", err);2952        }2953        const resp = await chrome.runtime.sendMessage({2954          type: "COPY",2955          payload: { text: code, label: "TOTP", alreadyWritten },2956        }).catch(() => null) as { ok?: boolean } | null;2957        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2958        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2959      });29602961      platter.appendChild(trayEl);2962    }29632964    const editBtn = document.createElement("button");2965    editBtn.className = "sp-action-btn sp-action-edit";2966    editBtn.type = "button";2967    editBtn.title = "Edit entry";2968    editBtn.textContent = "Edit";2969    editBtn.addEventListener("click", (e) => {2970      e.stopPropagation();2971      closeTray();2972      void renderInlineEdit(entry);2973    });2974    actions.appendChild(editBtn);29752976    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2977    // "···" toggle was zero-savings (the toggle button took the same space2978    // the "2FA" label needed) and made the code one extra click away.2979    if (entry.hasTotp && !options.capability) void openTOTPTray();29802981    platter.appendChild(actionsGroup);2982    container.appendChild(platter);2983  }29842985  /** Raw TOTP seeds and password history stay inside the extension popup. */2986  async function renderInlineEdit(summary: SelectorEntry) {2987    await chrome.runtime.sendMessage({2988      type: "OPEN_POPUP",2989      payload: { entryId: summary.id },2990    }).catch(() => null);2991    dismiss();2992  }29932994  function renderLocked() {2995    container.innerHTML = "";29962997    // Domain header (same as list view)2998    const domHdr = document.createElement("div");2999    domHdr.className = "domain-header";3000    const eyebrow = document.createElement("div");3001    eyebrow.className = "domain-eyebrow";3002    eyebrow.textContent = "vault locked";3003    const domName = document.createElement("div");3004    domName.className = "domain-name";3005    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3006    domHdr.append(eyebrow, domName);3007    container.appendChild(domHdr);30083009    const wrap = document.createElement("div");3010    wrap.className = "locked-wrap";30113012    // Icon + label row3013    const head = document.createElement("div"); head.className = "locked-head";3014    const icon = document.createElement("div"); icon.className = "locked-icon";3015    icon.innerHTML = keySvgStr();3016    const title = document.createElement("div"); title.className = "locked-title";3017    title.textContent = "unlock to autofill";3018    head.append(icon, title);30193020    // The master password is NEVER collected in page-hosted DOM. A malicious3021    // page can observe keystrokes on the shared DOM event stream (a capture-3022    // phase listener registered before Peach injects sees every key before any3023    // stopImmediatePropagation), which would leak the vault's root secret3024    // (audit HIGH). Instead, route unlocking to the trusted extension popup,3025    // where keystrokes are isolated from the page. After the user unlocks3026    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill3027    // automatically (see content/index.ts), so the flow resumes on its own.3028    const sub = document.createElement("div");3029    sub.className = "locked-sub";3030    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";30313032    const openBtn = document.createElement("button");3033    openBtn.className = "locked-btn";3034    openBtn.type = "button";3035    openBtn.textContent = "Open Peach to unlock";3036    openBtn.addEventListener("click", () => {3037      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});3038      openBtn.textContent = "opening Peach…";3039      openBtn.disabled = true;3040      // openPopup() can't always open programmatically (browser/version/gesture3041      // limits); reset so the user can retry or click the toolbar icon.3042      setTimeout(() => {3043        if (openBtn.isConnected) {3044          openBtn.textContent = "Open Peach to unlock";3045          openBtn.disabled = false;3046        }3047      }, 2500);3048    });30493050    wrap.append(head, sub, openBtn);3051    container.appendChild(wrap);3052  }30533054  function handleKeyDown(e: KeyboardEvent) {3055    // PCH-01-007: reject page-synthesised KeyboardEvents — only genuine3056    // keystrokes may drive selection/fill. A page hosting an open selector could3057    // otherwise dispatch ArrowDown/Enter at `document` to fill without user intent.3058    if (!e.isTrusted) return;3059    if (options.locked) {3060      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3061      return;3062    }3063    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {3064      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3065      return;3066    }3067    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");3068    const count = allEntryEls.length;3069    const activeElement = shadow.activeElement ?? document.activeElement;3070    if (activeElement === searchInput) {3071      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }3072      if (count === 0) return;3073      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;3074    }3075    if (count === 0) return;3076    switch (e.key) {3077      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3078      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3079      case "Enter": {3080        if (focusedIndex >= 0) {3081          const el = allEntryEls[focusedIndex] as HTMLElement;3082          const id = el.dataset.id;3083          if (id) { onSelect(id); dismiss(); }3084          else if (el.classList.contains("is-new") || !id) {3085            // "New entry" row (last item, no data-id)3086            showCreateForm();3087          }3088        }3089        break;3090      }3091      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3092    }3093  }30943095  document.addEventListener("keydown", handleKeyDown);30963097  // Type-to-search from the silver platter. A printable single-character3098  // keystroke (no modifier) seeds the search query and switches into the3099  // list view, so the user can pivot to a different entry without first3100  // clicking the search icon. Capture phase so the anchor input does not3101  // receive the character before we hijack it.3102  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3103    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3104    if (currentMode !== "silver-platter") return;3105    if (e.ctrlKey || e.metaKey || e.altKey) return;3106    if (e.key.length !== 1) return;3107    e.preventDefault();3108    e.stopImmediatePropagation();3109    query = e.key;3110    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3111    void ensureSearchableLoaded(renderList);3112    renderList();3113  };3114  document.addEventListener("keydown", silverPlatterTypeHandler, true);3115  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));31163117  const identityHelperTypeHandler = (e: KeyboardEvent) => {3118    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3119    if (currentMode !== "identity-helper") return;3120    if (e.ctrlKey || e.metaKey || e.altKey) return;3121    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3122    if (active === searchInput) return;3123    if (3124      active instanceof HTMLInputElement ||3125      active instanceof HTMLTextAreaElement ||3126      (active instanceof HTMLElement && active.isContentEditable)3127    ) {3128      return;3129    }3130    if (e.key.length !== 1) return;3131    e.preventDefault();3132    e.stopImmediatePropagation();3133    query = e.key;3134    renderIdentityHelper();3135  };3136  document.addEventListener("keydown", identityHelperTypeHandler, true);3137  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));31383139  (modalAncestor ?? document.body).appendChild(host);31403141  // position:fixed normally resolves to the viewport, but an ancestor with3142  // transform / filter / backdrop-filter / perspective / contain / will-change3143  // establishes a containing block, so "fixed" then resolves to that ancestor's3144  // padding box instead. When the host is mounted inside such an ancestor (a3145  // modal) we subtract its border-box origin so the popup still lands at the3146  // field's true viewport position. At the document root there is no such3147  // ancestor and the offset is zero.3148  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3149    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3150    return (3151      has("transform") || has("perspective") || has("translate") ||3152      has("rotate") || has("scale") || has("filter") ||3153      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3154      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3155      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3156    );3157  }3158  function containingBlockOffset(): { dx: number; dy: number } {3159    let el: HTMLElement | null = host.parentElement;3160    while (el && el !== document.documentElement) {3161      const s = getComputedStyle(el);3162      if (establishesFixedContainingBlock(s)) {3163        const r = el.getBoundingClientRect();3164        return {3165          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3166          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3167        };3168      }3169      el = el.parentElement;3170    }3171    return { dx: 0, dy: 0 };3172  }31733174  function updatePosition() {3175    const r = anchorEl.getBoundingClientRect();3176    const { dx, dy } = containingBlockOffset();3177    host.style.top = `${r.bottom - dy + 5}px`;3178    host.style.left = `${r.left - dx}px`;3179    host.style.width = `${popupWidth}px`;3180  }3181  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3182  updatePosition();31833184  // observeAnchorPosition listens on window scroll, but a modal with its own3185  // internal scroll container doesn't move the window — track the modal's scroll3186  // too so the popup follows the field inside it.3187  if (modalAncestor) {3188    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3189    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3190  }31913192  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3193  // swap) removes the field without firing blur/click, so none of the normal3194  // dismiss triggers fire and the popup would otherwise linger over nothing.3195  const removalObserver = new MutationObserver(() => {3196    if (!document.contains(anchorEl)) dismiss();3197  });3198  removalObserver.observe(document.body, { childList: true, subtree: true });3199  cleanupHooks.push(() => removalObserver.disconnect());32003201  if (options.locked) {3202    renderLocked();3203  } else if (options.isSignup && options.savedIdentities) {3204    // State 10: identity helper — signup form detected, show derived3205    // identity list (emails then usernames) instead of vault entry list.3206    renderIdentityHelper();3207  } else if (entries.length === 1 && !options.isSignup) {3208    // Silver platter (State 1): single domain match → focused fill view.3209    // Multi-match goes through renderList instead.3210    renderSilverPlatter(entries[0]!);3211  } else {3212    renderList();3213  }32143215  let exitScheduled = false;3216  function dismiss(userAction = false) {3217    // Idempotent: dismiss() can be called from multiple paths (Escape,3218    // outside click, entry select, fill success, host page nav). The exit3219    // animation must only play once and host.remove() must run exactly once.3220    if (exitScheduled) return;3221    exitScheduled = true;3222    // Detach listeners synchronously so nothing can re-trigger during the3223    // 130ms exit window (a focusin firing here would race against the3224    // dismiss-lock work in Pass 2).3225    stopObserving();3226    document.removeEventListener("click", outsideClick, { capture: true });3227    document.removeEventListener("keydown", handleKeyDown);3228    for (const cleanup of cleanupHooks) {3229      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3230    }3231    if (userAction) options.onDismiss?.();3232    container.classList.add("is-exiting");3233    setTimeout(() => host.remove(), 130);3234  }32353236  function outsideClick(ev: MouseEvent) {3237    const path = ev.composedPath();3238    // Never dismiss when clicking the anchor field itself — that click is3239    // what triggered the selector to open, and the user may click the field3240    // again to re-focus it without intending to close the selector.3241    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3242  }3243  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3244  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);32453246  return dismiss;3247}32483249export function showTOTPSelector(3250  anchorEl: HTMLInputElement,3251  entries: SelectorEntry[],3252  onFill: (id: string) => void,3253  options: { domain?: string; onDismiss?: () => void } = {}3254): () => void {3255  const host = document.createElement("div");3256  host.style.cssText = "position: absolute; z-index: 2147483647;";3257  host.style.setProperty("--peach-accent", accentHex);3258  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3259  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3260  const shadow = host.attachShadow({ mode: "closed" });32613262  const style = shadow.appendChild(document.createElement("style"));3263  style.textContent = SELECTOR_STYLES;32643265  const rect = anchorEl.getBoundingClientRect();3266  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3267  host.style.left = `${rect.left + window.scrollX}px`;3268  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3269  host.style.width = `${popupWidth}px`;32703271  const container = shadow.appendChild(document.createElement("div"));3272  container.className = "peach-inline-popup";3273  container.setAttribute("data-theme", popupTheme);32743275  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3276  const current = entries.filter((entry) => entry.hasTotp);3277  let focusedIndex = current.length === 1 ? 0 : -1;32783279  function updatePosition() {3280    const r = anchorEl.getBoundingClientRect();3281    host.style.top = `${r.bottom + window.scrollY + 5}px`;3282    host.style.left = `${r.left + window.scrollX}px`;3283    host.style.width = `${popupWidth}px`;3284  }32853286  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);32873288  function choose(entry: SelectorEntry) {3289    onFill(entry.id);3290    dismiss();3291  }32923293  function render() {3294    container.innerHTML = "";32953296    const domHdr = document.createElement("div");3297    domHdr.className = "domain-header";3298    const headText = document.createElement("div");3299    headText.className = "domain-header-text";3300    const eyebrow = document.createElement("div");3301    eyebrow.className = "domain-eyebrow";3302    eyebrow.textContent = "2FA code";3303    const domName = document.createElement("div");3304    domName.className = "domain-name";3305    domName.textContent = domain;3306    headText.append(eyebrow, domName);3307    domHdr.appendChild(headText);3308    container.appendChild(domHdr);33093310    if (current.length === 1) {3311      const entry = current[0]!;3312      const platter = document.createElement("div");3313      platter.className = "silver-platter";33143315      const title = document.createElement("div");3316      title.className = "sp-title";3317      title.textContent = entry.title;3318      platter.appendChild(title);33193320      const sub = document.createElement("div");3321      sub.className = "sp-username";3322      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3323      platter.appendChild(sub);33243325      const fill = document.createElement("button");3326      fill.className = "sp-fill-btn";3327      fill.type = "button";3328      fill.textContent = "Fill 2FA code";3329      fill.addEventListener("click", () => choose(entry));3330      platter.appendChild(fill);33313332      container.appendChild(platter);3333      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3334      return;3335    }33363337    const results = document.createElement("div");3338    results.className = "results";3339    container.appendChild(results);33403341    for (let i = 0; i < current.length; i++) {3342      const entry = current[i]!;3343      const row = document.createElement("div");3344      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3345      row.dataset.index = String(i);3346      row.setAttribute("tabindex", "-1");33473348      const icon = document.createElement("div");3349      icon.className = "entry-icon";3350      icon.innerHTML = keySvgStr();3351      row.appendChild(icon);3352      const info = document.createElement("div");3353      info.className = "entry-info";3354      const title = document.createElement("div");3355      title.className = "entry-title";3356      title.textContent = entry.title;3357      const sub = document.createElement("div");3358      sub.className = "entry-sub";3359      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3360      info.append(title, sub);3361      row.appendChild(info);33623363      const badge = document.createElement("span");3364      badge.className = "totp-badge";3365      badge.textContent = "Fill";3366      row.appendChild(badge);3367      row.addEventListener("click", () => choose(entry));3368      results.appendChild(row);3369    }3370  }33713372  function setFocused(index: number) {3373    focusedIndex = index;3374    container.querySelectorAll(".entry").forEach((el, i) => {3375      el.classList.toggle("focused", i === focusedIndex);3376      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3377    });3378  }33793380  function handleKeyDown(e: KeyboardEvent) {3381    if (e.key === "Escape" || e.key === "Tab") {3382      e.preventDefault();3383      dismiss(true);3384      return;3385    }3386    if (current.length === 0) return;3387    if (e.key === "Enter") {3388      e.preventDefault();3389      choose(current[Math.max(0, focusedIndex)]!);3390      return;3391    }3392    if (current.length === 1) return;3393    if (e.key === "ArrowDown") {3394      e.preventDefault();3395      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3396    } else if (e.key === "ArrowUp") {3397      e.preventDefault();3398      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3399    }3400  }34013402  let exitScheduled = false;3403  function dismiss(userAction = false) {3404    if (exitScheduled) return;3405    exitScheduled = true;3406    stopObserving();3407    document.removeEventListener("click", outsideClick, { capture: true });3408    document.removeEventListener("keydown", handleKeyDown);3409    if (userAction) options.onDismiss?.();3410    container.classList.add("is-exiting");3411    setTimeout(() => host.remove(), 130);3412  }34133414  function outsideClick(ev: MouseEvent) {3415    const path = ev.composedPath();3416    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3417  }34183419  document.addEventListener("keydown", handleKeyDown);3420  document.body.appendChild(host);3421  render();3422  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);34233424  return dismiss;3425}34263427export interface CardSelectorEntry {3428  id: string;3429  title: string;3430  cardholderName?: string;3431  last4?: string;3432  expMonth?: string;3433  expYear?: string;3434  network?: import("../shared/types").CardNetwork;3435}34363437interface CardSelectorOptions {3438  domain?: string;3439  capability?: string;3440  /** Caller-provided fill — receives the full card payload from the SW. */3441  onFill: (entry: import("../shared/types").VaultEntry) => void;3442  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3443  onDismiss?: () => void;3444}34453446/**3447 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3448 * passkey create or get. Renders as a fixed-position floating popup (no3449 * field anchor needed — passkeys don't require a focused input). Uses the3450 * same theme tokens and entrance animation as all other inline popup states.3451 */3452export function showPasskeyProGate(): void {3453  const domain = location.hostname.replace(/^www\./, "");34543455  const host = document.createElement("div");3456  host.setAttribute("data-peach-passkey-gate", "1");3457  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3458  const shadow = host.attachShadow({ mode: "closed" });34593460  const style = document.createElement("style");3461  style.textContent = `3462    :host { all: initial; }3463    .gate-wrap {3464      position: fixed;3465      top: 50%;3466      left: 50%;3467      transform: translate(-50%, -50%);3468      width: 280px;3469      pointer-events: auto;3470      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3471    }3472    @keyframes g-in {3473      from { opacity:0; transform: translate(-50%,-52%); }3474      to   { opacity:1; transform: translate(-50%,-50%); }3475    }3476    .gate-wrap.is-exiting {3477      animation: g-out 130ms ease-in forwards;3478    }3479    @keyframes g-out {3480      to { opacity:0; transform: translate(-50%,-52%); }3481    }3482    .gate {3483      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3484      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3485      border-radius: 12px;3486      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3487      padding: 16px;3488      font-family: Inter, sans-serif;3489    }3490    .gate-header {3491      display: flex;3492      align-items: center;3493      gap: 7px;3494      margin-bottom: 12px;3495      padding-bottom: 10px;3496      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3497    }3498    .gate-domain {3499      font-size: 12px;3500      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3501      font-family: "IBM Plex Mono", monospace;3502      overflow: hidden;3503      text-overflow: ellipsis;3504      white-space: nowrap;3505    }3506    .gate-title {3507      font-size: 14px;3508      font-weight: 500;3509      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3510      margin-bottom: 6px;3511    }3512    .gate-subtitle {3513      font-size: 12px;3514      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3515      line-height: 1.5;3516      margin-bottom: 14px;3517    }3518    .gate-btn {3519      display: block;3520      width: 100%;3521      padding: 9px 0;3522      border-radius: 8px;3523      border: none;3524      cursor: pointer;3525      font-size: 13px;3526      font-family: Inter, sans-serif;3527      font-weight: 500;3528      transition: opacity 100ms;3529      margin-bottom: 7px;3530      text-align: center;3531    }3532    .gate-btn:last-child { margin-bottom: 0; }3533    .gate-btn--accent {3534      background: ${accentHex};3535      color: #fff;3536    }3537    .gate-btn--accent:hover { opacity: 0.88; }3538    .gate-btn--ghost {3539      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3540      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3541    }3542    .gate-btn--ghost:hover { opacity: 0.75; }3543    .backdrop {3544      position: fixed;3545      inset: 0;3546      pointer-events: auto;3547    }3548  `;3549  shadow.appendChild(style);35503551  const backdrop = document.createElement("div");3552  backdrop.className = "backdrop";3553  shadow.appendChild(backdrop);35543555  const wrap = document.createElement("div");3556  wrap.className = "gate-wrap";3557  shadow.appendChild(wrap);35583559  const gate = document.createElement("div");3560  gate.className = "gate";3561  wrap.appendChild(gate);35623563  // Header: peach icon + domain3564  const header = document.createElement("div");3565  header.className = "gate-header";3566  const icon = document.createElement("span");3567  icon.innerHTML = peachIconSvg();3568  const domainEl = document.createElement("span");3569  domainEl.className = "gate-domain";3570  domainEl.textContent = domain;3571  header.append(icon, domainEl);3572  gate.appendChild(header);35733574  const title = document.createElement("div");3575  title.className = "gate-title";3576  title.textContent = "Passkeys are part of Peach Pro.";3577  gate.appendChild(title);35783579  const subtitle = document.createElement("div");3580  subtitle.className = "gate-subtitle";3581  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3582  gate.appendChild(subtitle);35833584  const upgradeBtn = document.createElement("button");3585  upgradeBtn.className = "gate-btn gate-btn--accent";3586  upgradeBtn.type = "button";3587  upgradeBtn.textContent = "Upgrade to Pro";3588  gate.appendChild(upgradeBtn);35893590  const laterBtn = document.createElement("button");3591  laterBtn.className = "gate-btn gate-btn--ghost";3592  laterBtn.type = "button";3593  laterBtn.textContent = "Not right now";3594  gate.appendChild(laterBtn);35953596  function dismiss() {3597    wrap.classList.add("is-exiting");3598    setTimeout(() => host.remove(), 130);3599  }36003601  upgradeBtn.addEventListener("click", () => {3602    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3603    dismiss();3604  });3605  laterBtn.addEventListener("click", dismiss);3606  backdrop.addEventListener("click", dismiss);36073608  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3609    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3610  });36113612  document.body.appendChild(host);3613}36143615/**3616 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3617 * detector sees the page invoke navigator.credentials.create(); content/index.ts3618 * checks vault + decline state then calls this. "Save passkey to Peach"3619 * initiates the popup-context credential flow; "Not now" records a 30-day3620 * decline for the domain so we don't re-show on every page reload.3621 */3622export function showPasskeyRegistrationOffer(args: {3623  rpId: string;3624  rpName?: string;3625  userName?: string;3626  userDisplayName?: string;3627}): void {3628  const domain = location.hostname.replace(/^www\./, "");3629  const displayName = args.rpName || domain;36303631  const host = document.createElement("div");3632  host.setAttribute("data-peach-passkey-offer", "1");3633  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3634  const shadow = host.attachShadow({ mode: "closed" });36353636  const style = document.createElement("style");3637  style.textContent = `3638    :host { all: initial; }3639    .offer-wrap {3640      position: fixed;3641      top: 16px;3642      right: 16px;3643      width: 320px;3644      pointer-events: auto;3645      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3646    }3647    @keyframes o-in {3648      from { opacity: 0; transform: translateY(-6px); }3649      to   { opacity: 1; transform: translateY(0); }3650    }3651    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3652    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3653    .offer {3654      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3655      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3656      border-radius: 12px;3657      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3658      padding: 14px 14px 12px;3659      font-family: Inter, sans-serif;3660      position: relative;3661    }3662    .offer-close {3663      position: absolute;3664      top: 8px;3665      right: 8px;3666      width: 18px;3667      height: 18px;3668      border: none;3669      background: transparent;3670      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3671      cursor: pointer;3672      font-size: 14px;3673      line-height: 1;3674      padding: 0;3675    }3676    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3677    .offer-header {3678      display: flex;3679      align-items: center;3680      gap: 7px;3681      margin-bottom: 8px;3682      padding-bottom: 8px;3683      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3684    }3685    .offer-domain {3686      font-size: 12px;3687      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3688      font-family: "IBM Plex Mono", monospace;3689      overflow: hidden;3690      text-overflow: ellipsis;3691      white-space: nowrap;3692    }3693    .offer-title {3694      font-size: 13px;3695      font-weight: 500;3696      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3697      margin-bottom: 4px;3698    }3699    .offer-subtitle {3700      font-size: 11px;3701      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3702      line-height: 1.45;3703      margin-bottom: 12px;3704    }3705    .offer-btn {3706      display: block;3707      width: 100%;3708      padding: 8px 0;3709      border-radius: 7px;3710      border: none;3711      cursor: pointer;3712      font-size: 12px;3713      font-family: Inter, sans-serif;3714      font-weight: 500;3715      transition: opacity 100ms;3716      margin-bottom: 6px;3717      text-align: center;3718    }3719    .offer-btn:last-child { margin-bottom: 0; }3720    .offer-btn--accent { background: ${accentHex}; color: #fff; }3721    .offer-btn--accent:hover { opacity: 0.88; }3722    .offer-btn--ghost {3723      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3724      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3725    }3726    .offer-btn--ghost:hover { opacity: 0.75; }3727  `;3728  shadow.appendChild(style);37293730  const wrap = document.createElement("div");3731  wrap.className = "offer-wrap";3732  shadow.appendChild(wrap);37333734  const offer = document.createElement("div");3735  offer.className = "offer";3736  wrap.appendChild(offer);37373738  const closeBtn = document.createElement("button");3739  closeBtn.className = "offer-close";3740  closeBtn.type = "button";3741  closeBtn.setAttribute("aria-label", "Dismiss");3742  closeBtn.textContent = "✕";3743  offer.appendChild(closeBtn);37443745  const header = document.createElement("div");3746  header.className = "offer-header";3747  const icon = document.createElement("span");3748  icon.innerHTML = peachIconSvg();3749  const domainEl = document.createElement("span");3750  domainEl.className = "offer-domain";3751  domainEl.textContent = domain;3752  header.append(icon, domainEl);3753  offer.appendChild(header);37543755  const title = document.createElement("div");3756  title.className = "offer-title";3757  title.textContent = "This site supports passkeys.";3758  offer.appendChild(title);37593760  const subtitle = document.createElement("div");3761  subtitle.className = "offer-subtitle";3762  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3763  offer.appendChild(subtitle);37643765  const saveBtn = document.createElement("button");3766  saveBtn.className = "offer-btn offer-btn--accent";3767  saveBtn.type = "button";3768  saveBtn.textContent = "Save passkey to Peach";3769  offer.appendChild(saveBtn);37703771  const laterBtn = document.createElement("button");3772  laterBtn.className = "offer-btn offer-btn--ghost";3773  laterBtn.type = "button";3774  laterBtn.textContent = "Not now";3775  offer.appendChild(laterBtn);37763777  function dismiss(decline: boolean) {3778    if (decline) {3779      chrome.runtime.sendMessage({3780        type: "PASSKEY_OFFER_DECLINE",3781        payload: { domain },3782      }).catch(() => {});3783    }3784    wrap.classList.add("is-exiting");3785    setTimeout(() => host.remove(), 130);3786  }37873788  saveBtn.addEventListener("click", () => {3789    chrome.runtime.sendMessage({3790      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3791      payload: {3792        rpId: args.rpId,3793        rpName: args.rpName ?? displayName,3794        userName: args.userName ?? "user",3795        userDisplayName: args.userDisplayName,3796      },3797    }).catch(() => {});3798    dismiss(false);3799  });3800  laterBtn.addEventListener("click", () => dismiss(true));3801  closeBtn.addEventListener("click", () => dismiss(true));38023803  document.body.appendChild(host);3804}38053806/**3807 * State 11 — passkey available indicator. Shown when the user lands on a3808 * domain for which they already have a stored passkey. Tells them where to3809 * find it (the entry already shows in the vault list); the "Sign in with3810 * passkey" button opens the popup so they can use the platform authenticator3811 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3812 * the actual sign-in transparently, so this banner is informational only.3813 */3814export function showPasskeyAvailable(args: {3815  rpId: string;3816  userName: string;3817  fromBrowser?: "chrome" | "firefox";3818  currentBrowser?: "chrome" | "firefox" | "unknown";3819}): void {3820  const domain = location.hostname.replace(/^www\./, "");3821  const crossBrowser =3822    args.fromBrowser &&3823    args.currentBrowser &&3824    args.currentBrowser !== "unknown" &&3825    args.fromBrowser !== args.currentBrowser;38263827  const host = document.createElement("div");3828  host.setAttribute("data-peach-passkey-available", "1");3829  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3830  const shadow = host.attachShadow({ mode: "closed" });38313832  const style = document.createElement("style");3833  style.textContent = `3834    :host { all: initial; }3835    .avail-wrap {3836      position: fixed;3837      top: 16px;3838      right: 16px;3839      width: 320px;3840      pointer-events: auto;3841      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3842    }3843    @keyframes a-in {3844      from { opacity: 0; transform: translateY(-6px); }3845      to   { opacity: 1; transform: translateY(0); }3846    }3847    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3848    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3849    .avail {3850      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3851      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3852      border-radius: 12px;3853      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3854      padding: 14px 14px 12px;3855      font-family: Inter, sans-serif;3856      position: relative;3857    }3858    .avail-close {3859      position: absolute;3860      top: 8px;3861      right: 8px;3862      width: 18px;3863      height: 18px;3864      border: none;3865      background: transparent;3866      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3867      cursor: pointer;3868      font-size: 14px;3869      line-height: 1;3870      padding: 0;3871    }3872    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3873    .avail-header {3874      display: flex;3875      align-items: center;3876      gap: 7px;3877      margin-bottom: 8px;3878      padding-bottom: 8px;3879      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3880    }3881    .avail-domain {3882      font-size: 12px;3883      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3884      font-family: "IBM Plex Mono", monospace;3885    }3886    .avail-label {3887      font-size: 9px;3888      letter-spacing: 0.16em;3889      text-transform: uppercase;3890      color: ${accentHex};3891      margin-bottom: 4px;3892    }3893    .avail-user {3894      font-size: 13px;3895      font-weight: 500;3896      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3897      margin-bottom: 12px;3898      overflow: hidden;3899      text-overflow: ellipsis;3900      white-space: nowrap;3901    }3902    .avail-cross {3903      font-size: 11px;3904      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3905      line-height: 1.45;3906      margin-bottom: 12px;3907      padding: 8px;3908      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3909      border-radius: 6px;3910    }3911    .avail-btn {3912      display: block;3913      width: 100%;3914      padding: 8px 0;3915      border-radius: 7px;3916      border: none;3917      cursor: pointer;3918      font-size: 12px;3919      font-family: Inter, sans-serif;3920      font-weight: 500;3921      transition: opacity 100ms;3922      margin-bottom: 6px;3923      text-align: center;3924    }3925    .avail-btn:last-child { margin-bottom: 0; }3926    .avail-btn--accent { background: ${accentHex}; color: #fff; }3927    .avail-btn--accent:hover { opacity: 0.88; }3928    .avail-btn--ghost {3929      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3930      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3931    }3932    .avail-btn--ghost:hover { opacity: 0.75; }3933  `;3934  shadow.appendChild(style);39353936  const wrap = document.createElement("div");3937  wrap.className = "avail-wrap";3938  shadow.appendChild(wrap);39393940  const avail = document.createElement("div");3941  avail.className = "avail";3942  wrap.appendChild(avail);39433944  const closeBtn = document.createElement("button");3945  closeBtn.className = "avail-close";3946  closeBtn.type = "button";3947  closeBtn.setAttribute("aria-label", "Dismiss");3948  closeBtn.textContent = "✕";3949  avail.appendChild(closeBtn);39503951  const header = document.createElement("div");3952  header.className = "avail-header";3953  const icon = document.createElement("span");3954  icon.innerHTML = peachIconSvg();3955  const domainEl = document.createElement("span");3956  domainEl.className = "avail-domain";3957  domainEl.textContent = domain;3958  header.append(icon, domainEl);3959  avail.appendChild(header);39603961  const label = document.createElement("div");3962  label.className = "avail-label";3963  label.textContent = "PASSKEY";3964  avail.appendChild(label);39653966  const user = document.createElement("div");3967  user.className = "avail-user";3968  user.textContent = args.userName;3969  avail.appendChild(user);39703971  if (crossBrowser) {3972    const cross = document.createElement("div");3973    cross.className = "avail-cross";3974    cross.textContent =3975      args.fromBrowser === "chrome"3976        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3977        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3978    avail.appendChild(cross);3979  }39803981  const signInBtn = document.createElement("button");3982  signInBtn.className = "avail-btn avail-btn--accent";3983  signInBtn.type = "button";3984  signInBtn.textContent = "Sign in with passkey";3985  avail.appendChild(signInBtn);39863987  const passwordBtn = document.createElement("button");3988  passwordBtn.className = "avail-btn avail-btn--ghost";3989  passwordBtn.type = "button";3990  passwordBtn.textContent = "Use password instead";3991  avail.appendChild(passwordBtn);39923993  function dismiss() {3994    wrap.classList.add("is-exiting");3995    setTimeout(() => host.remove(), 130);3996  }39973998  signInBtn.addEventListener("click", () => {3999    // On Chrome: the user clicking the page's own Sign-in button is what4000    //   triggers webAuthenticationProxy → existing background flow handles it.4001    //   Our button just dismisses since the page itself drives auth.4002    // On Firefox: cross-browser passkeys can't be used, so we just dismiss4003    //   and surface the entry for manual reference (popup view).4004    dismiss();4005    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});4006  });4007  passwordBtn.addEventListener("click", dismiss);4008  closeBtn.addEventListener("click", dismiss);40094010  document.body.appendChild(host);4011}40124013/**4014 * State 7 — card silver platter. Single-card focused fill view rendered4015 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the4016 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes4017 * so card and login flows render identically. Multi-card list view is a4018 * follow-up; today this picks the first card.4019 */4020export function showCardSelector(4021  anchorEl: HTMLInputElement,4022  cards: CardSelectorEntry[],4023  options: CardSelectorOptions4024): () => void {4025  if (cards.length === 0) return () => {};4026  const card = cards[0]!;4027  let capabilityActionClaimed = false;4028  const claimCapabilityAction = () => {4029    if (!options.capability) return true;4030    if (capabilityActionClaimed) return false;4031    capabilityActionClaimed = true;4032    return true;4033  };40344035  const host = document.createElement("div");4036  host.style.cssText = "position: absolute; z-index: 2147483647;";4037  host.style.setProperty("--peach-accent", accentHex);4038  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));4039  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));4040  const shadow = host.attachShadow({ mode: "closed" });40414042  const style = shadow.appendChild(document.createElement("style"));4043  style.textContent = SELECTOR_STYLES;40444045  const rect = anchorEl.getBoundingClientRect();4046  host.style.top = `${rect.bottom + window.scrollY + 5}px`;4047  host.style.left = `${rect.left + window.scrollX}px`;4048  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;40494050  const container = shadow.appendChild(document.createElement("div"));4051  container.className = "peach-inline-popup";4052  container.setAttribute("data-theme", popupTheme);40534054  // Domain header — eyebrow communicates the card context, not the site4055  const domHdr = document.createElement("div");4056  domHdr.className = "domain-header";4057  const eyebrow = document.createElement("div");4058  eyebrow.className = "domain-eyebrow";4059  eyebrow.textContent = "Pay with Peach";4060  const domName = document.createElement("div");4061  domName.className = "domain-name";4062  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");4063  domHdr.append(eyebrow, domName);4064  container.appendChild(domHdr);40654066  const platter = document.createElement("div");4067  platter.className = "card-platter";40684069  if (card.network && card.network !== "unknown") {4070    const net = document.createElement("div");4071    net.className = "cp-network";4072    net.textContent = card.network;4073    platter.appendChild(net);4074  }40754076  const nick = document.createElement("div");4077  nick.className = "cp-nickname";4078  nick.textContent = card.title;4079  platter.appendChild(nick);40804081  if (card.last4) {4082    const l4 = document.createElement("div");4083    l4.className = "cp-last4";4084    l4.textContent = `•••• ${card.last4}`;4085    platter.appendChild(l4);4086  }40874088  const meta = document.createElement("div");4089  meta.className = "cp-meta";4090  if (card.cardholderName) {4091    const name = document.createElement("span");4092    name.textContent = card.cardholderName;4093    meta.appendChild(name);4094  }4095  if (card.expMonth && card.expYear) {4096    if (card.cardholderName) {4097      const sep = document.createElement("span");4098      sep.className = "cp-meta-sep";4099      sep.textContent = "·";4100      meta.appendChild(sep);4101    }4102    const exp = document.createElement("span");4103    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4104    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4105    meta.appendChild(exp);4106  }4107  if (meta.childElementCount > 0) platter.appendChild(meta);41084109  const fillWrap = document.createElement("div");4110  fillWrap.className = "cp-fill-wrap";4111  const fillBtn = document.createElement("button");4112  fillBtn.className = "sp-fill-btn";4113  fillBtn.type = "button";4114  fillBtn.textContent = "Fill card details";4115  fillBtn.addEventListener("click", async () => {4116    if (fillBtn.disabled || !claimCapabilityAction()) return;4117    fillBtn.disabled = true;4118    fillBtn.classList.add("filled");4119    fillBtn.innerHTML = checkSvgStr();4120    const resp = await chrome.runtime.sendMessage({4121      type: "GET_ENTRY_FOR_FILL",4122      // MV-1: explicit user click to fill this card's details.4123      payload: { id: card.id, capability: options.capability },4124    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4125    if (resp?.ok && resp.data) options.onFill(resp.data);4126    setTimeout(() => dismiss(), 400);4127  });4128  fillWrap.appendChild(fillBtn);4129  platter.appendChild(fillWrap);41304131  // Secondary actions — copy number, copy CVC, dismiss4132  const actions = document.createElement("div");4133  actions.className = "sp-actions";41344135  function flashBtn(b: HTMLButtonElement) {4136    b.classList.add("flashed");4137    setTimeout(() => b.classList.remove("flashed"), 700);4138  }41394140  // M3/QUA-005: clipboard + background COPY both failed — show user.4141  function flashCopyError(b: HTMLButtonElement) {4142    const original = b.textContent ?? "";4143    b.textContent = "Blocked";4144    b.classList.add("flashed");4145    setTimeout(() => {4146      b.classList.remove("flashed");4147      if (b.isConnected) b.textContent = original;4148    }, 1200);4149  }41504151  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4152    if (!claimCapabilityAction()) return null;4153    const resp = await chrome.runtime.sendMessage({4154      type: "GET_ENTRY_FOR_FILL",4155      // MV-1: explicit user action on a card the user opened in Peach's UI.4156      payload: { id: card.id, capability: options.capability },4157    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4158    const full = resp?.ok && resp.data ? resp.data : null;4159    if (options.capability) dismiss();4160    return full;4161  }41624163  const copyNum = document.createElement("button");4164  copyNum.className = "sp-action-btn";4165  copyNum.type = "button";4166  copyNum.title = "Copy card number";4167  copyNum.textContent = "Copy number";4168  copyNum.addEventListener("click", async (e) => {4169    e.stopPropagation();4170    const full = await fetchFullCard();4171    if (!full?.cardNumber) return;4172    let alreadyWritten = false;4173    try {4174      await navigator.clipboard.writeText(full.cardNumber);4175      alreadyWritten = true;4176    } catch (err) {4177      console.warn("[Peach] clipboard write denied:", err);4178    }4179    const resp = await chrome.runtime.sendMessage({4180      type: "COPY",4181      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4182    }).catch(() => null) as { ok?: boolean } | null;4183    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4184    else flashCopyError(copyNum);4185  });4186  actions.appendChild(copyNum);41874188  const copyCvc = document.createElement("button");4189  copyCvc.className = "sp-action-btn";4190  copyCvc.type = "button";4191  copyCvc.title = "Copy CVC";4192  copyCvc.textContent = "Copy CVC";4193  copyCvc.addEventListener("click", async (e) => {4194    e.stopPropagation();4195    const full = await fetchFullCard();4196    if (!full?.cvc) return;4197    let alreadyWritten = false;4198    try {4199      await navigator.clipboard.writeText(full.cvc);4200      alreadyWritten = true;4201    } catch (err) {4202      console.warn("[Peach] clipboard write denied:", err);4203    }4204    const resp = await chrome.runtime.sendMessage({4205      type: "COPY",4206      payload: { text: full.cvc, label: "CVC", alreadyWritten },4207    }).catch(() => null) as { ok?: boolean } | null;4208    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4209    else flashCopyError(copyCvc);4210  });4211  actions.appendChild(copyCvc);42124213  const closeBtn = document.createElement("button");4214  closeBtn.className = "sp-action-btn";4215  closeBtn.type = "button";4216  closeBtn.title = "Dismiss";4217  closeBtn.textContent = "✕";4218  closeBtn.addEventListener("click", (e) => {4219    e.stopPropagation();4220    dismiss(true);4221  });4222  actions.appendChild(closeBtn);42234224  platter.appendChild(actions);4225  container.appendChild(platter);42264227  document.body.appendChild(host);4228  function updatePosition() {4229    const r = anchorEl.getBoundingClientRect();4230    host.style.top = `${r.bottom + window.scrollY + 5}px`;4231    host.style.left = `${r.left + window.scrollX}px`;4232  }4233  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);42344235  function onKeyDown(e: KeyboardEvent) {4236    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4237  }4238  document.addEventListener("keydown", onKeyDown);42394240  let exitScheduled = false;4241  function dismiss(userAction = false) {4242    if (exitScheduled) return;4243    exitScheduled = true;4244    stopObserving();4245    document.removeEventListener("click", outsideClick, { capture: true });4246    document.removeEventListener("keydown", onKeyDown);4247    if (userAction) options.onDismiss?.();4248    container.classList.add("is-exiting");4249    setTimeout(() => host.remove(), 130);4250  }42514252  function outsideClick(ev: MouseEvent) {4253    const path = ev.composedPath();4254    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4255  }4256  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);42574258  return dismiss;4259}