inject.ts

176.9 KB · raw

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