inject.ts

176.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    // Detect page password policy once for this form — reused on every2485    // regenerate click so the user always gets a compliant password.2486    const sitePolicy = detectPasswordPolicy();24872488    const formIdentities = options.savedIdentities ?? [];24892490    const wrap = document.createElement("div");2491    wrap.className = "create-form-wrap";24922493    // Header2494    const head = document.createElement("div"); head.className = "create-head";2495    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2496    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>`;2497    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2498    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2499    head.append(backBtn, lbl);25002501    // Body2502    const body = document.createElement("div"); body.className = "create-body";25032504    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2505      const g = document.createElement("div"); g.className = "f-group";2506      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2507      const inp = document.createElement("input"); inp.className = "f-input";2508      g.append(l, inp); return { g, inp };2509    }25102511    // Title2512    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2513    body.appendChild(tg.g);25142515    // URL2516    const ug = fGroup("website");2517    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2518    if (loginSubdomain) {2519      const h = document.createElement("div"); h.className = "url-hint";2520      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2521    }2522    body.appendChild(ug.g);25232524    // Username — pre-fill from anchor if it doesn't look like an email2525    const xg = fGroup("username");2526    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2527    xg.inp.placeholder = "johndoe";2528    xg.inp.setAttribute("autocomplete", "off");2529    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2530    body.appendChild(xg.g);25312532    // Email — pre-fill from anchor if it looks like an email2533    const eg = fGroup("email");2534    (eg.inp as HTMLInputElement).type = "email";2535    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2536    eg.inp.placeholder = "[email protected]";2537    eg.inp.setAttribute("autocomplete", "off");2538    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2539    body.appendChild(eg.g);25402541    // Password — full smart generator with charset pills + length slider +2542    // policy hint. Mirrors the main UI's compact generator so users get the2543    // same controls inline as in the popup.2544    const pg = fGroup("password");2545    pg.inp.remove(); // smartGen provides its own display — no separate input needed2546    let currentPassword = prePassword || "";2547    const smartGen = createSmartGenerator({2548      policy: sitePolicy,2549      initialPassword: prePassword || undefined,2550      onChange: (pw) => { currentPassword = pw; },2551    });2552    pg.g.appendChild(smartGen.root);2553    body.appendChild(pg.g);25542555    // Save2556    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2557    saveBtn.textContent = "Save entry";2558    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2559    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2560    saveBtn.addEventListener("click", async () => {2561      const title = tg.inp.value.trim();2562      const pw = currentPassword.trim();2563      const username = xg.inp.value.trim();2564      const email = eg.inp.value.trim();2565      if (!title) {2566        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2567        showFormError("Entry needs a title");2568        return;2569      }2570      if (!pw) {2571        showFormError("Entry needs a password — tap regen to make one");2572        return;2573      }2574      errEl.style.display = "none";2575      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2576      try {2577        const res = await chrome.runtime.sendMessage({2578          type: "ADD_ENTRY",2579          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2580        });2581        if ((res as { ok?: boolean }).ok) {2582          // Fill the detected form. onFillFields uses whichever identity the2583          // page anchored on — the vault captures both username and email.2584          options.onFillFields?.(username || email, pw);2585          showSuccess(title);2586        } else {2587          const err = (res as { error?: string })?.error;2588          const errMsg = err === "vault_locked"2589            ? "Vault locked — open Peach to save"2590            : err === "STORAGE_QUOTA_EXCEEDED"2591              ? "Out of storage — open Peach → Settings to free space"2592              : err2593                ? `Could not save: ${err}`2594                : "Could not save entry";2595          showFormError(errMsg);2596          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2597        }2598      } catch (e) {2599        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2600        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2601      }2602    });2603    body.appendChild(saveBtn);2604    body.appendChild(errEl);26052606    wrap.append(head, body);2607    container.appendChild(wrap);2608    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2609  }26102611  function showSuccess(title: string) {2612    currentMode = "success";2613    container.innerHTML = "";2614    const wrap = document.createElement("div"); wrap.className = "success-wrap";2615    const ring = document.createElement("div"); ring.className = "success-ring";2616    ring.innerHTML = checkSvgStr();2617    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2618    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2619    wrap.append(ring, t, s);2620    container.appendChild(wrap);2621    setTimeout(() => dismiss(), 1600);2622  }26232624  function flashActionBtn(btn: HTMLButtonElement) {2625    btn.classList.add("flashed");2626    setTimeout(() => btn.classList.remove("flashed"), 700);2627  }26282629  // M3/QUA-005: when both the direct clipboard write and the background COPY2630  // fallback fail, briefly show the user that the copy did not happen.2631  function flashCopyError(btn: HTMLButtonElement) {2632    const original = btn.textContent ?? "";2633    btn.textContent = "Blocked";2634    btn.classList.add("flashed");2635    setTimeout(() => {2636      btn.classList.remove("flashed");2637      if (btn.isConnected) btn.textContent = original;2638    }, 1200);2639  }26402641  function renderSilverPlatter(entry: SelectorEntry) {2642    container.innerHTML = "";2643    searchInput = null;2644    focusedIndex = -1;2645    currentMode = "silver-platter";2646    silverPlatterOrigin = entry;26472648    const domHdr = document.createElement("div");2649    domHdr.className = "domain-header";2650    const headText = document.createElement("div");2651    headText.className = "domain-header-text";2652    const eyebrow = document.createElement("div");2653    eyebrow.className = "domain-eyebrow";2654    eyebrow.textContent = "Saved for this site";2655    const domName = document.createElement("div");2656    domName.className = "domain-name";2657    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2658    headText.append(eyebrow, domName);2659    domHdr.appendChild(headText);2660    if (!options.isSignup) {2661      const actions = document.createElement("div");2662      actions.className = "domain-header-actions";26632664      // Search shortcut — same idea as type-to-search below, but visible so2665      // the user can discover that another entry is reachable from a2666      // single-match platter. Sits to the left of the create button.2667      const searchBtn = document.createElement("button");2668      searchBtn.className = "domain-search-btn";2669      searchBtn.type = "button";2670      searchBtn.setAttribute("aria-label", "Search for a different entry");2671      searchBtn.title = "Search for a different entry";2672      searchBtn.innerHTML = searchSvgStr();2673      searchBtn.addEventListener("click", (e) => {2674        e.stopPropagation();2675        query = "";2676        renderList();2677      });2678      actions.appendChild(searchBtn);26792680      const addBtn = document.createElement("button");2681      addBtn.className = "domain-add-btn";2682      addBtn.type = "button";2683      addBtn.setAttribute("aria-label", "Create new entry");2684      addBtn.title = "Create new entry";2685      addBtn.textContent = "+";2686      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2687      actions.appendChild(addBtn);26882689      domHdr.appendChild(actions);2690    }2691    container.appendChild(domHdr);26922693    const platter = document.createElement("div");2694    platter.className = "silver-platter";2695    let capabilityActionClaimed = false;2696    const claimCapabilityAction = () => {2697      if (!options.capability) return true;2698      if (capabilityActionClaimed) return false;2699      capabilityActionClaimed = true;2700      return true;2701    };27022703    const titleEl = document.createElement("div");2704    titleEl.className = "sp-title";2705    titleEl.textContent = entry.title;2706    platter.appendChild(titleEl);27072708    if (entry.email) {2709      const emailEl = document.createElement("div");2710      emailEl.className = "sp-identity-row";2711      const emailLbl = document.createElement("span");2712      emailLbl.className = "sp-identity-label";2713      emailLbl.textContent = "email";2714      const emailVal = document.createElement("span");2715      emailVal.className = "sp-username";2716      emailVal.textContent = entry.email;2717      emailEl.append(emailLbl, emailVal);2718      platter.appendChild(emailEl);2719    }27202721    if (entry.username) {2722      const userEl = document.createElement("div");2723      userEl.className = "sp-identity-row";2724      const userLbl = document.createElement("span");2725      userLbl.className = "sp-identity-label";2726      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2727      const userVal = document.createElement("span");2728      userVal.className = "sp-username";2729      userVal.textContent = entry.username;2730      userEl.append(userLbl, userVal);2731      platter.appendChild(userEl);2732    }27332734    const fillBtn = document.createElement("button");2735    fillBtn.className = "sp-fill-btn";2736    fillBtn.type = "button";2737    fillBtn.textContent = "Fill credentials";2738    fillBtn.addEventListener("click", () => {2739      if (fillBtn.disabled || !claimCapabilityAction()) return;2740      fillBtn.disabled = true;2741      fillBtn.classList.add("filled");2742      fillBtn.innerHTML = checkSvgStr();2743      // Fire the fill, then exit via the standard exit animation. The fill2744      // itself is async (handled in index.ts) — by 400ms the form is filled2745      // and the popup begins its exit. Total dwell from click to host2746      // removal: 400ms + 130ms (exit animation) = 530ms.2747      onSelect(entry.id);2748      setTimeout(() => dismiss(), 400);2749    });2750    platter.appendChild(fillBtn);27512752    const actionsGroup = document.createElement("div");2753    actionsGroup.className = "sp-actions-group";2754    const actionsLabel = document.createElement("div");2755    actionsLabel.className = "sp-actions-label";2756    actionsLabel.textContent = "Copy";2757    actionsGroup.appendChild(actionsLabel);27582759    const actions = document.createElement("div");2760    actions.className = "sp-actions";2761    actionsGroup.appendChild(actions);27622763    if (entry.email) {2764      const copyEmail = document.createElement("button");2765      copyEmail.className = "sp-action-btn";2766      copyEmail.type = "button";2767      copyEmail.title = "Copy email";2768      copyEmail.textContent = "Email";2769      copyEmail.addEventListener("click", async (e) => {2770        e.stopPropagation();2771        let alreadyWritten = false;2772        try {2773          await navigator.clipboard.writeText(entry.email!);2774          alreadyWritten = true;2775        } catch (err) {2776          console.warn("[Peach] clipboard write denied:", err);2777        }2778        const resp = await chrome.runtime.sendMessage({2779          type: "COPY",2780          payload: { text: entry.email, label: "Email", alreadyWritten },2781        }).catch(() => null) as { ok?: boolean } | null;2782        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2783        else flashCopyError(copyEmail);2784      });2785      actions.appendChild(copyEmail);2786    }27872788    const copyU = document.createElement("button");2789    copyU.className = "sp-action-btn";2790    copyU.type = "button";2791    const usernameIsEmail = entry.username?.includes("@") ?? false;2792    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2793    copyU.textContent = usernameIsEmail ? "Email" : "Username";2794    copyU.disabled = !entry.username;2795    copyU.addEventListener("click", async (e) => {2796      e.stopPropagation();2797      if (!entry.username) return;2798      let alreadyWritten = false;2799      try {2800        await navigator.clipboard.writeText(entry.username);2801        alreadyWritten = true;2802      } catch (err) {2803        console.warn("[Peach] clipboard write denied:", err);2804      }2805      const resp = await chrome.runtime.sendMessage({2806        type: "COPY",2807        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2808      }).catch(() => null) as { ok?: boolean } | null;2809      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2810      else flashCopyError(copyU);2811    });2812    actions.appendChild(copyU);28132814    const copyP = document.createElement("button");2815    copyP.className = "sp-action-btn";2816    copyP.type = "button";2817    copyP.title = "Copy password";2818    copyP.textContent = "Password";2819    copyP.addEventListener("click", async (e) => {2820      e.stopPropagation();2821      if (!claimCapabilityAction()) return;2822      const resp = await chrome.runtime.sendMessage({2823        type: "GET_ENTRY_FOR_FILL",2824        payload: { id: entry.id, capability: options.capability },2825      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2826      if (!resp?.ok || !resp.data?.password) {2827        if (options.capability) dismiss();2828        return;2829      }2830      let alreadyWritten = false;2831      try {2832        await navigator.clipboard.writeText(resp.data.password);2833        alreadyWritten = true;2834      } catch (err) {2835        console.warn("[Peach] clipboard write denied:", err);2836      }2837      const copyResp = await chrome.runtime.sendMessage({2838        type: "COPY",2839        payload: { text: resp.data.password, label: "Password", alreadyWritten },2840      }).catch(() => null) as { ok?: boolean } | null;2841      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2842      else flashCopyError(copyP);2843      if (options.capability) dismiss();2844    });2845    actions.appendChild(copyP);28462847    let trayEl: HTMLDivElement | null = null;2848    let trayInterval: ReturnType<typeof setInterval> | null = null;28492850    function closeTray() {2851      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2852      trayEl?.remove();2853      trayEl = null;2854    }2855    // Register so dismiss() will close the tray and clear the interval2856    // even if the user dismisses without explicitly closing the tray.2857    cleanupHooks.push(closeTray);28582859    async function openTOTPTray() {2860      // Fetch the current TOTP code from the background. The raw base32 seed2861      // never enters the content script (SEV-3-C): we receive the live 6-digit2862      // code plus the seconds remaining, count down locally, and re-fetch a2863      // fresh code only when the 30s window rolls over.2864      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2865        const r = await chrome.runtime.sendMessage({2866          type: "GET_ENTRY_FOR_FILL",2867          payload: { id: entry.id, capability: options.capability },2868        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2869        if (!r?.ok || !r.data?.totpCode) return null;2870        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2871      }2872      let current = await fetchCode();2873      if (!current) return;28742875      trayEl = document.createElement("div");2876      trayEl.className = "sp-tray";28772878      const label = document.createElement("span");2879      label.className = "sp-tray-label";2880      label.textContent = "2FA";2881      trayEl.appendChild(label);28822883      const codeEl = document.createElement("div");2884      codeEl.className = "sp-totp-code";2885      trayEl.appendChild(codeEl);28862887      const ringNs = "http://www.w3.org/2000/svg";2888      const ring = document.createElementNS(ringNs, "svg");2889      ring.setAttribute("class", "sp-totp-ring");2890      ring.setAttribute("viewBox", "0 0 24 24");2891      const trackC = document.createElementNS(ringNs, "circle");2892      trackC.setAttribute("class", "ring-track");2893      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2894      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2895      const fillC = document.createElementNS(ringNs, "circle");2896      fillC.setAttribute("class", "ring-fill");2897      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2898      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2899      fillC.setAttribute("stroke-linecap", "round");2900      fillC.setAttribute("stroke-dasharray", "62.83");2901      ring.append(trackC, fillC);2902      trayEl.appendChild(ring);29032904      const copyBtn = document.createElement("button");2905      copyBtn.className = "sp-totp-copy";2906      copyBtn.type = "button";2907      copyBtn.textContent = "Copy";2908      trayEl.appendChild(copyBtn);29092910      function render() {2911        const { code, remaining } = current!;2912        // Group as "847 291" — easier to read than "847291"2913        codeEl.textContent = code.length === 62914          ? `${code.slice(0, 3)} ${code.slice(3)}`2915          : code;2916        // Ring fills counter-clockwise as time elapses: dashoffset goes from2917        // 0 (full ring) to 62.83 (empty) over the 30s window.2918        const fraction = (30 - remaining) / 30;2919        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2920      }2921      render();2922      trayInterval = setInterval(async () => {2923        if (!current) return;2924        current = { code: current.code, remaining: current.remaining - 1 };2925        // Window rolled over — pull a fresh code from the background.2926        if (current.remaining <= 0) {2927          const next = await fetchCode();2928          current = next ?? { code: current.code, remaining: 30 };2929        }2930        render();2931      }, 1000);29322933      copyBtn.addEventListener("click", async (e) => {2934        e.stopPropagation();2935        const code = current?.code;2936        if (!code) return;2937        let alreadyWritten = false;2938        try {2939          await navigator.clipboard.writeText(code);2940          alreadyWritten = true;2941        } catch (err) {2942          console.warn("[Peach] clipboard write denied:", err);2943        }2944        const resp = await chrome.runtime.sendMessage({2945          type: "COPY",2946          payload: { text: code, label: "TOTP", alreadyWritten },2947        }).catch(() => null) as { ok?: boolean } | null;2948        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2949        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2950      });29512952      platter.appendChild(trayEl);2953    }29542955    const editBtn = document.createElement("button");2956    editBtn.className = "sp-action-btn sp-action-edit";2957    editBtn.type = "button";2958    editBtn.title = "Edit entry";2959    editBtn.textContent = "Edit";2960    editBtn.addEventListener("click", (e) => {2961      e.stopPropagation();2962      closeTray();2963      void renderInlineEdit(entry);2964    });2965    actions.appendChild(editBtn);29662967    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2968    // "···" toggle was zero-savings (the toggle button took the same space2969    // the "2FA" label needed) and made the code one extra click away.2970    if (entry.hasTotp && !options.capability) void openTOTPTray();29712972    platter.appendChild(actionsGroup);2973    container.appendChild(platter);2974  }29752976  /** Raw TOTP seeds, password history, and passkeys stay inside extension-owned UI. */2977  async function renderInlineEdit(summary: SelectorEntry) {2978    currentMode = "edit";2979    container.innerHTML = "";29802981    const wrap = document.createElement("div");2982    wrap.className = "create-form-wrap";2983    const head = document.createElement("div");2984    head.className = "create-head";2985    const back = document.createElement("button");2986    back.className = "back-btn";2987    back.type = "button";2988    back.title = "Cancel";2989    back.innerHTML = `<svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M7 2L3 5.5L7 9"/></svg>`;2990    back.addEventListener("click", () => renderSilverPlatter(summary));2991    const label = document.createElement("div");2992    label.className = "create-label";2993    label.textContent = "Edit entry";2994    head.append(back, label);2995    wrap.appendChild(head);29962997    const body = document.createElement("div");2998    body.className = "create-body";2999    const loading = document.createElement("div");3000    loading.className = "empty-hint";3001    loading.textContent = "loading…";3002    body.appendChild(loading);3003    wrap.appendChild(body);3004    container.appendChild(wrap);30053006    const response = await chrome.runtime.sendMessage({3007      type: "GET_ENTRY_FOR_FILL",3008      payload: { id: summary.id, capability: options.capability },3009    }).catch(() => null) as {3010      ok?: boolean;3011      data?: {3012        title?: string;3013        username?: string;3014        email?: string;3015        password?: string;3016        url?: string;3017        notes?: string;3018      };3019    } | null;3020    if (!response?.ok || !response.data) {3021      loading.textContent = "couldn't load this entry";3022      return;3023    }3024    body.innerHTML = "";30253026    function field(labelText: string, value: string, type: "text" | "password" = "text") {3027      const group = document.createElement("div");3028      group.className = "f-group";3029      const fieldLabel = document.createElement("div");3030      fieldLabel.className = "f-label";3031      fieldLabel.textContent = labelText;3032      const input = document.createElement("input");3033      input.className = "f-input";3034      input.type = type;3035      input.value = value;3036      input.autocomplete = type === "password" ? "new-password" : "off";3037      group.append(fieldLabel, input);3038      body.appendChild(group);3039      return input;3040    }30413042    const entry = response.data;3043    const titleInput = field("title", entry.title ?? summary.title);3044    const urlInput = field("url", entry.url ?? summary.url ?? "");3045    const usernameInput = field("username", entry.username ?? summary.username ?? "");3046    const emailInput = field("email", entry.email ?? summary.email ?? "");3047    const passwordInput = field("password", entry.password ?? "", "password");30483049    const generator = createSmartGenerator({3050      policy: detectPasswordPolicy(),3051      initialPassword: entry.password,3052      onChange: (password) => { passwordInput.value = password; },3053    });3054    generator.root.hidden = true;3055    const generatorToggle = document.createElement("button");3056    generatorToggle.className = "gen-toggle-link";3057    generatorToggle.type = "button";3058    generatorToggle.textContent = "⚙ generate";3059    generatorToggle.addEventListener("click", () => {3060      generator.root.hidden = !generator.root.hidden;3061      generatorToggle.textContent = generator.root.hidden ? "⚙ generate" : "☰ hide generator";3062    });3063    body.append(generatorToggle, generator.root);30643065    const notesGroup = document.createElement("div");3066    notesGroup.className = "f-group";3067    const notesLabel = document.createElement("div");3068    notesLabel.className = "f-label";3069    notesLabel.textContent = "notes";3070    const notesInput = document.createElement("textarea");3071    notesInput.className = "f-input";3072    notesInput.rows = 3;3073    notesInput.value = entry.notes ?? "";3074    notesGroup.append(notesLabel, notesInput);3075    body.appendChild(notesGroup);30763077    const actions = document.createElement("div");3078    actions.className = "f-row";3079    const save = document.createElement("button");3080    save.className = "save-btn";3081    save.type = "button";3082    save.textContent = "Save changes";3083    save.style.flex = "1";3084    const cancel = document.createElement("button");3085    cancel.className = "gen-btn";3086    cancel.type = "button";3087    cancel.textContent = "cancel";3088    cancel.addEventListener("click", () => renderSilverPlatter(summary));3089    actions.append(save, cancel);3090    body.appendChild(actions);30913092    save.addEventListener("click", async () => {3093      save.disabled = true;3094      save.textContent = "Saving…";3095      const patch = {3096        title: titleInput.value.trim(),3097        url: urlInput.value.trim(),3098        username: usernameInput.value.trim(),3099        email: emailInput.value.trim() || undefined,3100        password: passwordInput.value,3101        notes: notesInput.value,3102      };3103      const update = await chrome.runtime.sendMessage({3104        type: "UPDATE_ENTRY",3105        payload: { id: summary.id, patch },3106      }).catch(() => null) as { ok?: boolean; error?: string } | null;3107      if (!update?.ok) {3108        save.disabled = false;3109        save.textContent = "Save changes";3110        const error = document.createElement("div");3111        error.className = "empty-hint";3112        error.textContent = update?.error ?? "couldn't save this entry";3113        body.appendChild(error);3114        setTimeout(() => error.remove(), 3000);3115        return;3116      }3117      renderSilverPlatter({3118        ...summary,3119        title: patch.title,3120        url: patch.url,3121        username: patch.username,3122        email: patch.email,3123      });3124    });31253126    queueMicrotask(() => titleInput.focus());3127  }31283129  function renderLocked() {3130    container.innerHTML = "";31313132    // Domain header (same as list view)3133    const domHdr = document.createElement("div");3134    domHdr.className = "domain-header";3135    const eyebrow = document.createElement("div");3136    eyebrow.className = "domain-eyebrow";3137    eyebrow.textContent = "vault locked";3138    const domName = document.createElement("div");3139    domName.className = "domain-name";3140    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3141    domHdr.append(eyebrow, domName);3142    container.appendChild(domHdr);31433144    const wrap = document.createElement("div");3145    wrap.className = "locked-wrap";31463147    // Icon + label row3148    const head = document.createElement("div"); head.className = "locked-head";3149    const icon = document.createElement("div"); icon.className = "locked-icon";3150    icon.innerHTML = keySvgStr();3151    const title = document.createElement("div"); title.className = "locked-title";3152    title.textContent = "unlock to autofill";3153    head.append(icon, title);31543155    // The master password is NEVER collected in page-hosted DOM. A malicious3156    // page can observe keystrokes on the shared DOM event stream (a capture-3157    // phase listener registered before Peach injects sees every key before any3158    // stopImmediatePropagation), which would leak the vault's root secret3159    // (audit HIGH). Instead, route unlocking to the trusted extension popup,3160    // where keystrokes are isolated from the page. After the user unlocks3161    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill3162    // automatically (see content/index.ts), so the flow resumes on its own.3163    const sub = document.createElement("div");3164    sub.className = "locked-sub";3165    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";31663167    const openBtn = document.createElement("button");3168    openBtn.className = "locked-btn";3169    openBtn.type = "button";3170    openBtn.textContent = "Open Peach to unlock";3171    openBtn.addEventListener("click", () => {3172      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});3173      openBtn.textContent = "opening Peach…";3174      openBtn.disabled = true;3175      // openPopup() can't always open programmatically (browser/version/gesture3176      // limits); reset so the user can retry or click the toolbar icon.3177      setTimeout(() => {3178        if (openBtn.isConnected) {3179          openBtn.textContent = "Open Peach to unlock";3180          openBtn.disabled = false;3181        }3182      }, 2500);3183    });31843185    wrap.append(head, sub, openBtn);3186    container.appendChild(wrap);3187  }31883189  function handleKeyDown(e: KeyboardEvent) {3190    // PCH-01-007: reject page-synthesised KeyboardEvents — only genuine3191    // keystrokes may drive selection/fill. A page hosting an open selector could3192    // otherwise dispatch ArrowDown/Enter at `document` to fill without user intent.3193    if (!e.isTrusted) return;3194    if (options.locked) {3195      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3196      return;3197    }3198    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {3199      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3200      return;3201    }3202    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");3203    const count = allEntryEls.length;3204    const activeElement = shadow.activeElement ?? document.activeElement;3205    if (activeElement === searchInput) {3206      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }3207      if (count === 0) return;3208      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;3209    }3210    if (count === 0) return;3211    switch (e.key) {3212      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3213      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3214      case "Enter": {3215        if (focusedIndex >= 0) {3216          const el = allEntryEls[focusedIndex] as HTMLElement;3217          const id = el.dataset.id;3218          if (id) { onSelect(id); dismiss(); }3219          else if (el.classList.contains("is-new") || !id) {3220            // "New entry" row (last item, no data-id)3221            showCreateForm();3222          }3223        }3224        break;3225      }3226      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3227    }3228  }32293230  document.addEventListener("keydown", handleKeyDown);32313232  // Type-to-search from the silver platter. A printable single-character3233  // keystroke (no modifier) seeds the search query and switches into the3234  // list view, so the user can pivot to a different entry without first3235  // clicking the search icon. Capture phase so the anchor input does not3236  // receive the character before we hijack it.3237  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3238    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3239    if (currentMode !== "silver-platter") return;3240    if (e.ctrlKey || e.metaKey || e.altKey) return;3241    if (e.key.length !== 1) return;3242    e.preventDefault();3243    e.stopImmediatePropagation();3244    query = e.key;3245    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3246    void ensureSearchableLoaded(renderList);3247    renderList();3248  };3249  document.addEventListener("keydown", silverPlatterTypeHandler, true);3250  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));32513252  const identityHelperTypeHandler = (e: KeyboardEvent) => {3253    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3254    if (currentMode !== "identity-helper") return;3255    if (e.ctrlKey || e.metaKey || e.altKey) return;3256    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3257    if (active === searchInput) return;3258    if (3259      active instanceof HTMLInputElement ||3260      active instanceof HTMLTextAreaElement ||3261      (active instanceof HTMLElement && active.isContentEditable)3262    ) {3263      return;3264    }3265    if (e.key.length !== 1) return;3266    e.preventDefault();3267    e.stopImmediatePropagation();3268    query = e.key;3269    renderIdentityHelper();3270  };3271  document.addEventListener("keydown", identityHelperTypeHandler, true);3272  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));32733274  (modalAncestor ?? document.body).appendChild(host);32753276  // position:fixed normally resolves to the viewport, but an ancestor with3277  // transform / filter / backdrop-filter / perspective / contain / will-change3278  // establishes a containing block, so "fixed" then resolves to that ancestor's3279  // padding box instead. When the host is mounted inside such an ancestor (a3280  // modal) we subtract its border-box origin so the popup still lands at the3281  // field's true viewport position. At the document root there is no such3282  // ancestor and the offset is zero.3283  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3284    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3285    return (3286      has("transform") || has("perspective") || has("translate") ||3287      has("rotate") || has("scale") || has("filter") ||3288      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3289      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3290      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3291    );3292  }3293  function containingBlockOffset(): { dx: number; dy: number } {3294    let el: HTMLElement | null = host.parentElement;3295    while (el && el !== document.documentElement) {3296      const s = getComputedStyle(el);3297      if (establishesFixedContainingBlock(s)) {3298        const r = el.getBoundingClientRect();3299        return {3300          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3301          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3302        };3303      }3304      el = el.parentElement;3305    }3306    return { dx: 0, dy: 0 };3307  }33083309  function updatePosition() {3310    const r = anchorEl.getBoundingClientRect();3311    const { dx, dy } = containingBlockOffset();3312    host.style.top = `${r.bottom - dy + 5}px`;3313    host.style.left = `${r.left - dx}px`;3314    host.style.width = `${popupWidth}px`;3315  }3316  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3317  updatePosition();33183319  // observeAnchorPosition listens on window scroll, but a modal with its own3320  // internal scroll container doesn't move the window — track the modal's scroll3321  // too so the popup follows the field inside it.3322  if (modalAncestor) {3323    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3324    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3325  }33263327  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3328  // swap) removes the field without firing blur/click, so none of the normal3329  // dismiss triggers fire and the popup would otherwise linger over nothing.3330  const removalObserver = new MutationObserver(() => {3331    if (!document.contains(anchorEl)) dismiss();3332  });3333  removalObserver.observe(document.body, { childList: true, subtree: true });3334  cleanupHooks.push(() => removalObserver.disconnect());33353336  if (options.locked) {3337    renderLocked();3338  } else if (options.isSignup && options.savedIdentities) {3339    // State 10: identity helper — signup form detected, show derived3340    // identity list (emails then usernames) instead of vault entry list.3341    renderIdentityHelper();3342  } else if (entries.length === 1 && !options.isSignup) {3343    // Silver platter (State 1): single domain match → focused fill view.3344    // Multi-match goes through renderList instead.3345    renderSilverPlatter(entries[0]!);3346  } else {3347    renderList();3348  }33493350  let exitScheduled = false;3351  function dismiss(userAction = false) {3352    // Idempotent: dismiss() can be called from multiple paths (Escape,3353    // outside click, entry select, fill success, host page nav). The exit3354    // animation must only play once and host.remove() must run exactly once.3355    if (exitScheduled) return;3356    exitScheduled = true;3357    // Detach listeners synchronously so nothing can re-trigger during the3358    // 130ms exit window (a focusin firing here would race against the3359    // dismiss-lock work in Pass 2).3360    stopObserving();3361    document.removeEventListener("click", outsideClick, { capture: true });3362    document.removeEventListener("keydown", handleKeyDown);3363    for (const cleanup of cleanupHooks) {3364      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3365    }3366    if (userAction) options.onDismiss?.();3367    container.classList.add("is-exiting");3368    setTimeout(() => host.remove(), 130);3369  }33703371  function outsideClick(ev: MouseEvent) {3372    const path = ev.composedPath();3373    // Never dismiss when clicking the anchor field itself — that click is3374    // what triggered the selector to open, and the user may click the field3375    // again to re-focus it without intending to close the selector.3376    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3377  }3378  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3379  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33803381  return dismiss;3382}33833384export function showTOTPSelector(3385  anchorEl: HTMLInputElement,3386  entries: SelectorEntry[],3387  onFill: (id: string) => void,3388  options: { domain?: string; onDismiss?: () => void } = {}3389): () => void {3390  const host = document.createElement("div");3391  host.style.cssText = "position: absolute; z-index: 2147483647;";3392  host.style.setProperty("--peach-accent", accentHex);3393  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3394  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3395  const shadow = host.attachShadow({ mode: "closed" });33963397  const style = shadow.appendChild(document.createElement("style"));3398  style.textContent = SELECTOR_STYLES;33993400  const rect = anchorEl.getBoundingClientRect();3401  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3402  host.style.left = `${rect.left + window.scrollX}px`;3403  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3404  host.style.width = `${popupWidth}px`;34053406  const container = shadow.appendChild(document.createElement("div"));3407  container.className = "peach-inline-popup";3408  container.setAttribute("data-theme", popupTheme);34093410  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3411  const current = entries.filter((entry) => entry.hasTotp);3412  let focusedIndex = current.length === 1 ? 0 : -1;34133414  function updatePosition() {3415    const r = anchorEl.getBoundingClientRect();3416    host.style.top = `${r.bottom + window.scrollY + 5}px`;3417    host.style.left = `${r.left + window.scrollX}px`;3418    host.style.width = `${popupWidth}px`;3419  }34203421  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);34223423  function choose(entry: SelectorEntry) {3424    onFill(entry.id);3425    dismiss();3426  }34273428  function render() {3429    container.innerHTML = "";34303431    const domHdr = document.createElement("div");3432    domHdr.className = "domain-header";3433    const headText = document.createElement("div");3434    headText.className = "domain-header-text";3435    const eyebrow = document.createElement("div");3436    eyebrow.className = "domain-eyebrow";3437    eyebrow.textContent = "2FA code";3438    const domName = document.createElement("div");3439    domName.className = "domain-name";3440    domName.textContent = domain;3441    headText.append(eyebrow, domName);3442    domHdr.appendChild(headText);3443    container.appendChild(domHdr);34443445    if (current.length === 1) {3446      const entry = current[0]!;3447      const platter = document.createElement("div");3448      platter.className = "silver-platter";34493450      const title = document.createElement("div");3451      title.className = "sp-title";3452      title.textContent = entry.title;3453      platter.appendChild(title);34543455      const sub = document.createElement("div");3456      sub.className = "sp-username";3457      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3458      platter.appendChild(sub);34593460      const fill = document.createElement("button");3461      fill.className = "sp-fill-btn";3462      fill.type = "button";3463      fill.textContent = "Fill 2FA code";3464      fill.addEventListener("click", () => choose(entry));3465      platter.appendChild(fill);34663467      container.appendChild(platter);3468      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3469      return;3470    }34713472    const results = document.createElement("div");3473    results.className = "results";3474    container.appendChild(results);34753476    for (let i = 0; i < current.length; i++) {3477      const entry = current[i]!;3478      const row = document.createElement("div");3479      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3480      row.dataset.index = String(i);3481      row.setAttribute("tabindex", "-1");34823483      const icon = document.createElement("div");3484      icon.className = "entry-icon";3485      icon.innerHTML = keySvgStr();3486      row.appendChild(icon);3487      const info = document.createElement("div");3488      info.className = "entry-info";3489      const title = document.createElement("div");3490      title.className = "entry-title";3491      title.textContent = entry.title;3492      const sub = document.createElement("div");3493      sub.className = "entry-sub";3494      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3495      info.append(title, sub);3496      row.appendChild(info);34973498      const badge = document.createElement("span");3499      badge.className = "totp-badge";3500      badge.textContent = "Fill";3501      row.appendChild(badge);3502      row.addEventListener("click", () => choose(entry));3503      results.appendChild(row);3504    }3505  }35063507  function setFocused(index: number) {3508    focusedIndex = index;3509    container.querySelectorAll(".entry").forEach((el, i) => {3510      el.classList.toggle("focused", i === focusedIndex);3511      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3512    });3513  }35143515  function handleKeyDown(e: KeyboardEvent) {3516    if (e.key === "Escape" || e.key === "Tab") {3517      e.preventDefault();3518      dismiss(true);3519      return;3520    }3521    if (current.length === 0) return;3522    if (e.key === "Enter") {3523      e.preventDefault();3524      choose(current[Math.max(0, focusedIndex)]!);3525      return;3526    }3527    if (current.length === 1) return;3528    if (e.key === "ArrowDown") {3529      e.preventDefault();3530      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3531    } else if (e.key === "ArrowUp") {3532      e.preventDefault();3533      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3534    }3535  }35363537  let exitScheduled = false;3538  function dismiss(userAction = false) {3539    if (exitScheduled) return;3540    exitScheduled = true;3541    stopObserving();3542    document.removeEventListener("click", outsideClick, { capture: true });3543    document.removeEventListener("keydown", handleKeyDown);3544    if (userAction) options.onDismiss?.();3545    container.classList.add("is-exiting");3546    setTimeout(() => host.remove(), 130);3547  }35483549  function outsideClick(ev: MouseEvent) {3550    const path = ev.composedPath();3551    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3552  }35533554  document.addEventListener("keydown", handleKeyDown);3555  document.body.appendChild(host);3556  render();3557  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);35583559  return dismiss;3560}35613562export interface CardSelectorEntry {3563  id: string;3564  title: string;3565  cardholderName?: string;3566  last4?: string;3567  expMonth?: string;3568  expYear?: string;3569  network?: import("../shared/types").CardNetwork;3570}35713572interface CardSelectorOptions {3573  domain?: string;3574  capability?: string;3575  /** Caller-provided fill — receives the full card payload from the SW. */3576  onFill: (entry: import("../shared/types").VaultEntry) => void;3577  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3578  onDismiss?: () => void;3579}35803581/**3582 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3583 * passkey create or get. Renders as a fixed-position floating popup (no3584 * field anchor needed — passkeys don't require a focused input). Uses the3585 * same theme tokens and entrance animation as all other inline popup states.3586 */3587export function showPasskeyProGate(): void {3588  const domain = location.hostname.replace(/^www\./, "");35893590  const host = document.createElement("div");3591  host.setAttribute("data-peach-passkey-gate", "1");3592  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3593  const shadow = host.attachShadow({ mode: "closed" });35943595  const style = document.createElement("style");3596  style.textContent = `3597    :host { all: initial; }3598    .gate-wrap {3599      position: fixed;3600      top: 50%;3601      left: 50%;3602      transform: translate(-50%, -50%);3603      width: 280px;3604      pointer-events: auto;3605      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3606    }3607    @keyframes g-in {3608      from { opacity:0; transform: translate(-50%,-52%); }3609      to   { opacity:1; transform: translate(-50%,-50%); }3610    }3611    .gate-wrap.is-exiting {3612      animation: g-out 130ms ease-in forwards;3613    }3614    @keyframes g-out {3615      to { opacity:0; transform: translate(-50%,-52%); }3616    }3617    .gate {3618      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3619      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3620      border-radius: 12px;3621      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3622      padding: 16px;3623      font-family: Inter, sans-serif;3624    }3625    .gate-header {3626      display: flex;3627      align-items: center;3628      gap: 7px;3629      margin-bottom: 12px;3630      padding-bottom: 10px;3631      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3632    }3633    .gate-domain {3634      font-size: 12px;3635      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3636      font-family: "IBM Plex Mono", monospace;3637      overflow: hidden;3638      text-overflow: ellipsis;3639      white-space: nowrap;3640    }3641    .gate-title {3642      font-size: 14px;3643      font-weight: 500;3644      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3645      margin-bottom: 6px;3646    }3647    .gate-subtitle {3648      font-size: 12px;3649      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3650      line-height: 1.5;3651      margin-bottom: 14px;3652    }3653    .gate-btn {3654      display: block;3655      width: 100%;3656      padding: 9px 0;3657      border-radius: 8px;3658      border: none;3659      cursor: pointer;3660      font-size: 13px;3661      font-family: Inter, sans-serif;3662      font-weight: 500;3663      transition: opacity 100ms;3664      margin-bottom: 7px;3665      text-align: center;3666    }3667    .gate-btn:last-child { margin-bottom: 0; }3668    .gate-btn--accent {3669      background: ${accentHex};3670      color: #fff;3671    }3672    .gate-btn--accent:hover { opacity: 0.88; }3673    .gate-btn--ghost {3674      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3675      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3676    }3677    .gate-btn--ghost:hover { opacity: 0.75; }3678    .backdrop {3679      position: fixed;3680      inset: 0;3681      pointer-events: auto;3682    }3683  `;3684  shadow.appendChild(style);36853686  const backdrop = document.createElement("div");3687  backdrop.className = "backdrop";3688  shadow.appendChild(backdrop);36893690  const wrap = document.createElement("div");3691  wrap.className = "gate-wrap";3692  shadow.appendChild(wrap);36933694  const gate = document.createElement("div");3695  gate.className = "gate";3696  wrap.appendChild(gate);36973698  // Header: peach icon + domain3699  const header = document.createElement("div");3700  header.className = "gate-header";3701  const icon = document.createElement("span");3702  icon.innerHTML = peachIconSvg();3703  const domainEl = document.createElement("span");3704  domainEl.className = "gate-domain";3705  domainEl.textContent = domain;3706  header.append(icon, domainEl);3707  gate.appendChild(header);37083709  const title = document.createElement("div");3710  title.className = "gate-title";3711  title.textContent = "Passkeys are part of Peach Pro.";3712  gate.appendChild(title);37133714  const subtitle = document.createElement("div");3715  subtitle.className = "gate-subtitle";3716  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3717  gate.appendChild(subtitle);37183719  const upgradeBtn = document.createElement("button");3720  upgradeBtn.className = "gate-btn gate-btn--accent";3721  upgradeBtn.type = "button";3722  upgradeBtn.textContent = "Upgrade to Pro";3723  gate.appendChild(upgradeBtn);37243725  const laterBtn = document.createElement("button");3726  laterBtn.className = "gate-btn gate-btn--ghost";3727  laterBtn.type = "button";3728  laterBtn.textContent = "Not right now";3729  gate.appendChild(laterBtn);37303731  function dismiss() {3732    wrap.classList.add("is-exiting");3733    setTimeout(() => host.remove(), 130);3734  }37353736  upgradeBtn.addEventListener("click", () => {3737    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3738    dismiss();3739  });3740  laterBtn.addEventListener("click", dismiss);3741  backdrop.addEventListener("click", dismiss);37423743  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3744    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3745  });37463747  document.body.appendChild(host);3748}37493750/**3751 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3752 * detector sees the page invoke navigator.credentials.create(); content/index.ts3753 * checks vault + decline state then calls this. "Save passkey to Peach"3754 * initiates the popup-context credential flow; "Not now" records a 30-day3755 * decline for the domain so we don't re-show on every page reload.3756 */3757export function showPasskeyRegistrationOffer(args: {3758  rpId: string;3759  rpName?: string;3760  userName?: string;3761  userDisplayName?: string;3762}): void {3763  const domain = location.hostname.replace(/^www\./, "");3764  const displayName = args.rpName || domain;37653766  const host = document.createElement("div");3767  host.setAttribute("data-peach-passkey-offer", "1");3768  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3769  const shadow = host.attachShadow({ mode: "closed" });37703771  const style = document.createElement("style");3772  style.textContent = `3773    :host { all: initial; }3774    .offer-wrap {3775      position: fixed;3776      top: 16px;3777      right: 16px;3778      width: 320px;3779      pointer-events: auto;3780      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3781    }3782    @keyframes o-in {3783      from { opacity: 0; transform: translateY(-6px); }3784      to   { opacity: 1; transform: translateY(0); }3785    }3786    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3787    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3788    .offer {3789      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3790      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3791      border-radius: 12px;3792      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3793      padding: 14px 14px 12px;3794      font-family: Inter, sans-serif;3795      position: relative;3796    }3797    .offer-close {3798      position: absolute;3799      top: 8px;3800      right: 8px;3801      width: 18px;3802      height: 18px;3803      border: none;3804      background: transparent;3805      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3806      cursor: pointer;3807      font-size: 14px;3808      line-height: 1;3809      padding: 0;3810    }3811    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3812    .offer-header {3813      display: flex;3814      align-items: center;3815      gap: 7px;3816      margin-bottom: 8px;3817      padding-bottom: 8px;3818      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3819    }3820    .offer-domain {3821      font-size: 12px;3822      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3823      font-family: "IBM Plex Mono", monospace;3824      overflow: hidden;3825      text-overflow: ellipsis;3826      white-space: nowrap;3827    }3828    .offer-title {3829      font-size: 13px;3830      font-weight: 500;3831      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3832      margin-bottom: 4px;3833    }3834    .offer-subtitle {3835      font-size: 11px;3836      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3837      line-height: 1.45;3838      margin-bottom: 12px;3839    }3840    .offer-btn {3841      display: block;3842      width: 100%;3843      padding: 8px 0;3844      border-radius: 7px;3845      border: none;3846      cursor: pointer;3847      font-size: 12px;3848      font-family: Inter, sans-serif;3849      font-weight: 500;3850      transition: opacity 100ms;3851      margin-bottom: 6px;3852      text-align: center;3853    }3854    .offer-btn:last-child { margin-bottom: 0; }3855    .offer-btn--accent { background: ${accentHex}; color: #fff; }3856    .offer-btn--accent:hover { opacity: 0.88; }3857    .offer-btn--ghost {3858      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3859      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3860    }3861    .offer-btn--ghost:hover { opacity: 0.75; }3862  `;3863  shadow.appendChild(style);38643865  const wrap = document.createElement("div");3866  wrap.className = "offer-wrap";3867  shadow.appendChild(wrap);38683869  const offer = document.createElement("div");3870  offer.className = "offer";3871  wrap.appendChild(offer);38723873  const closeBtn = document.createElement("button");3874  closeBtn.className = "offer-close";3875  closeBtn.type = "button";3876  closeBtn.setAttribute("aria-label", "Dismiss");3877  closeBtn.textContent = "✕";3878  offer.appendChild(closeBtn);38793880  const header = document.createElement("div");3881  header.className = "offer-header";3882  const icon = document.createElement("span");3883  icon.innerHTML = peachIconSvg();3884  const domainEl = document.createElement("span");3885  domainEl.className = "offer-domain";3886  domainEl.textContent = domain;3887  header.append(icon, domainEl);3888  offer.appendChild(header);38893890  const title = document.createElement("div");3891  title.className = "offer-title";3892  title.textContent = "This site supports passkeys.";3893  offer.appendChild(title);38943895  const subtitle = document.createElement("div");3896  subtitle.className = "offer-subtitle";3897  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3898  offer.appendChild(subtitle);38993900  const saveBtn = document.createElement("button");3901  saveBtn.className = "offer-btn offer-btn--accent";3902  saveBtn.type = "button";3903  saveBtn.textContent = "Save passkey to Peach";3904  offer.appendChild(saveBtn);39053906  const laterBtn = document.createElement("button");3907  laterBtn.className = "offer-btn offer-btn--ghost";3908  laterBtn.type = "button";3909  laterBtn.textContent = "Not now";3910  offer.appendChild(laterBtn);39113912  function dismiss(decline: boolean) {3913    if (decline) {3914      chrome.runtime.sendMessage({3915        type: "PASSKEY_OFFER_DECLINE",3916        payload: { domain },3917      }).catch(() => {});3918    }3919    wrap.classList.add("is-exiting");3920    setTimeout(() => host.remove(), 130);3921  }39223923  saveBtn.addEventListener("click", () => {3924    chrome.runtime.sendMessage({3925      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3926      payload: {3927        rpId: args.rpId,3928        rpName: args.rpName ?? displayName,3929        userName: args.userName ?? "user",3930        userDisplayName: args.userDisplayName,3931      },3932    }).catch(() => {});3933    dismiss(false);3934  });3935  laterBtn.addEventListener("click", () => dismiss(true));3936  closeBtn.addEventListener("click", () => dismiss(true));39373938  document.body.appendChild(host);3939}39403941/**3942 * State 11 — passkey available indicator. Shown when the user lands on a3943 * domain for which they already have a stored passkey. Tells them where to3944 * find it (the entry already shows in the vault list); the "Sign in with3945 * passkey" button opens the popup so they can use the platform authenticator3946 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3947 * the actual sign-in transparently, so this banner is informational only.3948 */3949export function showPasskeyAvailable(args: {3950  rpId: string;3951  userName: string;3952  fromBrowser?: "chrome" | "firefox";3953  currentBrowser?: "chrome" | "firefox" | "unknown";3954}): void {3955  const domain = location.hostname.replace(/^www\./, "");3956  const crossBrowser =3957    args.fromBrowser &&3958    args.currentBrowser &&3959    args.currentBrowser !== "unknown" &&3960    args.fromBrowser !== args.currentBrowser;39613962  const host = document.createElement("div");3963  host.setAttribute("data-peach-passkey-available", "1");3964  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3965  const shadow = host.attachShadow({ mode: "closed" });39663967  const style = document.createElement("style");3968  style.textContent = `3969    :host { all: initial; }3970    .avail-wrap {3971      position: fixed;3972      top: 16px;3973      right: 16px;3974      width: 320px;3975      pointer-events: auto;3976      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3977    }3978    @keyframes a-in {3979      from { opacity: 0; transform: translateY(-6px); }3980      to   { opacity: 1; transform: translateY(0); }3981    }3982    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3983    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3984    .avail {3985      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3986      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3987      border-radius: 12px;3988      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3989      padding: 14px 14px 12px;3990      font-family: Inter, sans-serif;3991      position: relative;3992    }3993    .avail-close {3994      position: absolute;3995      top: 8px;3996      right: 8px;3997      width: 18px;3998      height: 18px;3999      border: none;4000      background: transparent;4001      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};4002      cursor: pointer;4003      font-size: 14px;4004      line-height: 1;4005      padding: 0;4006    }4007    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }4008    .avail-header {4009      display: flex;4010      align-items: center;4011      gap: 7px;4012      margin-bottom: 8px;4013      padding-bottom: 8px;4014      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};4015    }4016    .avail-domain {4017      font-size: 12px;4018      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};4019      font-family: "IBM Plex Mono", monospace;4020    }4021    .avail-label {4022      font-size: 9px;4023      letter-spacing: 0.16em;4024      text-transform: uppercase;4025      color: ${accentHex};4026      margin-bottom: 4px;4027    }4028    .avail-user {4029      font-size: 13px;4030      font-weight: 500;4031      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};4032      margin-bottom: 12px;4033      overflow: hidden;4034      text-overflow: ellipsis;4035      white-space: nowrap;4036    }4037    .avail-cross {4038      font-size: 11px;4039      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};4040      line-height: 1.45;4041      margin-bottom: 12px;4042      padding: 8px;4043      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};4044      border-radius: 6px;4045    }4046    .avail-btn {4047      display: block;4048      width: 100%;4049      padding: 8px 0;4050      border-radius: 7px;4051      border: none;4052      cursor: pointer;4053      font-size: 12px;4054      font-family: Inter, sans-serif;4055      font-weight: 500;4056      transition: opacity 100ms;4057      margin-bottom: 6px;4058      text-align: center;4059    }4060    .avail-btn:last-child { margin-bottom: 0; }4061    .avail-btn--accent { background: ${accentHex}; color: #fff; }4062    .avail-btn--accent:hover { opacity: 0.88; }4063    .avail-btn--ghost {4064      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};4065      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};4066    }4067    .avail-btn--ghost:hover { opacity: 0.75; }4068  `;4069  shadow.appendChild(style);40704071  const wrap = document.createElement("div");4072  wrap.className = "avail-wrap";4073  shadow.appendChild(wrap);40744075  const avail = document.createElement("div");4076  avail.className = "avail";4077  wrap.appendChild(avail);40784079  const closeBtn = document.createElement("button");4080  closeBtn.className = "avail-close";4081  closeBtn.type = "button";4082  closeBtn.setAttribute("aria-label", "Dismiss");4083  closeBtn.textContent = "✕";4084  avail.appendChild(closeBtn);40854086  const header = document.createElement("div");4087  header.className = "avail-header";4088  const icon = document.createElement("span");4089  icon.innerHTML = peachIconSvg();4090  const domainEl = document.createElement("span");4091  domainEl.className = "avail-domain";4092  domainEl.textContent = domain;4093  header.append(icon, domainEl);4094  avail.appendChild(header);40954096  const label = document.createElement("div");4097  label.className = "avail-label";4098  label.textContent = "PASSKEY";4099  avail.appendChild(label);41004101  const user = document.createElement("div");4102  user.className = "avail-user";4103  user.textContent = args.userName;4104  avail.appendChild(user);41054106  if (crossBrowser) {4107    const cross = document.createElement("div");4108    cross.className = "avail-cross";4109    cross.textContent =4110      args.fromBrowser === "chrome"4111        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."4112        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";4113    avail.appendChild(cross);4114  }41154116  const signInBtn = document.createElement("button");4117  signInBtn.className = "avail-btn avail-btn--accent";4118  signInBtn.type = "button";4119  signInBtn.textContent = "Sign in with passkey";4120  avail.appendChild(signInBtn);41214122  const passwordBtn = document.createElement("button");4123  passwordBtn.className = "avail-btn avail-btn--ghost";4124  passwordBtn.type = "button";4125  passwordBtn.textContent = "Use password instead";4126  avail.appendChild(passwordBtn);41274128  function dismiss() {4129    wrap.classList.add("is-exiting");4130    setTimeout(() => host.remove(), 130);4131  }41324133  signInBtn.addEventListener("click", () => {4134    // On Chrome: the user clicking the page's own Sign-in button is what4135    //   triggers webAuthenticationProxy → existing background flow handles it.4136    //   Our button just dismisses since the page itself drives auth.4137    // On Firefox: cross-browser passkeys can't be used, so we just dismiss4138    //   and surface the entry for manual reference (popup view).4139    dismiss();4140    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});4141  });4142  passwordBtn.addEventListener("click", dismiss);4143  closeBtn.addEventListener("click", dismiss);41444145  document.body.appendChild(host);4146}41474148/**4149 * State 7 — card silver platter. Single-card focused fill view rendered4150 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the4151 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes4152 * so card and login flows render identically. Multi-card list view is a4153 * follow-up; today this picks the first card.4154 */4155export function showCardSelector(4156  anchorEl: HTMLInputElement,4157  cards: CardSelectorEntry[],4158  options: CardSelectorOptions4159): () => void {4160  if (cards.length === 0) return () => {};4161  const card = cards[0]!;4162  let capabilityActionClaimed = false;4163  const claimCapabilityAction = () => {4164    if (!options.capability) return true;4165    if (capabilityActionClaimed) return false;4166    capabilityActionClaimed = true;4167    return true;4168  };41694170  const host = document.createElement("div");4171  host.style.cssText = "position: absolute; z-index: 2147483647;";4172  host.style.setProperty("--peach-accent", accentHex);4173  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));4174  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));4175  const shadow = host.attachShadow({ mode: "closed" });41764177  const style = shadow.appendChild(document.createElement("style"));4178  style.textContent = SELECTOR_STYLES;41794180  const rect = anchorEl.getBoundingClientRect();4181  host.style.top = `${rect.bottom + window.scrollY + 5}px`;4182  host.style.left = `${rect.left + window.scrollX}px`;4183  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;41844185  const container = shadow.appendChild(document.createElement("div"));4186  container.className = "peach-inline-popup";4187  container.setAttribute("data-theme", popupTheme);41884189  // Domain header — eyebrow communicates the card context, not the site4190  const domHdr = document.createElement("div");4191  domHdr.className = "domain-header";4192  const eyebrow = document.createElement("div");4193  eyebrow.className = "domain-eyebrow";4194  eyebrow.textContent = "Pay with Peach";4195  const domName = document.createElement("div");4196  domName.className = "domain-name";4197  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");4198  domHdr.append(eyebrow, domName);4199  container.appendChild(domHdr);42004201  const platter = document.createElement("div");4202  platter.className = "card-platter";42034204  if (card.network && card.network !== "unknown") {4205    const net = document.createElement("div");4206    net.className = "cp-network";4207    net.textContent = card.network;4208    platter.appendChild(net);4209  }42104211  const nick = document.createElement("div");4212  nick.className = "cp-nickname";4213  nick.textContent = card.title;4214  platter.appendChild(nick);42154216  if (card.last4) {4217    const l4 = document.createElement("div");4218    l4.className = "cp-last4";4219    l4.textContent = `•••• ${card.last4}`;4220    platter.appendChild(l4);4221  }42224223  const meta = document.createElement("div");4224  meta.className = "cp-meta";4225  if (card.cardholderName) {4226    const name = document.createElement("span");4227    name.textContent = card.cardholderName;4228    meta.appendChild(name);4229  }4230  if (card.expMonth && card.expYear) {4231    if (card.cardholderName) {4232      const sep = document.createElement("span");4233      sep.className = "cp-meta-sep";4234      sep.textContent = "·";4235      meta.appendChild(sep);4236    }4237    const exp = document.createElement("span");4238    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4239    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4240    meta.appendChild(exp);4241  }4242  if (meta.childElementCount > 0) platter.appendChild(meta);42434244  const fillWrap = document.createElement("div");4245  fillWrap.className = "cp-fill-wrap";4246  const fillBtn = document.createElement("button");4247  fillBtn.className = "sp-fill-btn";4248  fillBtn.type = "button";4249  fillBtn.textContent = "Fill card details";4250  fillBtn.addEventListener("click", async () => {4251    if (fillBtn.disabled || !claimCapabilityAction()) return;4252    fillBtn.disabled = true;4253    fillBtn.classList.add("filled");4254    fillBtn.innerHTML = checkSvgStr();4255    const resp = await chrome.runtime.sendMessage({4256      type: "GET_ENTRY_FOR_FILL",4257      // MV-1: explicit user click to fill this card's details.4258      payload: { id: card.id, capability: options.capability },4259    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4260    if (resp?.ok && resp.data) options.onFill(resp.data);4261    setTimeout(() => dismiss(), 400);4262  });4263  fillWrap.appendChild(fillBtn);4264  platter.appendChild(fillWrap);42654266  // Secondary actions — copy number, copy CVC, dismiss4267  const actions = document.createElement("div");4268  actions.className = "sp-actions";42694270  function flashBtn(b: HTMLButtonElement) {4271    b.classList.add("flashed");4272    setTimeout(() => b.classList.remove("flashed"), 700);4273  }42744275  // M3/QUA-005: clipboard + background COPY both failed — show user.4276  function flashCopyError(b: HTMLButtonElement) {4277    const original = b.textContent ?? "";4278    b.textContent = "Blocked";4279    b.classList.add("flashed");4280    setTimeout(() => {4281      b.classList.remove("flashed");4282      if (b.isConnected) b.textContent = original;4283    }, 1200);4284  }42854286  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4287    if (!claimCapabilityAction()) return null;4288    const resp = await chrome.runtime.sendMessage({4289      type: "GET_ENTRY_FOR_FILL",4290      // MV-1: explicit user action on a card the user opened in Peach's UI.4291      payload: { id: card.id, capability: options.capability },4292    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4293    const full = resp?.ok && resp.data ? resp.data : null;4294    if (options.capability) dismiss();4295    return full;4296  }42974298  const copyNum = document.createElement("button");4299  copyNum.className = "sp-action-btn";4300  copyNum.type = "button";4301  copyNum.title = "Copy card number";4302  copyNum.textContent = "Copy number";4303  copyNum.addEventListener("click", async (e) => {4304    e.stopPropagation();4305    const full = await fetchFullCard();4306    if (!full?.cardNumber) return;4307    let alreadyWritten = false;4308    try {4309      await navigator.clipboard.writeText(full.cardNumber);4310      alreadyWritten = true;4311    } catch (err) {4312      console.warn("[Peach] clipboard write denied:", err);4313    }4314    const resp = await chrome.runtime.sendMessage({4315      type: "COPY",4316      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4317    }).catch(() => null) as { ok?: boolean } | null;4318    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4319    else flashCopyError(copyNum);4320  });4321  actions.appendChild(copyNum);43224323  const copyCvc = document.createElement("button");4324  copyCvc.className = "sp-action-btn";4325  copyCvc.type = "button";4326  copyCvc.title = "Copy CVC";4327  copyCvc.textContent = "Copy CVC";4328  copyCvc.addEventListener("click", async (e) => {4329    e.stopPropagation();4330    const full = await fetchFullCard();4331    if (!full?.cvc) return;4332    let alreadyWritten = false;4333    try {4334      await navigator.clipboard.writeText(full.cvc);4335      alreadyWritten = true;4336    } catch (err) {4337      console.warn("[Peach] clipboard write denied:", err);4338    }4339    const resp = await chrome.runtime.sendMessage({4340      type: "COPY",4341      payload: { text: full.cvc, label: "CVC", alreadyWritten },4342    }).catch(() => null) as { ok?: boolean } | null;4343    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4344    else flashCopyError(copyCvc);4345  });4346  actions.appendChild(copyCvc);43474348  const closeBtn = document.createElement("button");4349  closeBtn.className = "sp-action-btn";4350  closeBtn.type = "button";4351  closeBtn.title = "Dismiss";4352  closeBtn.textContent = "✕";4353  closeBtn.addEventListener("click", (e) => {4354    e.stopPropagation();4355    dismiss(true);4356  });4357  actions.appendChild(closeBtn);43584359  platter.appendChild(actions);4360  container.appendChild(platter);43614362  document.body.appendChild(host);4363  function updatePosition() {4364    const r = anchorEl.getBoundingClientRect();4365    host.style.top = `${r.bottom + window.scrollY + 5}px`;4366    host.style.left = `${r.left + window.scrollX}px`;4367  }4368  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);43694370  function onKeyDown(e: KeyboardEvent) {4371    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4372  }4373  document.addEventListener("keydown", onKeyDown);43744375  let exitScheduled = false;4376  function dismiss(userAction = false) {4377    if (exitScheduled) return;4378    exitScheduled = true;4379    stopObserving();4380    document.removeEventListener("click", outsideClick, { capture: true });4381    document.removeEventListener("keydown", onKeyDown);4382    if (userAction) options.onDismiss?.();4383    container.classList.add("is-exiting");4384    setTimeout(() => host.remove(), 130);4385  }43864387  function outsideClick(ev: MouseEvent) {4388    const path = ev.composedPath();4389    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4390  }4391  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);43924393  return dismiss;4394}