inject.ts

167.6 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { generatePassword } from "../shared/generate";14import { detectPasswordPolicy } from "./policy";15import {16  filterSavedIdentities,17  identityFilterLabel,18  resolveCustomIdentityKind,19  type IdentityFilterMode,20  type IdentityKind,21} from "./identity-helper";2223let accentHex = "#E8956D";24let popupTheme: "dark" | "light" = "dark";25chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {26  const data = resp?.data;27  const name = data?.accentColor ?? "peach";28  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";29  popupTheme = data?.theme === "light" ? "light" : "dark";30});3132// 8-digit hex alpha helpers for the accent-derived shadow tokens.33// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing34// two hex digits as the alpha channel.35function withAlpha(hex: string, alpha: string): string {36  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS37  // always exposes 6-digit hex, so this is a guard against future changes38  // shipping shorthand colors that would silently break the var injection.39  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;40}4142export interface SelectorEntry {43  id: string;44  title: string;45  username?: string;46  email?: string;47  url?: string;48  hasTotp?: boolean;49  /** True when the entry also has a passkey credential attached. */50  hasPasskey?: boolean;51}5253interface SelectorOptions {54  domain?: string;55  /** Browser-issued one-shot authorization for a user-summoned cross-origin selection. */56  capability?: string;57  searchableEntries?: SelectorEntry[];58  /**59   * MV-2: lazy loader for the vault-wide searchable list. Invoked only on an60   * explicit user search gesture, never on passive popup open, so the full61   * account inventory never ships into the page world unless the user asks.62   * Result is cached for the popup's lifetime.63   */64  loadSearchableEntries?: () => Promise<SelectorEntry[]>;65  /** True when shown on a signup form — changes header label and entry-click behaviour */66  isSignup?: boolean;67  /**68   * Identity kind the current signup field is expecting. Used to avoid69   * assuming email when the user is actually filling a username.70   */71  identityKind?: IdentityKind;72  /**73   * Derived identity list (emails then usernames) for signup mode (State 10).74   * When present, renderIdentityHelper() is used instead of renderList().75   */76  savedIdentities?: SavedIdentity[];77  /**78   * Called after the user picks a saved identity (signup mode only) or79   * after successfully saving a new entry on a signup form.80   * Lets the caller fill the visible username + password fields.81   */82  onFillFields?: (username: string, password: string, email?: string) => void;83  /**84   * True when the form has both a distinct username field AND a distinct email85   * field (e.g. Name / Username / Email / Password signup forms). Enables the86   * two-step identity wizard: first pick the field type the user clicked on,87   * then pick the other, then generate a password.88   */89  hasEmailField?: boolean;90  /**91   * When true, show an inline unlock form instead of the entries list.92   * Used when the vault is locked so the user can unlock without opening93   * the popup.94   */95  locked?: boolean;96  /**97   * Called after a successful inline unlock — the caller should re-query98   * entries and re-open the selector with real data.99   */100  onUnlocked?: () => void;101  /**102   * Called when the user explicitly dismisses the selector (Escape, Tab, or103   * click outside) — NOT when an entry is selected or on auto-close.104   * Used by the caller to suppress spurious reopens on the same field.105   */106  onDismiss?: () => void;107}108109function getDomainFromUrl(url: string): string {110  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }111}112113function keySvgStr(): string {114  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>`;115}116117function plusSvgStr(): string {118  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>`;119}120121function searchSvgStr(): string {122  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>`;123}124125function backSvgStr(): string {126  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>`;127}128129function peachIconSvg(): string {130  // Peach body stays brand-peach regardless of `accentHex` — a sage or131  // sky accent must not turn the autofill icon green or blue. Accent132  // color still tints surrounding glow/hover halos below.133  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>`;134}135136function checkSvgStr(): string {137  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>`;138}139140function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {141  const { hostname, origin } = location;142  const parts = hostname.split(".");143  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",144    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",145    "oidc", "federation", "saml", "cas", "ldap"];146  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());147  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;148  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);149  return { origin, title, loginSubdomain };150}151152/**153 * Shows a bottom-of-page toast after filling credentials when the entry has154 * never matched the current site — offering to add the current origin to the155 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.156 */157export function showRememberSiteToast(158  pageDomain: string,159  entryId: string,160): void {161  const host = document.createElement("div");162  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";163  host.style.setProperty("--peach-accent", accentHex);164  const shadow = host.attachShadow({ mode: "closed" });165166  const style = document.createElement("style");167  style.textContent = `168    .bar {169      display:flex;align-items:center;gap:10px;padding:10px 14px;170      background:#131109;border:1px solid rgba(240,232,216,0.09);171      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);172      font-family:Inter,sans-serif;white-space:nowrap;173      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;174    }175    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }176    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }177    .yes {178      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;179      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;180    }181    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }182    .no {183      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;184      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;185    }186  `;187  shadow.appendChild(style);188189  const bar = document.createElement("div"); bar.className = "bar";190  const txt = document.createElement("span"); txt.className = "txt";191  txt.textContent = `Remember ${pageDomain} for this entry?`;192  const yesBtn = document.createElement("button"); yesBtn.className = "yes";193  yesBtn.textContent = "Remember";194  yesBtn.addEventListener("click", async () => {195    // The write itself is popup-confirmed: growing an entry's domain set is196    // the one autofill decision a page must not make for itself, because the197    // domain set is what gates future fills (PB-26-106).198    await chrome.runtime.sendMessage({199      type: "REQUEST_REMEMBER_SITE",200      payload: { id: entryId, url: location.origin },201    });202    host.remove();203  });204  const noBtn = document.createElement("button"); noBtn.className = "no";205  noBtn.textContent = "Not now";206  noBtn.addEventListener("click", () => host.remove());207  bar.append(txt, yesBtn, noBtn);208  shadow.appendChild(bar);209  document.body.appendChild(host);210  setTimeout(() => host.remove(), 9000);211}212213// Module handle so a second auto-copy resets the dismiss timer rather than214// letting the first toast's teardown race the replacement.215let totpToastDismissTimer: ReturnType<typeof setTimeout> | null = null;216217/**218 * Shows a brief top-right toast when Peach automatically copies a TOTP code,219 * telling the user how long until the clipboard self-clears. Auto-dismisses220 * after 3s; a second call while visible replaces the toast and resets the timer.221 * Rendered in the light DOM (not a closed shadow) so the copy is announced to222 * assistive tech via aria-live — the code itself is never placed in the DOM.223 */224export function showTotpCopyToast(secondsUntilClear: number): void {225  document.getElementById("peach-totp-toast")?.remove();226  if (totpToastDismissTimer) {227    clearTimeout(totpToastDismissTimer);228    totpToastDismissTimer = null;229  }230231  const toast = document.createElement("div");232  toast.id = "peach-totp-toast";233  toast.className = "peach-totp-toast";234  toast.setAttribute("data-peach-toast", "totp-copy");235  toast.setAttribute("aria-live", "polite");236237  // Inline styles — matches the passkey toast family (warm, minimal, top right).238  Object.assign(toast.style, {239    position: "fixed",240    top: "16px",241    right: "16px",242    zIndex: "2147483647",243    padding: "10px 14px",244    borderRadius: "8px",245    background: "rgba(30, 20, 10, 0.92)",246    border: "1px solid rgba(210, 140, 60, 0.3)",247    color: "#e8d5b0",248    fontFamily: '"IBM Plex Mono", monospace',249    fontSize: "11px",250    lineHeight: "1.5",251    boxShadow: "0 4px 24px rgba(0,0,0,0.4)",252    pointerEvents: "none",253  });254255  // secondsUntilClear is a typed number — safe to interpolate; no page-derived256  // string ever reaches this markup.257  toast.innerHTML = `258    <div style="font-style: italic; font-family: 'Cormorant Garamond', serif; font-size: 13px; margin-bottom: 2px;">259      2FA code copied260    </div>261    <div style="opacity: 0.6; font-size: 10px;">262      clears in ${secondsUntilClear}s263    </div>264  `;265266  document.body.appendChild(toast);267268  totpToastDismissTimer = setTimeout(() => {269    totpToastDismissTimer = null;270    toast.style.transition = "opacity 0.3s ease";271    toast.style.opacity = "0";272    setTimeout(() => toast.remove(), 300);273  }, 3000);274}275276interface SmartGenerator {277  root: HTMLElement;278  getPassword: () => string;279  /** Copy the current password to the clipboard with the standard pulse UX. */280  copy: () => Promise<void>;281}282283interface SmartGeneratorOptions {284  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */285  policy: PasswordPolicy;286  /**287   * Seed value: used as the displayed password without regenerating, e.g. the288   * password the user already typed into the page. The generator still289   * regenerates the moment any control changes.290   */291  initialPassword?: string;292  /** Fires every time the password regenerates (initial + on changes). */293  onChange?: (pw: string) => void;294}295296/**297 * Build the inline-popup smart-password generator. Mirrors the main popup's298 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset299 * pills + a policy hint that names the constraints Peach detected on the300 * page. Writing this in pure DOM rather than reusing the Solid component301 * keeps the content-script bundle small.302 */303function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {304  const policy = opts.policy ?? {};305306  // Start at site max (strongest password the site accepts), fall back to 64307  let length = policy.maxLength ?? 64;308  if (policy.minLength) length = Math.max(length, policy.minLength);309  if (length < 8) length = 8;310  if (length > 128) length = 128;311312  let upper = true;313  let lower = true;314  let numbers = true;315  let symbols = !policy.forbidsSymbols;316  if (policy.requiresSymbols) symbols = true;317  const forbiddenChars = policy.forbiddenChars ?? "";318319  let password = "";320321  const root = document.createElement("div");322  root.className = "pwgen-block";323324  const displayRow = root.appendChild(document.createElement("div"));325  displayRow.className = "pwgen-display-row";326  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;327  output.type = "text";328  output.className = "pwgen-output";329  output.setAttribute("autocomplete", "off");330  output.setAttribute("spellcheck", "false");331  output.setAttribute("autocorrect", "off");332  output.setAttribute("autocapitalize", "off");333334  const regenBtn = displayRow.appendChild(document.createElement("button"));335  regenBtn.className = "pwgen-icon-btn";336  regenBtn.type = "button";337  regenBtn.setAttribute("aria-label", "Regenerate password");338  regenBtn.title = "Regenerate";339  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>`;340341  const copyBtn = displayRow.appendChild(document.createElement("button"));342  copyBtn.className = "pwgen-icon-btn";343  copyBtn.type = "button";344  copyBtn.setAttribute("aria-label", "Copy password");345  copyBtn.title = "Copy";346  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>`;347348  const controls = root.appendChild(document.createElement("div"));349  controls.className = "pwgen-controls-row";350  const slider = controls.appendChild(document.createElement("input"));351  slider.type = "range";352  slider.className = "pwgen-slider";353  slider.min = "8";354  slider.max = "128";355  slider.value = String(length);356  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));357  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));358  const lenNum = controls.appendChild(document.createElement("span"));359  lenNum.className = "pwgen-len-num pwgen-len-num--edit";360  lenNum.textContent = String(length);361  lenNum.addEventListener("click", () => {362    const li = document.createElement("input");363    li.type = "text"; li.inputMode = "numeric";364    li.className = "pwgen-len-input"; li.value = String(length);365    lenNum.replaceWith(li);366    requestAnimationFrame(() => li.select());367    function commitLenEdit() {368      const n = parseInt(li.value, 10);369      if (!Number.isNaN(n)) {370        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));371        slider.value = String(length);372        regenerate();373      }374      lenNum.textContent = String(length);375      li.replaceWith(lenNum);376    }377    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });378    li.addEventListener("blur", commitLenEdit);379  });380381  const pills = root.appendChild(document.createElement("div"));382  pills.className = "pwgen-pills";383384  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {385    const b = document.createElement("button");386    b.type = "button";387    b.className = `pwgen-pill ${on ? "is-on" : ""}`;388    b.textContent = label;389    b.addEventListener("click", () => {390      const next = !b.classList.contains("is-on");391      b.classList.toggle("is-on", next);392      onToggle(next);393    });394    return b;395  }396  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));397  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));398  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));399  pills.appendChild(makePill("!@#", symbols, (next) => {400    // The site forbids symbols — UI lets the user override but still warn.401    symbols = next;402    regenerate();403  }));404405  // Policy hint — surfaces what Peach read off the site so the user knows the406  // generator is already tuned to it. Only shows when something interesting407  // was detected.408  const hintParts: string[] = [];409  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);410  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);411  if (policy.requiresSymbols) hintParts.push("requires symbols");412  if (policy.forbidsSymbols) hintParts.push("no symbols");413  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);414  if (hintParts.length > 0) {415    const hint = root.appendChild(document.createElement("div"));416    hint.className = "pwgen-policy-hint";417    const accent = document.createElement("span");418    accent.className = "pwgen-hint-accent";419    accent.textContent = "site rules · ";420    const text = document.createTextNode(hintParts.join(" · "));421    hint.appendChild(accent);422    hint.appendChild(text);423  }424425  function regenerate() {426    // Falls back gracefully when the user toggles every charset off — the427    // shared generator forces lowercase in that case rather than throwing.428    password = generatePassword({429      length,430      includeUppercase: upper,431      includeLowercase: lower,432      includeNumbers: numbers,433      includeSymbols: symbols,434      forbiddenChars,435    });436    output.value = password;437    opts.onChange?.(password);438  }439440  output.addEventListener("input", () => {441    password = output.value;442    length = password.length;443    slider.value = String(Math.max(8, Math.min(128, length)));444    lenNum.textContent = String(length);445    opts.onChange?.(password);446  });447448  slider.addEventListener("input", () => {449    length = parseInt(slider.value, 10);450    lenNum.textContent = String(length);451    regenerate();452  });453  regenBtn.addEventListener("click", regenerate);454455  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;456  async function copy(): Promise<void> {457    try {458      await navigator.clipboard.writeText(password);459      copyBtn.classList.add("is-copied");460      if (copyResetTimer) clearTimeout(copyResetTimer);461      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);462    } catch {463      // Clipboard API may be denied — silently no-op; user still has regen UI.464    }465  }466  copyBtn.addEventListener("click", () => { void copy(); });467468  if (opts.initialPassword) {469    password = opts.initialPassword;470    output.value = password;471    opts.onChange?.(password);472  } else {473    regenerate();474  }475476  return {477    root,478    getPassword: () => password,479    copy,480  };481}482483export function observeAnchorPosition(484  anchorEl: HTMLElement,485  onUpdate: () => void486): () => void {487  let rafId = 0;488  let burstUntil = 0;489490  const runUpdate = () => {491    rafId = 0;492    onUpdate();493    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);494  };495  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };496  const scheduleBurst = (ms = 220) => {497    burstUntil = Math.max(burstUntil, performance.now() + ms);498    scheduleUpdate();499  };500501  const resizeObserver = new ResizeObserver(() => scheduleBurst());502  resizeObserver.observe(anchorEl);503  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);504505  const mutationObserver = new MutationObserver(() => scheduleBurst());506  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });507  if (anchorEl.parentElement) {508    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });509  }510511  const onScroll = () => scheduleUpdate();512  window.addEventListener("scroll", onScroll, true);513  window.addEventListener("resize", onScroll);514  window.visualViewport?.addEventListener("resize", onScroll);515  window.visualViewport?.addEventListener("scroll", onScroll);516  anchorEl.addEventListener("focus", () => scheduleBurst());517  anchorEl.addEventListener("input", () => scheduleBurst());518519  scheduleBurst(260);520521  return () => {522    if (rafId) cancelAnimationFrame(rafId);523    resizeObserver.disconnect();524    mutationObserver.disconnect();525    window.removeEventListener("scroll", onScroll, true);526    window.removeEventListener("resize", onScroll);527    window.visualViewport?.removeEventListener("resize", onScroll);528    window.visualViewport?.removeEventListener("scroll", onScroll);529  };530}531532export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {533  const button = document.createElement("button");534  button.type = "button";535  button.setAttribute("aria-label", "Peach autofill");536  button.title = "Fill with Peach";537  button.innerHTML = peachIconSvg();538  // position: fixed is load-bearing — not absolute. Absolute positioning539  // inherits the nearest positioned ancestor's box, which on sites with540  // overflow:hidden or sticky parents clips or offsets the icon. Fixed541  // anchors to the viewport and escapes all parent layout.542  button.style.cssText = `543    position: fixed; z-index: 2147483646;544    width: 26px; height: 26px; cursor: pointer;545    pointer-events: auto; border: none; padding: 3px;546    display: inline-flex; align-items: center; justify-content: center;547    background: transparent; border-radius: 999px;548    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;549    opacity: 0;550  `;551  button.addEventListener("mouseenter", () => {552    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;553    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;554    button.style.transform = "scale(1.08)";555  });556  button.addEventListener("mouseleave", () => {557    button.style.background = "transparent";558    button.style.boxShadow = "none";559    button.style.transform = "none";560  });561  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });562  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });563564  document.body.appendChild(button);565566  function updatePosition() {567    const rect = field.getBoundingClientRect();568    if (rect.width === 0 || rect.height === 0) {569      button.style.opacity = "0"; button.style.pointerEvents = "none";570      return;571    }572    const sz = 26;573    const inset = Math.max(5, Math.min(10, rect.height * 0.22));574    const top = rect.top + rect.height / 2 - sz / 2;575    // Clamp left so the icon stays fully inside the field's right edge, never576    // spilling onto an adjacent sibling button.577    const minLeft = rect.left + 4;578    const left = Math.max(minLeft, rect.right - sz - inset);579    // Hide if the field is too narrow to fit the icon cleanly (< 40px)580    if (rect.width < 40) {581      button.style.opacity = "0"; button.style.pointerEvents = "none";582      return;583    }584    button.style.top = `${top}px`;585    button.style.left = `${left}px`;586    button.style.opacity = "1"; button.style.pointerEvents = "auto";587  }588  updatePosition();589  requestAnimationFrame(() => { button.style.opacity = "1"; });590  const stopObserving = observeAnchorPosition(field, updatePosition);591  return () => { stopObserving(); button.remove(); };592}593594// All theme-dependent values resolve through tokens scoped to595// .peach-inline-popup[data-theme="dark|light"]. Accent variables596// (--peach-accent, --peach-glow, --peach-border-accent)597// are identical in both themes — only surface tokens differ. See598// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the599// theme switch — only literal brand-peach in peachIconSvg may stay raw.600const SELECTOR_STYLES = `601  :host { all: initial; }602  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }603604  .peach-inline-popup[data-theme="dark"] {605    --peach-bg:           #1a1410;606    --peach-bg-card:      #221c16;607    --peach-text:         #f5f0ea;608    --peach-text-dim:     #8a7a6a;609    --peach-text-muted:   #4a3a2a;610    --peach-border:       rgba(255,255,255,0.07);611    --peach-input-bg:     rgba(255,255,255,0.05);612    --peach-input-border: rgba(255,255,255,0.08);613  }614  .peach-inline-popup[data-theme="light"] {615    --peach-bg:           #fdf8f4;616    --peach-bg-card:      #f5ede4;617    --peach-text:         #1c1310;618    --peach-text-dim:     #6b5a4a;619    --peach-text-muted:   #a89080;620    --peach-border:       rgba(0,0,0,0.08);621    --peach-input-bg:     rgba(0,0,0,0.04);622    --peach-input-border: rgba(0,0,0,0.10);623  }624625  .peach-inline-popup {626    background: var(--peach-bg);627    border: 1px solid var(--peach-border-accent, var(--peach-border));628    border-radius: 14px;629    overflow: hidden;630    box-shadow:631      0 8px 40px var(--peach-glow, transparent),632      0 2px 12px rgba(0,0,0,0.5);633    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;634    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;635    transition: height 220ms cubic-bezier(0.16,1,0.3,1);636  }637  /* Light theme: shadow against a light page is too strong otherwise — drop both638     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */639  .peach-inline-popup[data-theme="light"] {640    box-shadow:641      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),642      0 2px 12px rgba(0,0,0,0.12);643  }644  .peach-inline-popup.is-exiting {645    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;646    pointer-events: none;647  }648649  @keyframes peach-enter {650    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }651    65%  { opacity: 1; filter: blur(0); }652    100% { opacity: 1; transform: translateY(0) scale(1); }653  }654  @keyframes peach-exit {655    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }656    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }657  }658  @keyframes peach-slide-in {659    from { opacity: 0; transform: translateX(12px); }660    to   { opacity: 1; transform: translateX(0); }661  }662  @keyframes peach-slide-back {663    from { opacity: 0; transform: translateX(-12px); }664    to   { opacity: 1; transform: translateX(0); }665  }666  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }667  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }668669  /* Domain header */670  .domain-header {671    padding: 9px 13px 7px;672    border-bottom: 1px solid var(--peach-border);673    display: flex; align-items: center; justify-content: space-between;674    gap: 8px;675  }676  .domain-header-text {677    display: flex; flex-direction: column; gap: 2px;678    min-width: 0; flex: 1;679  }680  .domain-eyebrow {681    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;682    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;683  }684  .domain-name {685    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);686    font-family: "IBM Plex Mono", monospace;687    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;688  }689  .domain-header-actions {690    display: inline-flex; align-items: center; gap: 5px;691    flex-shrink: 0;692  }693  .domain-add-btn,694  .domain-search-btn {695    flex-shrink: 0;696    width: 22px; height: 22px;697    display: inline-flex; align-items: center; justify-content: center;698    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);699    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);700    border-radius: 6px;701    color: var(--peach-accent);702    cursor: pointer; padding: 0;703    transition: background 120ms, border-color 120ms, transform 80ms;704    font-family: "IBM Plex Mono", monospace;705    font-size: 14px; line-height: 1;706  }707  .domain-add-btn:hover,708  .domain-search-btn:hover {709    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);710    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);711    transform: scale(1.06);712  }713  .domain-add-btn:active,714  .domain-search-btn:active { transform: scale(0.96); }715716  /* Search */717  .search-wrap {718    padding: 9px 12px 7px;719    border-bottom: 1px solid var(--peach-border);720  }721  /* UI-2 / MV-2: brief loading hint while the vault-wide list lazy-loads. */722  .search-loading {723    display: block;724    margin-top: 5px;725    font-size: 10px;726    color: var(--peach-text-dim);727    font-family: "IBM Plex Mono", monospace;728    animation: search-loading-pulse 1s ease-in-out infinite;729  }730  @keyframes search-loading-pulse { 0%,100% { opacity: 0.45; } 50% { opacity: 0.9; } }731  .search {732    width: 100%; background: var(--peach-input-bg);733    border: 1px solid var(--peach-input-border);734    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;735    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;736    transition: border-color 120ms, box-shadow 120ms;737  }738  .search:focus {739    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);740    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);741  }742  .search::placeholder { color: var(--peach-text-muted); }743744  /* Results */745  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }746  .results::-webkit-scrollbar { display: none; }747748  /* Entry rows */749  .entry {750    display: flex; align-items: center; padding: 8px 12px;751    cursor: pointer; border-bottom: 1px solid var(--peach-border);752    transition: background 70ms; position: relative; outline: none;753  }754  .entry:last-child { border-bottom: none; }755  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }756  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }757  .entry.focused::before {758    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;759    width: 2px; border-radius: 2px;760    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);761  }762763  .entry-icon {764    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;765    background: var(--peach-input-bg); border: 1px solid var(--peach-border);766    display: flex; align-items: center; justify-content: center;767    overflow: hidden; margin-right: 10px;768  }769  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }770  .entry-icon.is-new {771    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);772    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);773    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);774  }775776  .entry-info { flex: 1; min-width: 0; }777  .entry-title {778    font-size: 12.5px; color: var(--peach-text);779    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;780    line-height: 1.3;781  }782  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }783  .entry-sub {784    font-size: 10px; color: var(--peach-text-dim);785    font-family: "IBM Plex Mono", monospace;786    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;787    margin-top: 1px;788  }789790  .totp-badge {791    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;792    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);793    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);794    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;795  }796  .passkey-badge {797    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;798    border-radius: 4px;799    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);800    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);801    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);802    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;803  }804805  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }806807  .empty-hint {808    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);809    font-family: "IBM Plex Mono", monospace;810  }811812  /* Create form */813  .create-form-wrap {814    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;815  }816  .create-head {817    display: flex; align-items: center; gap: 8px;818    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);819  }820  .back-btn {821    background: transparent; border: none; cursor: pointer;822    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;823    display: flex; align-items: center; line-height: 0;824    transition: color 100ms, background 100ms;825  }826  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }827  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }828  /* minmax(0, 1fr) caps the grid track at the popup width — without it,829     long monospace content (e.g. a 60-char generated password) would830     auto-size the track wider than the popup and overflow the right edge. */831  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }832  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }833  .f-label {834    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;835    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;836  }837  .f-input {838    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);839    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;840    font-size: 11px; font-family: "IBM Plex Mono", monospace;841    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;842  }843  .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); }844  .f-input::placeholder { color: var(--peach-text-muted); }845  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }846  .f-row { display: flex; gap: 6px; }847  .f-row .f-input { flex: 1; min-width: 0; }848  .gen-btn {849    padding: 0 10px; border-radius: 7px; border: none;850    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);851    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);852    font-size: 10px; font-family: "IBM Plex Mono", monospace;853    cursor: pointer; white-space: nowrap; flex-shrink: 0;854    display: flex; align-items: center; gap: 4px;855    transition: background 100ms;856  }857  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }858  .gen-toggle-link {859    background: none; border: none; padding: 2px 0;860    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);861    font-size: 10px; font-family: "IBM Plex Mono", monospace;862    cursor: pointer; text-align: left; transition: color 100ms;863  }864  .gen-toggle-link:hover { color: var(--peach-accent); }865  .pw-history {866    display: grid; gap: 4px; margin-top: 4px;867    max-height: 150px; overflow-y: auto; scrollbar-width: thin;868  }869  .pw-history-row {870    display: flex; align-items: center; justify-content: space-between; gap: 6px;871    padding: 5px 7px; border-radius: 7px;872    background: color-mix(in srgb, var(--peach-accent) 6%, transparent);873    border: 1px solid color-mix(in srgb, var(--peach-accent) 10%, transparent);874  }875  .pw-history-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }876  .pw-history-pw {877    font-family: "IBM Plex Mono", monospace; font-size: 11px;878    color: var(--peach-t1, #eee); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;879  }880  .pw-history-age {881    font-family: "IBM Plex Mono", monospace; font-size: 9px;882    color: color-mix(in srgb, var(--peach-accent) 55%, transparent); letter-spacing: 0.03em;883  }884  .pw-history-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }885  .pw-history-btn {886    background: none; border: none; padding: 2px 5px; border-radius: 5px;887    color: color-mix(in srgb, var(--peach-accent) 65%, transparent);888    font-size: 9px; font-family: "IBM Plex Mono", monospace; cursor: pointer;889    transition: color 100ms, background 100ms;890  }891  .pw-history-btn:hover {892    color: var(--peach-accent);893    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);894  }895  .pw-history-empty {896    font-family: "IBM Plex Mono", monospace; font-size: 10px; line-height: 1.45;897    color: color-mix(in srgb, var(--peach-accent) 55%, transparent);898    padding: 6px 8px; border-radius: 7px;899    background: color-mix(in srgb, var(--peach-accent) 5%, transparent);900    border: 1px solid color-mix(in srgb, var(--peach-accent) 9%, transparent);901  }902  .save-btn {903    width: 100%; padding: 8px; border-radius: 8px; border: none;904    background: var(--peach-accent); color: #fff; font-size: 12px;905    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;906    transition: background 120ms, box-shadow 120ms, transform 80ms;907    letter-spacing: 0.01em;908  }909  .save-btn:hover {910    background: color-mix(in srgb, var(--peach-accent) 82%, #000);911    box-shadow: 0 4px 20px var(--peach-glow, transparent);912  }913  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }914  .url-hint {915    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);916    font-family: "IBM Plex Mono", monospace; font-style: italic;917  }918919  /* Success */920  .success-wrap {921    display: flex; flex-direction: column; align-items: center;922    padding: 24px 16px 20px; gap: 8px;923    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;924  }925  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }926  .success-ring {927    width: 40px; height: 40px; border-radius: 50%;928    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);929    display: flex; align-items: center; justify-content: center;930  }931  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }932  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }933934  /* Silver platter (State 1 — single match) */935  .silver-platter {936    padding: 14px 14px 12px;937    display: flex; flex-direction: column; gap: 6px;938  }939  .sp-title {940    font-size: 14px; font-weight: 500; color: var(--peach-text);941    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;942    line-height: 1.25;943  }944  .sp-identity-row {945    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;946  }947  .sp-identity-label {948    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;949    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;950  }951  .sp-username {952    font-size: 12px; color: var(--peach-text-dim);953    font-family: "IBM Plex Mono", monospace;954    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;955    margin-bottom: 0;956  }957  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }958  .sp-fill-btn {959    width: 100%; padding: 11px; border-radius: 9px; border: none;960    background: var(--peach-accent); color: #fff;961    font-size: 13px; font-weight: 500; cursor: pointer;962    font-family: Inter, sans-serif; letter-spacing: 0.01em;963    display: flex; align-items: center; justify-content: center; min-height: 38px;964    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;965  }966  .sp-fill-btn:hover {967    filter: brightness(1.1);968    box-shadow: 0 4px 20px var(--peach-glow, transparent);969    transform: translateY(-1px);970  }971  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }972  .sp-fill-btn.filled {973    background: #16a34a; transform: none; filter: none;974    box-shadow: 0 4px 16px rgba(22,163,74,0.35);975    cursor: default;976  }977  .sp-fill-btn:disabled { cursor: default; }978  .sp-actions-group {979    margin-top: 6px;980    display: flex; flex-direction: column; gap: 4px;981  }982  .sp-actions-label {983    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;984    color: var(--peach-text-muted);985    font-family: "IBM Plex Mono", monospace;986    text-align: center;987  }988  .sp-actions {989    display: flex; gap: 4px; justify-content: space-between; align-items: center;990  }991  .sp-action-btn {992    flex: 1; height: 28px; border: none; border-radius: 6px;993    background: transparent; color: var(--peach-text-dim);994    font-size: 12px; cursor: pointer;995    transition: background 120ms ease, color 120ms ease;996    font-family: Inter, sans-serif; letter-spacing: 0.04em;997    display: inline-flex; align-items: center; justify-content: center; gap: 4px;998    white-space: nowrap; overflow: hidden;999  }1000  .sp-action-btn:hover:not(:disabled) {1001    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1002    color: var(--peach-text);1003  }1004  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }1005  .sp-action-btn.flashed {1006    color: var(--peach-accent);1007    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1008  }10091010  /* TOTP tray — shown below the silver-platter secondary actions */1011  .sp-tray {1012    margin-top: 8px;1013    padding: 10px 12px;1014    border-radius: 9px;1015    background: var(--peach-input-bg);1016    border: 1px solid var(--peach-input-border);1017    display: flex; align-items: center; gap: 12px;1018    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;1019  }1020  .sp-tray-label {1021    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;1022    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;1023    flex-shrink: 0;1024  }1025  .sp-totp-code {1026    font-size: 18px; font-weight: 500;1027    color: var(--peach-text);1028    font-family: "IBM Plex Mono", monospace;1029    letter-spacing: 0.12em;1030    flex: 1;1031    text-align: center;1032  }1033  .sp-totp-ring {1034    width: 22px; height: 22px; flex-shrink: 0;1035  }1036  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }1037  .sp-totp-ring .ring-fill {1038    stroke: var(--peach-accent);1039    transition: stroke-dashoffset 1s linear;1040    transform: rotate(-90deg);1041    transform-origin: center;1042  }1043  .sp-totp-copy {1044    background: transparent; border: none; cursor: pointer;1045    padding: 4px 8px; border-radius: 5px;1046    color: var(--peach-text-dim); font-size: 11px;1047    font-family: Inter, sans-serif;1048    transition: background 120ms, color 120ms;1049  }1050  .sp-totp-copy:hover {1051    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1052    color: var(--peach-text);1053  }10541055  /* Card silver platter (State 7) — reuses .sp-* primary action classes */1056  .card-platter {1057    padding: 12px 14px 10px;1058    display: flex; flex-direction: column; gap: 4px;1059  }1060  .cp-network {1061    font-size: 10px; font-weight: 600;1062    color: var(--peach-accent);1063    letter-spacing: 0.08em; text-transform: uppercase;1064    font-family: Inter, sans-serif;1065  }1066  .cp-nickname {1067    font-size: 14px; font-weight: 500; color: var(--peach-text);1068    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1069    line-height: 1.2;1070  }1071  .cp-last4 {1072    font-size: 12px; color: var(--peach-text-dim);1073    font-family: "IBM Plex Mono", monospace;1074    letter-spacing: 0.04em;1075    margin-top: 2px;1076  }1077  .cp-meta {1078    font-size: 11px; color: var(--peach-text-dim);1079    font-family: "IBM Plex Mono", monospace;1080    margin-top: 2px;1081    display: flex; gap: 10px; align-items: center;1082  }1083  .cp-meta-sep { opacity: 0.5; }1084  .cp-fill-wrap { margin-top: 10px; }10851086  /* Locked state */1087  .locked-wrap {1088    display: flex; flex-direction: column; align-items: stretch;1089    padding: 14px 13px 13px; gap: 9px;1090  }1091  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }1092  .locked-icon {1093    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;1094    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1095    display: flex; align-items: center; justify-content: center;1096  }1097  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }1098  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }1099  .locked-input {1100    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1101    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;1102    font-size: 11px; font-family: "IBM Plex Mono", monospace;1103    outline: none; transition: border-color 120ms, box-shadow 120ms;1104  }1105  .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); }1106  .locked-input::placeholder { color: var(--peach-text-muted); }1107  .locked-btn {1108    width: 100%; padding: 8px; border-radius: 8px; border: none;1109    background: var(--peach-accent); color: #fff; font-size: 12px;1110    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;1111    transition: background 120ms;1112    letter-spacing: 0.01em;1113    box-shadow: 0 2px 16px var(--peach-glow, transparent);1114    animation: peach-pulse-glow 2.4s ease-in-out infinite;1115  }1116  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }1117  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }1118  .locked-error {1119    font-size: 10px; color: rgba(220,80,60,0.85);1120    font-family: "IBM Plex Mono", monospace;1121  }11221123  @keyframes peach-pulse-glow {1124    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }1125    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),1126                            0 0 48px var(--peach-glow, transparent); }1127  }11281129  /* ── State 10: identity helper ─────────────────────────────── */1130  .identity-list {1131    max-height: 192px; overflow-y: auto; padding: 4px 0;1132    scrollbar-width: none;1133  }1134  .identity-list::-webkit-scrollbar { display: none; }1135  .peach-identity-row {1136    display: flex; align-items: center; gap: 10px;1137    padding: 9px 12px; cursor: pointer; border-radius: 8px;1138    transition: background 100ms ease;1139  }1140  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1141  .peach-identity-value {1142    font-family: "IBM Plex Mono", monospace; font-size: 13px;1143    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1144  }1145  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1146  .identity-search-wrap {1147    display: flex; flex-direction: column; gap: 6px;1148  }1149  .identity-mode-toggle {1150    display: inline-flex; gap: 4px; flex-wrap: wrap;1151  }1152  .identity-mode-btn {1153    border: 1px solid var(--peach-input-border);1154    background: var(--peach-input-bg);1155    color: var(--peach-text-dim);1156    border-radius: 999px;1157    padding: 4px 9px;1158    cursor: pointer;1159    font-family: "IBM Plex Mono", monospace;1160    font-size: 9px;1161    letter-spacing: 0.03em;1162    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1163  }1164  .identity-mode-btn:hover {1165    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1166    color: var(--peach-text);1167  }1168  .identity-mode-btn.is-active {1169    color: var(--peach-accent);1170    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1171    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1172  }1173  .identity-mode-btn:active { transform: translateY(1px); }1174  .identity-custom-row {1175    display: flex; flex-direction: column; gap: 2px;1176    padding: 9px 12px; cursor: pointer; border-radius: 8px;1177    transition: background 100ms ease;1178  }1179  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1180  .identity-custom-row-title {1181    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1182  }1183  .identity-custom-row-sub {1184    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1185  }1186  .identity-empty {1187    padding: 10px 12px 2px; color: var(--peach-text-dim);1188    font-size: 10px; font-family: "IBM Plex Mono", monospace;1189  }1190  .identity-alt-row {1191    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1192    border-radius: 8px; transition: background 100ms ease;1193    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1194  }1195  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1196  .identity-escape-row {1197    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1198    border-radius: 8px; transition: background 100ms ease; outline: none;1199    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1200    margin-top: 2px;1201  }1202  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1203  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1204  .identity-alt-input-wrap.open { display: flex; }1205  .identity-alt-input {1206    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1207    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1208    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1209    outline: none; transition: border-color 120ms;1210  }1211  .identity-alt-input:focus {1212    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1213    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1214  }1215  .identity-alt-confirm {1216    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1217    background: var(--peach-accent); color: #fff; font-size: 12px;1218    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1219  }1220  /* ── Generator view (after identity picked) ────────────────── */1221  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1222  .gen-confirmed {1223    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1224    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1225    border-radius: 8px;1226  }1227  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1228  .gen-confirmed-val {1229    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1230    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1231  }1232  .gen-label {1233    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1234    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1235  }1236  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1237  .gen-pw-val {1238    flex: 1; padding: 8px 10px; border-radius: 7px;1239    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1240    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1241    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1242  }1243  .gen-regen-btn {1244    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1245    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1246    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1247    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1248  }1249  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1250  .gen-fill-btn {1251    padding: 10px; border-radius: 8px; border: none;1252    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1253    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1254    transition: filter 120ms ease, transform 80ms ease;1255  }1256  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1257  .gen-fill-btn:active { transform: translateY(0); }12581259  /* ── Smart password generator (parity with main UI compact mode) ─── */1260  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1261  .pwgen-display-row {1262    display: flex; align-items: center; gap: 6px;1263    padding: 8px 10px; border-radius: 7px;1264    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1265  }1266  .pwgen-output {1267    flex: 1; min-width: 0; width: 0;1268    font-family: "IBM Plex Mono", monospace; font-size: 12px;1269    color: var(--peach-text);1270    background: transparent; border: none; outline: none; padding: 0;1271  }1272  .pwgen-icon-btn {1273    flex-shrink: 0;1274    width: 26px; height: 26px;1275    display: inline-flex; align-items: center; justify-content: center;1276    background: transparent; border: 1px solid var(--peach-input-border);1277    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1278    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1279  }1280  .pwgen-icon-btn:hover {1281    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1282    color: var(--peach-accent);1283    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1284  }1285  .pwgen-icon-btn.is-copied {1286    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1287    color: var(--peach-accent);1288    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1289  }1290  .pwgen-controls-row {1291    display: flex; align-items: center; gap: 8px;1292    flex-wrap: wrap;1293  }1294  .pwgen-slider {1295    flex: 1; min-width: 110px;1296    accent-color: var(--peach-accent);1297    cursor: pointer; height: 2px; background: transparent;1298  }1299  .pwgen-len-num {1300    font-family: "IBM Plex Mono", monospace; font-size: 11px;1301    color: var(--peach-accent); min-width: 22px; text-align: right;1302  }1303  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1304  .pwgen-len-input {1305    font-family: "IBM Plex Mono", monospace; font-size: 11px;1306    color: var(--peach-accent); width: 28px; text-align: right;1307    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1308    outline: none; padding: 0; min-width: 22px;1309  }1310  @keyframes identity-suggest-in {1311    from { opacity: 0; transform: translateY(-4px); }1312    to   { opacity: 1; transform: none; }1313  }1314  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1315    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1316  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1317  .identity-collapse-btn {1318    margin-left: auto; background: transparent; border: none; cursor: pointer;1319    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1320    line-height: 0; border-radius: 3px;1321    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1322  }1323  .identity-collapse-btn:hover { color: var(--peach-text); }1324  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1325  .identity-rows { display: grid; grid-template-rows: 1fr;1326    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1327  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1328  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1329    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1330  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1331  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1332  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1333  .identity-filter-pill {1334    padding: 2px 7px; border-radius: 999px;1335    border: 1px solid var(--peach-input-border);1336    background: transparent; color: var(--peach-text-muted);1337    font-family: "IBM Plex Mono", monospace; font-size: 9px;1338    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1339  }1340  .identity-filter-pill.is-on {1341    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1342    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1343    color: var(--peach-accent);1344  }1345  .identity-suggest-row {1346    display: flex; align-items: center; gap: 5px;1347    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1348    background: transparent; cursor: pointer; text-align: left;1349    transition: background 80ms;1350  }1351  .identity-suggest-row:hover,1352  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1353  .identity-suggest-val {1354    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1355    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1356  }1357  .identity-suggest-type {1358    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1359    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1360  }1361  .identity-suggest-type--email {1362    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1363    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1364  }1365  .identity-suggest-type--username {1366    color: var(--peach-text-muted);1367    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1368  }1369  .identity-suggest-meta {1370    font-family: "IBM Plex Mono", monospace; font-size: 9px;1371    color: var(--peach-text-muted); flex-shrink: 0;1372  }1373  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1374  .pwgen-pill {1375    padding: 3px 8px; border-radius: 999px;1376    border: 1px solid var(--peach-input-border);1377    background: transparent; color: var(--peach-text-muted);1378    font-family: "IBM Plex Mono", monospace; font-size: 9px;1379    letter-spacing: 0.06em; cursor: pointer;1380    transition: all 130ms ease;1381  }1382  .pwgen-pill.is-on {1383    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1384    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1385    color: var(--peach-accent);1386  }1387  .pwgen-pill:not(.is-on):hover {1388    color: var(--peach-text-dim);1389    border-color: var(--peach-text-muted);1390  }1391  .pwgen-policy-hint {1392    font-size: 10px; color: var(--peach-text-muted);1393    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1394    line-height: 1.3;1395  }1396  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }13971398  /* ── Save offer (after password filled) ───────────────────── */1399  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1400  .save-offer-title {1401    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1402  }1403  .save-offer-row {1404    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1405    border-radius: 7px; background: var(--peach-input-bg);1406    border: 1px solid var(--peach-input-border);1407  }1408  .save-offer-lbl {1409    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1410    font-family: "IBM Plex Mono", monospace;1411  }1412  .save-offer-val {1413    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1414    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1415  }1416  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1417  .save-offer-save {1418    flex: 1; padding: 9px; border-radius: 8px; border: none;1419    background: var(--peach-accent); color: #fff; font-size: 13px;1420    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1421  }1422  .save-offer-save:hover { filter: brightness(1.08); }1423  .save-offer-skip {1424    flex: 1; padding: 9px; border-radius: 8px; border: none;1425    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1426    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1427    font-family: Inter, sans-serif; transition: background 100ms ease;1428  }1429  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1430`;14311432export function showAutofillSelector(1433  anchorEl: HTMLInputElement,1434  entries: SelectorEntry[],1435  onSelect: (id: string) => void,1436  options: SelectorOptions = {}1437): () => void {1438  const host = document.createElement("div");1439  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1440  // when Peach's internal inputs gain focus, immediately blurring them and closing1441  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1442  // as in-bounds (v3.6.131).1443  //1444  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1445  // A plain login page whose card uses transform/filter/backdrop-filter establishes1446  // a containing block for position:fixed, so a host mounted inside it lands offset1447  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1448  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1449  // the popup ~400px off the field and clipped it behind overflow:clip — the user1450  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1451  // everything else mounts at the document root, where fixed == viewport.1452  const modalAncestor = (1453    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1454    (() => {1455      let cur: HTMLElement | null = anchorEl.parentElement;1456      while (cur && cur !== document.body) {1457        if (window.getComputedStyle(cur).position === 'fixed') return cur;1458        cur = cur.parentElement;1459      }1460      return null;1461    })()1462  );1463  host.style.cssText = `position: fixed; z-index: 2147483647;`;1464  host.style.setProperty("--peach-accent", accentHex);1465  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1466  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1467  // Hint the compositor that top/left animate during scroll repositioning so the1468  // popup stays on the GPU layer and doesn't flicker as observeAnchorPosition1469  // re-asserts its coordinates.1470  host.style.willChange = "top, left";1471  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1472  // HOST appear focused to the outside DOM. Modal focus traps that monitor1473  // focusin then see the host (mounted inside the modal) as the focused element1474  // rather than an opaque closed-shadow node, so they don't fire their1475  // "focus escaped" handler and yank focus back. Harmless outside modals.1476  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });14771478  const style = shadow.appendChild(document.createElement("style"));1479  style.textContent = SELECTOR_STYLES;14801481  const rect = anchorEl.getBoundingClientRect();1482  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1483  // applying containing-block compensation once host.parentElement is known.1484  host.style.top = `${rect.bottom + 5}px`;1485  host.style.left = `${rect.left}px`;1486  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1487  // wide single-input fields (e.g. centered email input on signup pages).1488  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1489  // expand the host after the initial measurement.1490  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1491  host.style.width = `${popupWidth}px`;14921493  const container = shadow.appendChild(document.createElement("div"));1494  container.className = "peach-inline-popup";1495  container.setAttribute("data-theme", popupTheme);14961497  // MV-2: the vault-wide list is loaded lazily on the first search gesture,1498  // never eagerly on passive popup open. Cached for the popup's lifetime.1499  let searchableEntries: SelectorEntry[] = options.searchableEntries ?? [];1500  let searchableLoading = false;1501  let searchableLoaded = !options.loadSearchableEntries;15021503  async function ensureSearchableLoaded(rerender: () => void): Promise<void> {1504    if (searchableLoaded || searchableLoading || !options.loadSearchableEntries) {1505      return;1506    }1507    searchableLoading = true;1508    try {1509      searchableEntries = await options.loadSearchableEntries();1510    } catch {1511      searchableEntries = [];1512    } finally {1513      searchableLoaded = true;1514      searchableLoading = false;1515      rerender();1516    }1517  }1518  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();15191520  let query = "";1521  let focusedIndex = -1;1522  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" | "edit" = "list";1523  let searchInput: HTMLInputElement | null = null;1524  let identityMode: IdentityFilterMode = "both";1525  // Tracks the silver-platter entry the user pivoted away from, so the1526  // search/list header can offer a one-click way back to it. null when the1527  // popup never showed a single-match platter (e.g. multi-match list view).1528  let silverPlatterOrigin: SelectorEntry | null = null;1529  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1530  // setInterval. Add to this list — don't fan out the dismiss function.1531  const cleanupHooks: Array<() => void> = [];15321533  // Smooth height transitions whenever content changes height.1534  // ResizeObserver fires on natural height changes; we freeze the old height,1535  // then animate to the new one so the surface never jumps.1536  {1537    let prevH = 0;1538    let blocked = false;1539    const heightRo = new ResizeObserver(([entry]) => {1540      if (blocked) return;1541      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1542      if (prevH > 0 && Math.abs(h - prevH) > 1) {1543        blocked = true;1544        container.style.height = `${prevH}px`;1545        requestAnimationFrame(() => requestAnimationFrame(() => {1546          container.style.height = `${h}px`;1547          prevH = h;1548          const onEnd = (e: TransitionEvent) => {1549            if (e.propertyName !== "height") return;1550            container.style.height = "";1551            blocked = false;1552            container.removeEventListener("transitionend", onEnd);1553          };1554          container.addEventListener("transitionend", onEnd);1555        }));1556      } else {1557        prevH = h;1558      }1559    });1560    heightRo.observe(container);1561    cleanupHooks.push(() => heightRo.disconnect());1562  }15631564  // Pre-capture the anchor field value for username prefill1565  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1566  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1567  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";15681569  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1570    const seen = new Set<string>();1571    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1572  }15731574  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1575    const q = value.trim().toLowerCase();1576    const deduped = uniqueEntries(source);1577    if (!q) return deduped.slice(0, 8);1578    return deduped.filter(e =>1579      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1580    ).slice(0, 12);1581  }15821583  function activeEntries(): SelectorEntry[] {1584    // When user is typing a search, filter across all known entries (domain matches + vault)1585    if (query.trim()) {1586      const merged = uniqueEntries([...entries, ...searchableEntries]);1587      return filterEntries(merged, query);1588    }1589    // Default: show domain matches; fall back to vault search when no matches1590    if (entries.length > 0) return entries;1591    return filterEntries(searchableEntries, "").slice(0, 8);1592  }15931594  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1595    const icon = document.createElement("div");1596    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1597    if (isNew) {1598      icon.innerHTML = plusSvgStr();1599    } else {1600      // Use the generic key glyph for all entries in the page-injected selector.1601      // Avoids disclosing vault domains to any third party and avoids needing1602      // to expose the browser favicon API to page context via web_accessible_resources.1603      void url;1604      icon.innerHTML = keySvgStr();1605    }1606    return icon;1607  }16081609  function renderIdentityHelper() {1610    currentMode = "identity-helper";1611    container.innerHTML = "";1612    focusedIndex = -1;1613    searchInput = null;16141615    const fallbackKind: IdentityKind = options.identityKind ?? "username";1616    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1617    const typedQuery = query.trim();1618    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);16191620    function applyIdentity(identity: string) {1621      if (options.hasEmailField) {1622        if (options.identityKind === "email") {1623          options.onFillFields?.("", "", identity);       // fill email field now1624          renderSecondaryIdentityStep("username", identity);1625        } else {1626          options.onFillFields?.(identity, "", "");       // fill username field now1627          renderSecondaryIdentityStep("email", identity);1628        }1629      } else {1630        options.onFillFields?.(identity, "");1631        renderGenerator(identity);1632      }1633    }16341635    function applyCustomIdentity(identity: string) {1636      const trimmed = identity.trim();1637      if (!trimmed) return;1638      applyIdentity(trimmed);1639    }16401641    // Header: "NEW ACCOUNT" + domain name1642    const hdr = container.appendChild(document.createElement("div"));1643    hdr.className = "domain-header";1644    const headText = hdr.appendChild(document.createElement("div"));1645    headText.className = "domain-header-text";1646    const eyebrow = headText.appendChild(document.createElement("div"));1647    eyebrow.className = "domain-eyebrow";1648    eyebrow.textContent = "NEW ACCOUNT";1649    const domName = headText.appendChild(document.createElement("div"));1650    domName.className = "domain-name";1651    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");16521653    const actions = hdr.appendChild(document.createElement("div"));1654    actions.className = "identity-mode-toggle";1655    for (const mode of ["both", "email", "username"] as const) {1656      const btn = actions.appendChild(document.createElement("button"));1657      btn.type = "button";1658      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1659      btn.textContent = identityFilterLabel(mode);1660      btn.setAttribute("aria-pressed", String(identityMode === mode));1661      btn.addEventListener("click", () => {1662        identityMode = mode;1663        renderIdentityHelper();1664      });1665    }16661667    const searchWrap = container.appendChild(document.createElement("div"));1668    searchWrap.className = "search-wrap identity-search-wrap";1669    const search = searchWrap.appendChild(document.createElement("input"));1670    search.className = "search";1671    search.placeholder = "search identities…";1672    search.value = query;1673    search.addEventListener("input", () => {1674      query = search.value;1675      renderIdentityHelper();1676      searchInput?.focus();1677      searchInput?.setSelectionRange(query.length, query.length);1678    });1679    search.addEventListener("keydown", (e) => {1680      if (e.key === "Escape") {1681        e.preventDefault();1682        dismiss(true);1683        return;1684      }1685      if (e.key !== "Enter") return;1686      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1687      if (exact) {1688        e.preventDefault();1689        applyIdentity(exact.value);1690        return;1691      }1692      if (!typedQuery || identities.length > 0) return;1693      e.preventDefault();1694      applyCustomIdentity(typedQuery);1695    });1696    const searchTools = searchWrap.appendChild(document.createElement("div"));1697    searchTools.className = "identity-mode-toggle";1698    const sortHint = searchTools.appendChild(document.createElement("div"));1699    sortHint.className = "identity-empty";1700    sortHint.style.padding = "0";1701    sortHint.textContent = "sorted by recent use";1702    searchInput = search;1703    const customLabel = identityMode === "both"1704      ? customKind1705      : identityMode;17061707    // Identity rows1708    const list = container.appendChild(document.createElement("div"));1709    list.className = "identity-list";1710    // Bottom fade only when the list overflows its max-height and isn't scrolled1711    // to the end. A short list (1-2 identities) shows no fade, so it never looks1712    // prematurely cut off; a long list gets the affordance, which clears on1713    // reaching the bottom.1714    const updateListFade = () => {1715      const overflowing = list.scrollHeight > list.clientHeight + 1;1716      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1717      const mask = overflowing && !atBottom1718        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1719        : "none";1720      list.style.setProperty("mask-image", mask);1721      list.style.setProperty("-webkit-mask-image", mask);1722    };1723    list.addEventListener("scroll", updateListFade);1724    if (typedQuery && identities.length === 0) {1725      const empty = list.appendChild(document.createElement("div"));1726      empty.className = "identity-empty";1727      empty.textContent = identityMode === "both"1728        ? `No match for “${typedQuery}”.`1729        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1730      const custom = list.appendChild(document.createElement("div"));1731      custom.className = "identity-custom-row";1732      const customTitle = custom.appendChild(document.createElement("div"));1733      customTitle.className = "identity-custom-row-title";1734      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1735      const customSub = custom.appendChild(document.createElement("div"));1736      customSub.className = "identity-custom-row-sub";1737      customSub.textContent = "Press Enter or click to continue.";1738      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1739    }1740    for (const id of identities) {1741      const row = list.appendChild(document.createElement("div"));1742      row.className = "peach-identity-row";1743      row.setAttribute("tabindex", "-1");1744      const val = row.appendChild(document.createElement("div"));1745      val.className = "peach-identity-value";1746      val.textContent = id.value;1747      const meta = row.appendChild(document.createElement("div"));1748      meta.className = "peach-identity-meta";1749      meta.textContent = `used ${id.useCount}×`;1750      row.addEventListener("click", () => {1751        applyIdentity(id.value);1752      });1753    }17541755    updateListFade();17561757    // Divider before "Use a different email…"1758    if (identities.length > 0) {1759      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1760    }17611762    // "Use a different email/username…" expandable row1763    const altRow = container.appendChild(document.createElement("div"));1764    altRow.className = "identity-alt-row";1765    altRow.textContent = `+ Use a different ${customLabel}…`;17661767    const altInputWrap = container.appendChild(document.createElement("div"));1768    altInputWrap.className = "identity-alt-input-wrap";1769    const altInput = altInputWrap.appendChild(document.createElement("input"));1770    altInput.className = "identity-alt-input";1771    altInput.type = "text";1772    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1773    altInput.setAttribute("autocomplete", "off");1774    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1775    altConfirm.className = "identity-alt-confirm";1776    altConfirm.type = "button";1777    altConfirm.textContent = "✓";17781779    function fillCustomIdentity() {1780      const v = altInput.value.trim();1781      if (!v) return;1782      applyCustomIdentity(v);1783    }17841785    altRow.addEventListener("click", () => {1786      altRow.style.display = "none";1787      altInputWrap.classList.add("open");1788      altInput.value = typedQuery || altInput.value;1789      altInput.focus();1790      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1791    });1792    altConfirm.addEventListener("click", fillCustomIdentity);1793    altInput.addEventListener("keydown", (e) => {1794      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1795    });17961797    // Escape hatch: user already has a vault entry for this site but it1798    // wasn't detected (different domain, old entry, etc.). Tapping this1799    // switches to the full searchable list so they can find and fill it;1800    // selecting an entry there will trigger the remember-site toast if1801    // the domain isn't already associated.1802    // MV-2: with lazy loading we no longer know the vault-wide count up front,1803    // so offer the escape hatch whenever a loader (or an eager array) exists.1804    if (options.loadSearchableEntries || (options.searchableEntries?.length ?? 0) > 0) {1805      const escapeRow = container.appendChild(document.createElement("div"));1806      escapeRow.className = "identity-escape-row";1807      escapeRow.textContent = "I already have an account →";1808      escapeRow.setAttribute("tabindex", "0");1809      const toSearch = () => { void ensureSearchableLoaded(renderList); renderList(); };1810      escapeRow.addEventListener("click", toSearch);1811      escapeRow.addEventListener("keydown", (e) => {1812        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toSearch(); }1813      });1814    }18151816    requestAnimationFrame(() => {1817      search.focus();1818      search.setSelectionRange(query.length, query.length);1819    });1820  }18211822  /**1823   * Step 2 of the contextual signup wizard.1824   * `stepKind` is the identity type to collect in this step ("email" or "username").1825   * `firstValue` is what was picked in step 1 (the other type).1826   */1827  function renderSecondaryIdentityStep(stepKind: "email" | "username", firstValue: string) {1828    currentMode = "identity-helper";1829    container.innerHTML = "";18301831    const wrap = container.appendChild(document.createElement("div"));1832    wrap.className = "gen-view";18331834    // Header1835    const hdrRow = wrap.appendChild(document.createElement("div"));1836    hdrRow.className = "domain-header";1837    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1838    eyebrow2.className = "domain-eyebrow";1839    eyebrow2.textContent = "NEW ACCOUNT";1840    const domName2 = hdrRow.appendChild(document.createElement("div"));1841    domName2.className = "domain-name";1842    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");18431844    // Confirmed first step1845    const conf = wrap.appendChild(document.createElement("div"));1846    conf.className = "gen-confirmed";1847    const confCheck = conf.appendChild(document.createElement("span"));1848    confCheck.className = "gen-confirmed-check";1849    confCheck.textContent = "✓";1850    const confVal = conf.appendChild(document.createElement("div"));1851    confVal.className = "gen-confirmed-val";1852    confVal.textContent = firstValue;18531854    const stepLbl = wrap.appendChild(document.createElement("div"));1855    stepLbl.className = "gen-label";1856    stepLbl.textContent = stepKind === "email" ? "Now choose your email" : "Now choose your username";18571858    // Filter saved identities to the correct type for this step1859    const identities = (options.savedIdentities ?? [])1860      .filter(s => s.type === stepKind)1861      .sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0))1862      .slice(0, 6);18631864    const list = wrap.appendChild(document.createElement("div"));1865    list.className = "identity-list";1866    for (const id of identities) {1867      const row = list.appendChild(document.createElement("div"));1868      row.className = "peach-identity-row";1869      row.setAttribute("tabindex", "-1");1870      const val = row.appendChild(document.createElement("div"));1871      val.className = "peach-identity-value";1872      val.textContent = id.value;1873      const meta = row.appendChild(document.createElement("div"));1874      meta.className = "peach-identity-meta";1875      meta.textContent = `used ${id.useCount}×`;1876      row.addEventListener("click", () => applySecondIdentity(id.value));1877    }18781879    // Text input for a value not in the list1880    const altInputWrap = wrap.appendChild(document.createElement("div"));1881    altInputWrap.className = "identity-alt-input-wrap open";1882    const altInput = altInputWrap.appendChild(document.createElement("input"));1883    altInput.className = "identity-alt-input";1884    altInput.type = stepKind === "email" ? "email" : "text";1885    altInput.placeholder = stepKind === "email" ? "[email protected]" : "your username";1886    altInput.setAttribute("autocomplete", "off");1887    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1888    altConfirm.className = "identity-alt-confirm";1889    altConfirm.type = "button";1890    altConfirm.textContent = "→";18911892    function applySecondIdentity(value: string) {1893      const trimmed = value.trim();1894      if (!trimmed) return;1895      // Determine final email + username order before passing to the generator1896      const [email, username] = stepKind === "email"1897        ? [trimmed, firstValue]1898        : [firstValue, trimmed];1899      if (stepKind === "email") {1900        options.onFillFields?.("", "", trimmed); // fill email field1901      } else {1902        options.onFillFields?.(trimmed, "", ""); // fill username field1903      }1904      renderGenerator(email, username);1905    }19061907    altConfirm.addEventListener("click", () => applySecondIdentity(altInput.value));1908    altInput.addEventListener("keydown", (e) => {1909      if (e.key === "Enter") { e.preventDefault(); applySecondIdentity(altInput.value); }1910    });19111912    // Skip: proceed without this field1913    const skipRow = wrap.appendChild(document.createElement("div"));1914    skipRow.className = "identity-escape-row";1915    skipRow.textContent = `Skip ${stepKind} →`;1916    skipRow.setAttribute("tabindex", "0");1917    skipRow.addEventListener("click", () => {1918      const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1919      renderGenerator(email, username);1920    });1921    skipRow.addEventListener("keydown", (e) => {1922      if (e.key === "Enter" || e.key === " ") {1923        e.preventDefault();1924        const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1925        renderGenerator(email, username);1926      }1927    });19281929    requestAnimationFrame(() => { altInput.focus(); });1930  }19311932  function renderGenerator(filledEmail: string, filledUsername?: string) {1933    container.innerHTML = "";1934    const sitePolicy = detectPasswordPolicy();19351936    const wrap = container.appendChild(document.createElement("div"));1937    wrap.className = "gen-view";19381939    // Header: domain + NEW ACCOUNT1940    const hdrRow = wrap.appendChild(document.createElement("div"));1941    hdrRow.className = "domain-header";1942    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1943    eyebrow2.className = "domain-eyebrow";1944    eyebrow2.textContent = "NEW ACCOUNT";1945    const domName2 = hdrRow.appendChild(document.createElement("div"));1946    domName2.className = "domain-name";1947    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");19481949    // Confirmed identity rows — show both username and email when both were collected1950    function confirmedRow(value: string) {1951      const conf = wrap.appendChild(document.createElement("div"));1952      conf.className = "gen-confirmed";1953      const confCheck = conf.appendChild(document.createElement("span"));1954      confCheck.className = "gen-confirmed-check";1955      confCheck.textContent = "✓";1956      const confVal = conf.appendChild(document.createElement("div"));1957      confVal.className = "gen-confirmed-val";1958      confVal.textContent = value;1959    }1960    if (filledEmail) confirmedRow(filledEmail);1961    if (filledUsername && filledUsername !== filledEmail) confirmedRow(filledUsername);19621963    const lbl = wrap.appendChild(document.createElement("div"));1964    lbl.className = "gen-label";1965    lbl.textContent = "Generate a password";19661967    let currentPw = "";1968    const smartGen = createSmartGenerator({1969      policy: sitePolicy,1970      onChange: (pw) => { currentPw = pw; },1971    });1972    wrap.appendChild(smartGen.root);19731974    const fillBtn = wrap.appendChild(document.createElement("button"));1975    fillBtn.className = "gen-fill-btn";1976    fillBtn.type = "button";1977    fillBtn.textContent = "Copy & fill";1978    fillBtn.addEventListener("click", async () => {1979      if (!currentPw) return;1980      fillBtn.disabled = true;1981      fillBtn.textContent = "Saving…";1982      // Fill the page fields first — password lands immediately.1983      options.onFillFields?.("", currentPw, "");1984      // Auto-save to vault. Fall back to the save-offer form only if the save fails1985      // (vault locked, quota exceeded, etc.) so the user sees the error and can retry.1986      const saveUsername = filledUsername || filledEmail;1987      const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;1988      try {1989        const res = await chrome.runtime.sendMessage({1990          type: "ADD_ENTRY",1991          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: currentPw, type: "login" },1992        });1993        if ((res as { ok?: boolean }).ok) {1994          showSuccess(sTitle);1995        } else {1996          renderSaveOffer(filledEmail, currentPw, filledUsername);1997        }1998      } catch {1999        renderSaveOffer(filledEmail, currentPw, filledUsername);2000      }2001    });2002  }20032004  function renderSaveOffer(filledEmail: string, filledPassword: string, filledUsername?: string) {2005    container.innerHTML = "";2006    const domain = options.domain ?? location.hostname.replace(/^www\./, "");20072008    const wrap = container.appendChild(document.createElement("div"));2009    wrap.className = "save-offer";20102011    const title = wrap.appendChild(document.createElement("div"));2012    title.className = "save-offer-title";2013    title.textContent = "Save this login to Peach?";20142015    function detailRow(label: string, value: string) {2016      const row = wrap.appendChild(document.createElement("div"));2017      row.className = "save-offer-row";2018      const lbl = row.appendChild(document.createElement("div"));2019      lbl.className = "save-offer-lbl";2020      lbl.textContent = label;2021      const val = row.appendChild(document.createElement("div"));2022      val.className = "save-offer-val";2023      val.textContent = value;2024    }20252026    detailRow("site", domain);2027    // When both username and email were collected, show both; otherwise show the identity as "email"2028    if (filledUsername) {2029      detailRow("username", filledUsername);2030      if (filledEmail) detailRow("email", filledEmail);2031    } else {2032      if (filledEmail) detailRow("email", filledEmail);2033    }2034    detailRow("password", "••••••••••••••••");20352036    const btns = wrap.appendChild(document.createElement("div"));2037    btns.className = "save-offer-btns";20382039    const saveBtn = btns.appendChild(document.createElement("button"));2040    saveBtn.className = "save-offer-save";2041    saveBtn.type = "button";2042    saveBtn.textContent = "Save";2043    saveBtn.addEventListener("click", async () => {2044      saveBtn.disabled = true;2045      saveBtn.textContent = "Saving…";2046      try {2047        // When both username and email were set, save them in the correct fields.2048        // Otherwise fall back to storing the identity as the username (current behaviour).2049        const saveUsername = filledUsername || filledEmail;2050        const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;2051        const res = await chrome.runtime.sendMessage({2052          type: "ADD_ENTRY",2053          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: filledPassword, type: "login" },2054        });2055        if ((res as { ok?: boolean }).ok) {2056          showSuccess(sTitle);2057        } else {2058          saveBtn.disabled = false;2059          saveBtn.textContent = "Save";2060        }2061      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }2062    });20632064    const skipBtn = btns.appendChild(document.createElement("button"));2065    skipBtn.className = "save-offer-skip";2066    skipBtn.type = "button";2067    skipBtn.textContent = "Not now";2068    skipBtn.addEventListener("click", () => { dismiss(true); });2069  }20702071  function renderList() {2072    container.innerHTML = "";2073    focusedIndex = -1;2074    searchInput = null;2075    currentMode = "list";20762077    const current = activeEntries();20782079    // Domain header (always show) — eyebrow + domain on the left,2080    // a "+" shortcut to the create form on the right so the user is never2081    // trapped in the search list when they want to make a new entry.2082    const domHdr = document.createElement("div");2083    domHdr.className = "domain-header";2084    const headText = document.createElement("div");2085    headText.className = "domain-header-text";2086    const eyebrow = document.createElement("div");2087    eyebrow.className = "domain-eyebrow";2088    eyebrow.textContent = options.isSignup2089      ? "Sign up as"2090      : entries.length > 0 ? "Saved for this site" : "No saved login";2091    const domName = document.createElement("div");2092    domName.className = "domain-name";2093    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2094    headText.append(eyebrow, domName);2095    domHdr.appendChild(headText);20962097    if (!options.isSignup) {2098      const actions = document.createElement("div");2099      actions.className = "domain-header-actions";21002101      // Back arrow takes the place of the silver-platter's search icon when2102      // the user has pivoted away from a single-match platter — gives them2103      // a one-click way back to the original recommendation.2104      if (silverPlatterOrigin) {2105        const backBtn = document.createElement("button");2106        backBtn.className = "domain-search-btn";2107        backBtn.type = "button";2108        backBtn.setAttribute("aria-label", "Back to suggested entry");2109        backBtn.title = "Back to suggested entry";2110        backBtn.innerHTML = backSvgStr();2111        backBtn.addEventListener("click", (e) => {2112          e.stopPropagation();2113          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);2114        });2115        actions.appendChild(backBtn);2116      }21172118      const addBtn = document.createElement("button");2119      addBtn.className = "domain-add-btn";2120      addBtn.type = "button";2121      addBtn.setAttribute("aria-label", "Create new entry");2122      addBtn.title = "Create new entry";2123      addBtn.textContent = "+";2124      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2125      actions.appendChild(addBtn);21262127      domHdr.appendChild(actions);2128    }21292130    container.appendChild(domHdr);21312132    // Search — always show so user can find entries beyond the domain matches2133    const sw = document.createElement("div"); sw.className = "search-wrap";2134    searchInput = document.createElement("input");2135    searchInput.className = "search";2136    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";2137    searchInput.value = query;2138    searchInput.addEventListener("input", () => {2139      query = searchInput?.value ?? "";2140      // MV-2: typing in the search box is the explicit gesture that loads the2141      // vault-wide list (once, cached); it re-renders when it resolves.2142      void ensureSearchableLoaded(renderList);2143      renderList();2144      searchInput?.focus();2145      searchInput?.setSelectionRange(query.length, query.length);2146    });2147    sw.appendChild(searchInput);2148    // UI-2 / MV-2: show a brief loading hint while the vault-wide list loads2149    // on the first search gesture (cached afterwards, so only the first time).2150    if (searchableLoading) {2151      const loadingHint = document.createElement("span");2152      loadingHint.className = "search-loading";2153      loadingHint.textContent = "searching…";2154      sw.appendChild(loadingHint);2155    }2156    container.appendChild(sw);21572158    // Results2159    const results = document.createElement("div");2160    results.className = "results";2161    container.appendChild(results);21622163    if (current.length === 0 && entries.length > 0) {2164      // Show a hint but don't render empty entries2165    }21662167    for (let i = 0; i < current.length; i++) {2168      const e = current[i]!;2169      const entryEl = document.createElement("div");2170      entryEl.className = "entry";2171      entryEl.dataset.id = e.id;2172      entryEl.dataset.index = String(i);2173      entryEl.setAttribute("tabindex", "-1");21742175      entryEl.appendChild(makeEntryIcon(e.url));21762177      const info = document.createElement("div"); info.className = "entry-info";2178      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;2179      const subEl = document.createElement("div"); subEl.className = "entry-sub";2180      const domain = e.url ? getDomainFromUrl(e.url) : "";2181      subEl.textContent = domain || e.username || "";2182      info.append(titleEl, subEl);2183      entryEl.appendChild(info);21842185      if (e.hasTotp) {2186        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";2187        entryEl.appendChild(badge);2188      }2189      if (e.hasPasskey) {2190        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";2191        entryEl.appendChild(badge);2192      }21932194      entryEl.addEventListener("click", () => {2195        if (options.isSignup && options.onFillFields) {2196          // Fill username, email, and leave password for the user to confirm2197          options.onFillFields(e.username ?? "", "", e.email);2198          dismiss();2199        } else {2200          onSelect(e.id);2201          dismiss();2202        }2203      });2204      results.appendChild(entryEl);2205    }22062207    // Divider before "New entry"2208    if (current.length > 0) {2209      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));2210    }22112212    // "New entry" row — always present2213    const newEl = document.createElement("div");2214    newEl.className = "entry";2215    newEl.setAttribute("tabindex", "-1");2216    newEl.appendChild(makeEntryIcon(undefined, true));22172218    const newInfo = document.createElement("div"); newInfo.className = "entry-info";2219    const newTitle = document.createElement("div");2220    newTitle.className = "entry-title is-new";2221    newTitle.textContent = `New entry for ${sTitle}`;2222    const newSub = document.createElement("div");2223    newSub.className = "entry-sub";2224    newSub.textContent = sOrigin;2225    newInfo.append(newTitle, newSub);2226    newEl.appendChild(newInfo);2227    newEl.addEventListener("click", showCreateForm);2228    results.appendChild(newEl);22292230    // Focus search if present2231    if (searchInput) {2232      requestAnimationFrame(() => {2233        searchInput?.focus();2234        // Seed query (from type-to-search or domain-search-btn) lands at the2235        // end so the next keystroke extends it, not overwrites.2236        searchInput?.setSelectionRange(query.length, query.length);2237      });2238    }2239  }22402241  function setFocused(idx: number) {2242    const all = container.querySelectorAll<HTMLElement>(".entry");2243    all.forEach((el, i) => el.classList.toggle("focused", i === idx));2244    focusedIndex = idx;2245    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });2246  }22472248  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {2249    const typed = identities.filter(s => s.type === fieldType);2250    if (!typed.length) return;2251    let collapsed = false;2252    let suppressNextFocus = false;22532254    const list = g.appendChild(document.createElement("div"));2255    list.className = "identity-suggest-list";2256    list.style.display = "none";22572258    // Collapse toggle — sits alone now that filter pills are gone2259    const collapseRow = list.appendChild(document.createElement("div"));2260    collapseRow.className = "identity-filter-row";2261    collapseRow.style.justifyContent = "flex-end";2262    const collapseBtn = collapseRow.appendChild(document.createElement("button"));2263    collapseBtn.type = "button";2264    collapseBtn.className = "identity-collapse-btn";2265    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>`;2266    collapseBtn.addEventListener("mousedown", (e) => {2267      e.preventDefault();2268      collapsed = !collapsed;2269      collapseBtn.classList.toggle("is-collapsed", collapsed);2270      rowsWrapper.classList.toggle("is-collapsed", collapsed);2271    });22722273    const rowsWrapper = list.appendChild(document.createElement("div"));2274    rowsWrapper.className = "identity-rows";2275    const rows = rowsWrapper.appendChild(document.createElement("div"));2276    rows.className = "identity-rows-inner";22772278    // Bottom fade only when the list actually overflows and isn't scrolled to2279    // the end — a static mask-image fades the last row even on a 1-2 item list2280    // that fits entirely, making it look cut off. Driven off live scroll state.2281    const updateRowsFade = () => {2282      const overflowing = rows.scrollHeight > rows.clientHeight + 1;2283      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;2284      const mask = overflowing && !atBottom2285        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"2286        : "none";2287      rows.style.setProperty("mask-image", mask);2288      rows.style.setProperty("-webkit-mask-image", mask);2289    };2290    rows.addEventListener("scroll", updateRowsFade);22912292    // Hides the list and removes the document-level click watcher.2293    function hideList() {2294      list.style.display = "none";2295      document.removeEventListener("mousedown", onDocMousedown, { capture: true });2296    }22972298    // Dismiss list on any mousedown that originates outside the popup's shadow2299    // DOM. This is the ONLY close trigger for the list — blur is intentionally2300    // NOT used, because modal focus traps fire blur without a mousedown (they2301    // call element.focus() programmatically in response to focusin/focusout),2302    // which caused the list to vanish before the user could pick from it.2303    function onDocMousedown(e: MouseEvent) {2304      if (e.composedPath().includes(host)) return;2305      hideList();2306    }23072308    function pick(value: string) {2309      inp.value = value;2310      hideList();2311      suppressNextFocus = true;2312      inp.focus();2313      // If a focus trap intercepts inp.focus() and redirects to anchorEl before2314      // inp ever fires its focus event, suppressNextFocus would strand the user.2315      // Clear after a short window so subsequent clicks still work.2316      setTimeout(() => { suppressNextFocus = false; }, 120);2317    }23182319    function render() {2320      const q = inp.value.toLowerCase();2321      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2322      rows.innerHTML = "";2323      if (!filtered.length) { hideList(); return; }2324      for (const s of filtered) {2325        const row = rows.appendChild(document.createElement("button"));2326        row.type = "button"; row.className = "identity-suggest-row";2327        const val = row.appendChild(document.createElement("span"));2328        val.className = "identity-suggest-val"; val.textContent = s.value;2329        const meta = row.appendChild(document.createElement("span"));2330        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2331        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2332        row.addEventListener("keydown", (e) => {2333          if (e.key === "ArrowDown") {2334            e.preventDefault();2335            (row.nextElementSibling as HTMLElement | null)?.focus();2336          } else if (e.key === "ArrowUp") {2337            e.preventDefault();2338            const prev = row.previousElementSibling as HTMLElement | null;2339            if (prev) prev.focus();2340            else inp.focus();2341          } else if (e.key === "Enter" || e.key === " ") {2342            e.preventDefault();2343            pick(s.value);2344          } else if (e.key === "Escape") {2345            e.preventDefault();2346            hideList();2347            suppressNextFocus = true;2348            inp.focus();2349          }2350        });2351        // Row blur only fires during keyboard navigation (arrow keys / Tab).2352        // Focus traps don't produce row blur events since rows aren't focused2353        // when the trap fires; this handler is therefore trap-safe.2354        row.addEventListener("blur", (e) => {2355          const rt = (e as FocusEvent).relatedTarget as Node | null;2356          if (rt && (rt === inp || list.contains(rt))) return;2357          setTimeout(() => { hideList(); }, 150);2358        });2359      }2360      list.style.display = "";2361      updateRowsFade();2362      // Register the close-on-outside-click watcher each time the list shows.2363      // addEventListener deduplicates identical (fn, options) pairs, so2364      // re-rendering on input events does not stack up listeners.2365      document.addEventListener("mousedown", onDocMousedown, { capture: true });2366    }23672368    inp.addEventListener("focus", () => {2369      if (suppressNextFocus) { suppressNextFocus = false; return; }2370      render();2371    });2372    inp.addEventListener("input", render);2373    inp.addEventListener("keydown", (e) => {2374      if (list.style.display === "none") return;2375      if (e.key === "ArrowDown" && !collapsed) {2376        e.preventDefault();2377        (rows.firstElementChild as HTMLElement | null)?.focus();2378      } else if (e.key === "Escape") {2379        e.preventDefault();2380        hideList();2381      } else if (e.key === "Tab") {2382        // Tab moves focus away intentionally — close the list.2383        hideList();2384      }2385    });2386    // No blur handler on inp. Blur fires for ANY focus movement including2387    // programmatic focus() calls from modal focus traps, which caused the list2388    // to close before the user could interact. The document mousedown listener2389    // (registered in render()) handles intentional click-outside dismissal,2390    // and the keydown handler above covers keyboard Tab/Escape.23912392    // Ensure the watcher is removed if the main popup is dismissed while the2393    // list is visible.2394    cleanupHooks.push(hideList);2395  }23962397  async function showCreateForm() {2398    currentMode = "create";2399    container.innerHTML = "";24002401    // Guard: the service worker may lock the vault between when the selector2402    // opens and when the user clicks "New entry". Show the inline unlock form2403    // instead of silently failing on save.2404    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2405    if (!statusRes?.unlocked) {2406      renderLocked();2407      return;2408    }24092410    // Detect page password policy once for this form — reused on every2411    // regenerate click so the user always gets a compliant password.2412    const sitePolicy = detectPasswordPolicy();24132414    const formIdentities = options.savedIdentities ?? [];24152416    const wrap = document.createElement("div");2417    wrap.className = "create-form-wrap";24182419    // Header2420    const head = document.createElement("div"); head.className = "create-head";2421    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2422    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>`;2423    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2424    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2425    head.append(backBtn, lbl);24262427    // Body2428    const body = document.createElement("div"); body.className = "create-body";24292430    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2431      const g = document.createElement("div"); g.className = "f-group";2432      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2433      const inp = document.createElement("input"); inp.className = "f-input";2434      g.append(l, inp); return { g, inp };2435    }24362437    // Title2438    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2439    body.appendChild(tg.g);24402441    // URL2442    const ug = fGroup("website");2443    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2444    if (loginSubdomain) {2445      const h = document.createElement("div"); h.className = "url-hint";2446      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2447    }2448    body.appendChild(ug.g);24492450    // Username — pre-fill from anchor if it doesn't look like an email2451    const xg = fGroup("username");2452    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2453    xg.inp.placeholder = "johndoe";2454    xg.inp.setAttribute("autocomplete", "off");2455    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2456    body.appendChild(xg.g);24572458    // Email — pre-fill from anchor if it looks like an email2459    const eg = fGroup("email");2460    (eg.inp as HTMLInputElement).type = "email";2461    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2462    eg.inp.placeholder = "[email protected]";2463    eg.inp.setAttribute("autocomplete", "off");2464    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2465    body.appendChild(eg.g);24662467    // Password — full smart generator with charset pills + length slider +2468    // policy hint. Mirrors the main UI's compact generator so users get the2469    // same controls inline as in the popup.2470    const pg = fGroup("password");2471    pg.inp.remove(); // smartGen provides its own display — no separate input needed2472    let currentPassword = prePassword || "";2473    const smartGen = createSmartGenerator({2474      policy: sitePolicy,2475      initialPassword: prePassword || undefined,2476      onChange: (pw) => { currentPassword = pw; },2477    });2478    pg.g.appendChild(smartGen.root);2479    body.appendChild(pg.g);24802481    // Save2482    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2483    saveBtn.textContent = "Save entry";2484    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2485    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2486    saveBtn.addEventListener("click", async () => {2487      const title = tg.inp.value.trim();2488      const pw = currentPassword.trim();2489      const username = xg.inp.value.trim();2490      const email = eg.inp.value.trim();2491      if (!title) {2492        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2493        showFormError("Entry needs a title");2494        return;2495      }2496      if (!pw) {2497        showFormError("Entry needs a password — tap regen to make one");2498        return;2499      }2500      errEl.style.display = "none";2501      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2502      try {2503        const res = await chrome.runtime.sendMessage({2504          type: "ADD_ENTRY",2505          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2506        });2507        if ((res as { ok?: boolean }).ok) {2508          // Fill the detected form. onFillFields uses whichever identity the2509          // page anchored on — the vault captures both username and email.2510          options.onFillFields?.(username || email, pw);2511          showSuccess(title);2512        } else {2513          const err = (res as { error?: string })?.error;2514          const errMsg = err === "vault_locked"2515            ? "Vault locked — open Peach to save"2516            : err === "STORAGE_QUOTA_EXCEEDED"2517              ? "Out of storage — open Peach → Settings to free space"2518              : err2519                ? `Could not save: ${err}`2520                : "Could not save entry";2521          showFormError(errMsg);2522          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2523        }2524      } catch (e) {2525        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2526        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2527      }2528    });2529    body.appendChild(saveBtn);2530    body.appendChild(errEl);25312532    wrap.append(head, body);2533    container.appendChild(wrap);2534    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2535  }25362537  function showSuccess(title: string) {2538    currentMode = "success";2539    container.innerHTML = "";2540    const wrap = document.createElement("div"); wrap.className = "success-wrap";2541    const ring = document.createElement("div"); ring.className = "success-ring";2542    ring.innerHTML = checkSvgStr();2543    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2544    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2545    wrap.append(ring, t, s);2546    container.appendChild(wrap);2547    setTimeout(() => dismiss(), 1600);2548  }25492550  function flashActionBtn(btn: HTMLButtonElement) {2551    btn.classList.add("flashed");2552    setTimeout(() => btn.classList.remove("flashed"), 700);2553  }25542555  // M3/QUA-005: when both the direct clipboard write and the background COPY2556  // fallback fail, briefly show the user that the copy did not happen.2557  function flashCopyError(btn: HTMLButtonElement) {2558    const original = btn.textContent ?? "";2559    btn.textContent = "Blocked";2560    btn.classList.add("flashed");2561    setTimeout(() => {2562      btn.classList.remove("flashed");2563      if (btn.isConnected) btn.textContent = original;2564    }, 1200);2565  }25662567  function renderSilverPlatter(entry: SelectorEntry) {2568    container.innerHTML = "";2569    searchInput = null;2570    focusedIndex = -1;2571    currentMode = "silver-platter";2572    silverPlatterOrigin = entry;25732574    const domHdr = document.createElement("div");2575    domHdr.className = "domain-header";2576    const headText = document.createElement("div");2577    headText.className = "domain-header-text";2578    const eyebrow = document.createElement("div");2579    eyebrow.className = "domain-eyebrow";2580    eyebrow.textContent = "Saved for this site";2581    const domName = document.createElement("div");2582    domName.className = "domain-name";2583    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2584    headText.append(eyebrow, domName);2585    domHdr.appendChild(headText);2586    if (!options.isSignup) {2587      const actions = document.createElement("div");2588      actions.className = "domain-header-actions";25892590      // Search shortcut — same idea as type-to-search below, but visible so2591      // the user can discover that another entry is reachable from a2592      // single-match platter. Sits to the left of the create button.2593      const searchBtn = document.createElement("button");2594      searchBtn.className = "domain-search-btn";2595      searchBtn.type = "button";2596      searchBtn.setAttribute("aria-label", "Search for a different entry");2597      searchBtn.title = "Search for a different entry";2598      searchBtn.innerHTML = searchSvgStr();2599      searchBtn.addEventListener("click", (e) => {2600        e.stopPropagation();2601        query = "";2602        renderList();2603      });2604      actions.appendChild(searchBtn);26052606      const addBtn = document.createElement("button");2607      addBtn.className = "domain-add-btn";2608      addBtn.type = "button";2609      addBtn.setAttribute("aria-label", "Create new entry");2610      addBtn.title = "Create new entry";2611      addBtn.textContent = "+";2612      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2613      actions.appendChild(addBtn);26142615      domHdr.appendChild(actions);2616    }2617    container.appendChild(domHdr);26182619    const platter = document.createElement("div");2620    platter.className = "silver-platter";2621    let capabilityActionClaimed = false;2622    const claimCapabilityAction = () => {2623      if (!options.capability) return true;2624      if (capabilityActionClaimed) return false;2625      capabilityActionClaimed = true;2626      return true;2627    };26282629    const titleEl = document.createElement("div");2630    titleEl.className = "sp-title";2631    titleEl.textContent = entry.title;2632    platter.appendChild(titleEl);26332634    if (entry.email) {2635      const emailEl = document.createElement("div");2636      emailEl.className = "sp-identity-row";2637      const emailLbl = document.createElement("span");2638      emailLbl.className = "sp-identity-label";2639      emailLbl.textContent = "email";2640      const emailVal = document.createElement("span");2641      emailVal.className = "sp-username";2642      emailVal.textContent = entry.email;2643      emailEl.append(emailLbl, emailVal);2644      platter.appendChild(emailEl);2645    }26462647    if (entry.username) {2648      const userEl = document.createElement("div");2649      userEl.className = "sp-identity-row";2650      const userLbl = document.createElement("span");2651      userLbl.className = "sp-identity-label";2652      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2653      const userVal = document.createElement("span");2654      userVal.className = "sp-username";2655      userVal.textContent = entry.username;2656      userEl.append(userLbl, userVal);2657      platter.appendChild(userEl);2658    }26592660    const fillBtn = document.createElement("button");2661    fillBtn.className = "sp-fill-btn";2662    fillBtn.type = "button";2663    fillBtn.textContent = "Fill credentials";2664    fillBtn.addEventListener("click", () => {2665      if (fillBtn.disabled || !claimCapabilityAction()) return;2666      fillBtn.disabled = true;2667      fillBtn.classList.add("filled");2668      fillBtn.innerHTML = checkSvgStr();2669      // Fire the fill, then exit via the standard exit animation. The fill2670      // itself is async (handled in index.ts) — by 400ms the form is filled2671      // and the popup begins its exit. Total dwell from click to host2672      // removal: 400ms + 130ms (exit animation) = 530ms.2673      onSelect(entry.id);2674      setTimeout(() => dismiss(), 400);2675    });2676    platter.appendChild(fillBtn);26772678    const actionsGroup = document.createElement("div");2679    actionsGroup.className = "sp-actions-group";2680    const actionsLabel = document.createElement("div");2681    actionsLabel.className = "sp-actions-label";2682    actionsLabel.textContent = "Copy";2683    actionsGroup.appendChild(actionsLabel);26842685    const actions = document.createElement("div");2686    actions.className = "sp-actions";2687    actionsGroup.appendChild(actions);26882689    if (entry.email) {2690      const copyEmail = document.createElement("button");2691      copyEmail.className = "sp-action-btn";2692      copyEmail.type = "button";2693      copyEmail.title = "Copy email";2694      copyEmail.textContent = "Email";2695      copyEmail.addEventListener("click", async (e) => {2696        e.stopPropagation();2697        let alreadyWritten = false;2698        try {2699          await navigator.clipboard.writeText(entry.email!);2700          alreadyWritten = true;2701        } catch (err) {2702          console.warn("[Peach] clipboard write denied:", err);2703        }2704        const resp = await chrome.runtime.sendMessage({2705          type: "COPY",2706          payload: { text: entry.email, label: "Email", alreadyWritten },2707        }).catch(() => null) as { ok?: boolean } | null;2708        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2709        else flashCopyError(copyEmail);2710      });2711      actions.appendChild(copyEmail);2712    }27132714    const copyU = document.createElement("button");2715    copyU.className = "sp-action-btn";2716    copyU.type = "button";2717    const usernameIsEmail = entry.username?.includes("@") ?? false;2718    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2719    copyU.textContent = usernameIsEmail ? "Email" : "Username";2720    copyU.disabled = !entry.username;2721    copyU.addEventListener("click", async (e) => {2722      e.stopPropagation();2723      if (!entry.username) return;2724      let alreadyWritten = false;2725      try {2726        await navigator.clipboard.writeText(entry.username);2727        alreadyWritten = true;2728      } catch (err) {2729        console.warn("[Peach] clipboard write denied:", err);2730      }2731      const resp = await chrome.runtime.sendMessage({2732        type: "COPY",2733        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2734      }).catch(() => null) as { ok?: boolean } | null;2735      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2736      else flashCopyError(copyU);2737    });2738    actions.appendChild(copyU);27392740    const copyP = document.createElement("button");2741    copyP.className = "sp-action-btn";2742    copyP.type = "button";2743    copyP.title = "Copy password";2744    copyP.textContent = "Password";2745    copyP.addEventListener("click", async (e) => {2746      e.stopPropagation();2747      if (!claimCapabilityAction()) return;2748      const resp = await chrome.runtime.sendMessage({2749        type: "GET_ENTRY_FOR_FILL",2750        payload: { id: entry.id, capability: options.capability },2751      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2752      if (!resp?.ok || !resp.data?.password) {2753        if (options.capability) dismiss();2754        return;2755      }2756      let alreadyWritten = false;2757      try {2758        await navigator.clipboard.writeText(resp.data.password);2759        alreadyWritten = true;2760      } catch (err) {2761        console.warn("[Peach] clipboard write denied:", err);2762      }2763      const copyResp = await chrome.runtime.sendMessage({2764        type: "COPY",2765        payload: { text: resp.data.password, label: "Password", alreadyWritten },2766      }).catch(() => null) as { ok?: boolean } | null;2767      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2768      else flashCopyError(copyP);2769      if (options.capability) dismiss();2770    });2771    actions.appendChild(copyP);27722773    let trayEl: HTMLDivElement | null = null;2774    let trayInterval: ReturnType<typeof setInterval> | null = null;27752776    function closeTray() {2777      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2778      trayEl?.remove();2779      trayEl = null;2780    }2781    // Register so dismiss() will close the tray and clear the interval2782    // even if the user dismisses without explicitly closing the tray.2783    cleanupHooks.push(closeTray);27842785    async function openTOTPTray() {2786      // Fetch the current TOTP code from the background. The raw base32 seed2787      // never enters the content script (SEV-3-C): we receive the live 6-digit2788      // code plus the seconds remaining, count down locally, and re-fetch a2789      // fresh code only when the 30s window rolls over.2790      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2791        const r = await chrome.runtime.sendMessage({2792          type: "GET_ENTRY_FOR_FILL",2793          payload: { id: entry.id, capability: options.capability },2794        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2795        if (!r?.ok || !r.data?.totpCode) return null;2796        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2797      }2798      let current = await fetchCode();2799      if (!current) return;28002801      trayEl = document.createElement("div");2802      trayEl.className = "sp-tray";28032804      const label = document.createElement("span");2805      label.className = "sp-tray-label";2806      label.textContent = "2FA";2807      trayEl.appendChild(label);28082809      const codeEl = document.createElement("div");2810      codeEl.className = "sp-totp-code";2811      trayEl.appendChild(codeEl);28122813      const ringNs = "http://www.w3.org/2000/svg";2814      const ring = document.createElementNS(ringNs, "svg");2815      ring.setAttribute("class", "sp-totp-ring");2816      ring.setAttribute("viewBox", "0 0 24 24");2817      const trackC = document.createElementNS(ringNs, "circle");2818      trackC.setAttribute("class", "ring-track");2819      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2820      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2821      const fillC = document.createElementNS(ringNs, "circle");2822      fillC.setAttribute("class", "ring-fill");2823      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2824      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2825      fillC.setAttribute("stroke-linecap", "round");2826      fillC.setAttribute("stroke-dasharray", "62.83");2827      ring.append(trackC, fillC);2828      trayEl.appendChild(ring);28292830      const copyBtn = document.createElement("button");2831      copyBtn.className = "sp-totp-copy";2832      copyBtn.type = "button";2833      copyBtn.textContent = "Copy";2834      trayEl.appendChild(copyBtn);28352836      function render() {2837        const { code, remaining } = current!;2838        // Group as "847 291" — easier to read than "847291"2839        codeEl.textContent = code.length === 62840          ? `${code.slice(0, 3)} ${code.slice(3)}`2841          : code;2842        // Ring fills counter-clockwise as time elapses: dashoffset goes from2843        // 0 (full ring) to 62.83 (empty) over the 30s window.2844        const fraction = (30 - remaining) / 30;2845        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2846      }2847      render();2848      trayInterval = setInterval(async () => {2849        if (!current) return;2850        current = { code: current.code, remaining: current.remaining - 1 };2851        // Window rolled over — pull a fresh code from the background.2852        if (current.remaining <= 0) {2853          const next = await fetchCode();2854          current = next ?? { code: current.code, remaining: 30 };2855        }2856        render();2857      }, 1000);28582859      copyBtn.addEventListener("click", async (e) => {2860        e.stopPropagation();2861        const code = current?.code;2862        if (!code) return;2863        let alreadyWritten = false;2864        try {2865          await navigator.clipboard.writeText(code);2866          alreadyWritten = true;2867        } catch (err) {2868          console.warn("[Peach] clipboard write denied:", err);2869        }2870        const resp = await chrome.runtime.sendMessage({2871          type: "COPY",2872          payload: { text: code, label: "TOTP", alreadyWritten },2873        }).catch(() => null) as { ok?: boolean } | null;2874        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2875        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2876      });28772878      platter.appendChild(trayEl);2879    }28802881    const editBtn = document.createElement("button");2882    editBtn.className = "sp-action-btn sp-action-edit";2883    editBtn.type = "button";2884    editBtn.title = "Edit entry";2885    editBtn.textContent = "Edit";2886    editBtn.addEventListener("click", (e) => {2887      e.stopPropagation();2888      closeTray();2889      void renderInlineEdit(entry);2890    });2891    actions.appendChild(editBtn);28922893    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2894    // "···" toggle was zero-savings (the toggle button took the same space2895    // the "2FA" label needed) and made the code one extra click away.2896    if (entry.hasTotp && !options.capability) void openTOTPTray();28972898    platter.appendChild(actionsGroup);2899    container.appendChild(platter);2900  }29012902  /** Raw TOTP seeds and password history stay inside the extension popup. */2903  async function renderInlineEdit(summary: SelectorEntry) {2904    await chrome.runtime.sendMessage({2905      type: "OPEN_POPUP",2906      payload: { entryId: summary.id },2907    }).catch(() => null);2908    dismiss();2909  }29102911  function renderLocked() {2912    container.innerHTML = "";29132914    // Domain header (same as list view)2915    const domHdr = document.createElement("div");2916    domHdr.className = "domain-header";2917    const eyebrow = document.createElement("div");2918    eyebrow.className = "domain-eyebrow";2919    eyebrow.textContent = "vault locked";2920    const domName = document.createElement("div");2921    domName.className = "domain-name";2922    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2923    domHdr.append(eyebrow, domName);2924    container.appendChild(domHdr);29252926    const wrap = document.createElement("div");2927    wrap.className = "locked-wrap";29282929    // Icon + label row2930    const head = document.createElement("div"); head.className = "locked-head";2931    const icon = document.createElement("div"); icon.className = "locked-icon";2932    icon.innerHTML = keySvgStr();2933    const title = document.createElement("div"); title.className = "locked-title";2934    title.textContent = "unlock to autofill";2935    head.append(icon, title);29362937    // The master password is NEVER collected in page-hosted DOM. A malicious2938    // page can observe keystrokes on the shared DOM event stream (a capture-2939    // phase listener registered before Peach injects sees every key before any2940    // stopImmediatePropagation), which would leak the vault's root secret2941    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2942    // where keystrokes are isolated from the page. After the user unlocks2943    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2944    // automatically (see content/index.ts), so the flow resumes on its own.2945    const sub = document.createElement("div");2946    sub.className = "locked-sub";2947    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";29482949    const openBtn = document.createElement("button");2950    openBtn.className = "locked-btn";2951    openBtn.type = "button";2952    openBtn.textContent = "Open Peach to unlock";2953    openBtn.addEventListener("click", () => {2954      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2955      openBtn.textContent = "opening Peach…";2956      openBtn.disabled = true;2957      // openPopup() can't always open programmatically (browser/version/gesture2958      // limits); reset so the user can retry or click the toolbar icon.2959      setTimeout(() => {2960        if (openBtn.isConnected) {2961          openBtn.textContent = "Open Peach to unlock";2962          openBtn.disabled = false;2963        }2964      }, 2500);2965    });29662967    wrap.append(head, sub, openBtn);2968    container.appendChild(wrap);2969  }29702971  function handleKeyDown(e: KeyboardEvent) {2972    // PCH-01-007: reject page-synthesised KeyboardEvents — only genuine2973    // keystrokes may drive selection/fill. A page hosting an open selector could2974    // otherwise dispatch ArrowDown/Enter at `document` to fill without user intent.2975    if (!e.isTrusted) return;2976    if (options.locked) {2977      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2978      return;2979    }2980    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {2981      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2982      return;2983    }2984    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2985    const count = allEntryEls.length;2986    const activeElement = shadow.activeElement ?? document.activeElement;2987    if (activeElement === searchInput) {2988      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2989      if (count === 0) return;2990      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2991    }2992    if (count === 0) return;2993    switch (e.key) {2994      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2995      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2996      case "Enter": {2997        if (focusedIndex >= 0) {2998          const el = allEntryEls[focusedIndex] as HTMLElement;2999          const id = el.dataset.id;3000          if (id) { onSelect(id); dismiss(); }3001          else if (el.classList.contains("is-new") || !id) {3002            // "New entry" row (last item, no data-id)3003            showCreateForm();3004          }3005        }3006        break;3007      }3008      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3009    }3010  }30113012  document.addEventListener("keydown", handleKeyDown);30133014  // Type-to-search from the silver platter. A printable single-character3015  // keystroke (no modifier) seeds the search query and switches into the3016  // list view, so the user can pivot to a different entry without first3017  // clicking the search icon. Capture phase so the anchor input does not3018  // receive the character before we hijack it.3019  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3020    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3021    if (currentMode !== "silver-platter") return;3022    if (e.ctrlKey || e.metaKey || e.altKey) return;3023    if (e.key.length !== 1) return;3024    e.preventDefault();3025    e.stopImmediatePropagation();3026    query = e.key;3027    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3028    void ensureSearchableLoaded(renderList);3029    renderList();3030  };3031  document.addEventListener("keydown", silverPlatterTypeHandler, true);3032  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));30333034  const identityHelperTypeHandler = (e: KeyboardEvent) => {3035    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3036    if (currentMode !== "identity-helper") return;3037    if (e.ctrlKey || e.metaKey || e.altKey) return;3038    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3039    if (active === searchInput) return;3040    if (3041      active instanceof HTMLInputElement ||3042      active instanceof HTMLTextAreaElement ||3043      (active instanceof HTMLElement && active.isContentEditable)3044    ) {3045      return;3046    }3047    if (e.key.length !== 1) return;3048    e.preventDefault();3049    e.stopImmediatePropagation();3050    query = e.key;3051    renderIdentityHelper();3052  };3053  document.addEventListener("keydown", identityHelperTypeHandler, true);3054  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));30553056  (modalAncestor ?? document.body).appendChild(host);30573058  // position:fixed normally resolves to the viewport, but an ancestor with3059  // transform / filter / backdrop-filter / perspective / contain / will-change3060  // establishes a containing block, so "fixed" then resolves to that ancestor's3061  // padding box instead. When the host is mounted inside such an ancestor (a3062  // modal) we subtract its border-box origin so the popup still lands at the3063  // field's true viewport position. At the document root there is no such3064  // ancestor and the offset is zero.3065  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3066    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3067    return (3068      has("transform") || has("perspective") || has("translate") ||3069      has("rotate") || has("scale") || has("filter") ||3070      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3071      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3072      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3073    );3074  }3075  function containingBlockOffset(): { dx: number; dy: number } {3076    let el: HTMLElement | null = host.parentElement;3077    while (el && el !== document.documentElement) {3078      const s = getComputedStyle(el);3079      if (establishesFixedContainingBlock(s)) {3080        const r = el.getBoundingClientRect();3081        return {3082          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3083          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3084        };3085      }3086      el = el.parentElement;3087    }3088    return { dx: 0, dy: 0 };3089  }30903091  function updatePosition() {3092    const r = anchorEl.getBoundingClientRect();3093    const { dx, dy } = containingBlockOffset();3094    host.style.top = `${r.bottom - dy + 5}px`;3095    host.style.left = `${r.left - dx}px`;3096    host.style.width = `${popupWidth}px`;3097  }3098  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3099  updatePosition();31003101  // observeAnchorPosition listens on window scroll, but a modal with its own3102  // internal scroll container doesn't move the window — track the modal's scroll3103  // too so the popup follows the field inside it.3104  if (modalAncestor) {3105    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3106    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3107  }31083109  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3110  // swap) removes the field without firing blur/click, so none of the normal3111  // dismiss triggers fire and the popup would otherwise linger over nothing.3112  const removalObserver = new MutationObserver(() => {3113    if (!document.contains(anchorEl)) dismiss();3114  });3115  removalObserver.observe(document.body, { childList: true, subtree: true });3116  cleanupHooks.push(() => removalObserver.disconnect());31173118  if (options.locked) {3119    renderLocked();3120  } else if (options.isSignup && options.savedIdentities) {3121    // State 10: identity helper — signup form detected, show derived3122    // identity list (emails then usernames) instead of vault entry list.3123    renderIdentityHelper();3124  } else if (entries.length === 1 && !options.isSignup) {3125    // Silver platter (State 1): single domain match → focused fill view.3126    // Multi-match goes through renderList instead.3127    renderSilverPlatter(entries[0]!);3128  } else {3129    renderList();3130  }31313132  let exitScheduled = false;3133  function dismiss(userAction = false) {3134    // Idempotent: dismiss() can be called from multiple paths (Escape,3135    // outside click, entry select, fill success, host page nav). The exit3136    // animation must only play once and host.remove() must run exactly once.3137    if (exitScheduled) return;3138    exitScheduled = true;3139    // Detach listeners synchronously so nothing can re-trigger during the3140    // 130ms exit window (a focusin firing here would race against the3141    // dismiss-lock work in Pass 2).3142    stopObserving();3143    document.removeEventListener("click", outsideClick, { capture: true });3144    document.removeEventListener("keydown", handleKeyDown);3145    for (const cleanup of cleanupHooks) {3146      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3147    }3148    if (userAction) options.onDismiss?.();3149    container.classList.add("is-exiting");3150    setTimeout(() => host.remove(), 130);3151  }31523153  function outsideClick(ev: MouseEvent) {3154    const path = ev.composedPath();3155    // Never dismiss when clicking the anchor field itself — that click is3156    // what triggered the selector to open, and the user may click the field3157    // again to re-focus it without intending to close the selector.3158    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3159  }3160  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3161  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);31623163  return dismiss;3164}31653166export function showTOTPSelector(3167  anchorEl: HTMLInputElement,3168  entries: SelectorEntry[],3169  onFill: (id: string) => void,3170  options: { domain?: string; onDismiss?: () => void } = {}3171): () => void {3172  const host = document.createElement("div");3173  host.style.cssText = "position: absolute; z-index: 2147483647;";3174  host.style.setProperty("--peach-accent", accentHex);3175  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3176  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3177  const shadow = host.attachShadow({ mode: "closed" });31783179  const style = shadow.appendChild(document.createElement("style"));3180  style.textContent = SELECTOR_STYLES;31813182  const rect = anchorEl.getBoundingClientRect();3183  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3184  host.style.left = `${rect.left + window.scrollX}px`;3185  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3186  host.style.width = `${popupWidth}px`;31873188  const container = shadow.appendChild(document.createElement("div"));3189  container.className = "peach-inline-popup";3190  container.setAttribute("data-theme", popupTheme);31913192  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3193  const current = entries.filter((entry) => entry.hasTotp);3194  let focusedIndex = current.length === 1 ? 0 : -1;31953196  function updatePosition() {3197    const r = anchorEl.getBoundingClientRect();3198    host.style.top = `${r.bottom + window.scrollY + 5}px`;3199    host.style.left = `${r.left + window.scrollX}px`;3200    host.style.width = `${popupWidth}px`;3201  }32023203  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);32043205  function choose(entry: SelectorEntry) {3206    onFill(entry.id);3207    dismiss();3208  }32093210  function render() {3211    container.innerHTML = "";32123213    const domHdr = document.createElement("div");3214    domHdr.className = "domain-header";3215    const headText = document.createElement("div");3216    headText.className = "domain-header-text";3217    const eyebrow = document.createElement("div");3218    eyebrow.className = "domain-eyebrow";3219    eyebrow.textContent = "2FA code";3220    const domName = document.createElement("div");3221    domName.className = "domain-name";3222    domName.textContent = domain;3223    headText.append(eyebrow, domName);3224    domHdr.appendChild(headText);3225    container.appendChild(domHdr);32263227    if (current.length === 1) {3228      const entry = current[0]!;3229      const platter = document.createElement("div");3230      platter.className = "silver-platter";32313232      const title = document.createElement("div");3233      title.className = "sp-title";3234      title.textContent = entry.title;3235      platter.appendChild(title);32363237      const sub = document.createElement("div");3238      sub.className = "sp-username";3239      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3240      platter.appendChild(sub);32413242      const fill = document.createElement("button");3243      fill.className = "sp-fill-btn";3244      fill.type = "button";3245      fill.textContent = "Fill 2FA code";3246      fill.addEventListener("click", () => choose(entry));3247      platter.appendChild(fill);32483249      container.appendChild(platter);3250      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3251      return;3252    }32533254    const results = document.createElement("div");3255    results.className = "results";3256    container.appendChild(results);32573258    for (let i = 0; i < current.length; i++) {3259      const entry = current[i]!;3260      const row = document.createElement("div");3261      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3262      row.dataset.index = String(i);3263      row.setAttribute("tabindex", "-1");32643265      const icon = document.createElement("div");3266      icon.className = "entry-icon";3267      icon.innerHTML = keySvgStr();3268      row.appendChild(icon);3269      const info = document.createElement("div");3270      info.className = "entry-info";3271      const title = document.createElement("div");3272      title.className = "entry-title";3273      title.textContent = entry.title;3274      const sub = document.createElement("div");3275      sub.className = "entry-sub";3276      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3277      info.append(title, sub);3278      row.appendChild(info);32793280      const badge = document.createElement("span");3281      badge.className = "totp-badge";3282      badge.textContent = "Fill";3283      row.appendChild(badge);3284      row.addEventListener("click", () => choose(entry));3285      results.appendChild(row);3286    }3287  }32883289  function setFocused(index: number) {3290    focusedIndex = index;3291    container.querySelectorAll(".entry").forEach((el, i) => {3292      el.classList.toggle("focused", i === focusedIndex);3293      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3294    });3295  }32963297  function handleKeyDown(e: KeyboardEvent) {3298    if (e.key === "Escape" || e.key === "Tab") {3299      e.preventDefault();3300      dismiss(true);3301      return;3302    }3303    if (current.length === 0) return;3304    if (e.key === "Enter") {3305      e.preventDefault();3306      choose(current[Math.max(0, focusedIndex)]!);3307      return;3308    }3309    if (current.length === 1) return;3310    if (e.key === "ArrowDown") {3311      e.preventDefault();3312      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3313    } else if (e.key === "ArrowUp") {3314      e.preventDefault();3315      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3316    }3317  }33183319  let exitScheduled = false;3320  function dismiss(userAction = false) {3321    if (exitScheduled) return;3322    exitScheduled = true;3323    stopObserving();3324    document.removeEventListener("click", outsideClick, { capture: true });3325    document.removeEventListener("keydown", handleKeyDown);3326    if (userAction) options.onDismiss?.();3327    container.classList.add("is-exiting");3328    setTimeout(() => host.remove(), 130);3329  }33303331  function outsideClick(ev: MouseEvent) {3332    const path = ev.composedPath();3333    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3334  }33353336  document.addEventListener("keydown", handleKeyDown);3337  document.body.appendChild(host);3338  render();3339  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33403341  return dismiss;3342}33433344export interface CardSelectorEntry {3345  id: string;3346  title: string;3347  cardholderName?: string;3348  last4?: string;3349  expMonth?: string;3350  expYear?: string;3351  network?: import("../shared/types").CardNetwork;3352}33533354interface CardSelectorOptions {3355  domain?: string;3356  capability?: string;3357  /** Caller-provided fill — receives the full card payload from the SW. */3358  onFill: (entry: import("../shared/types").VaultEntry) => void;3359  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3360  onDismiss?: () => void;3361}33623363/**3364 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3365 * passkey create or get. Renders as a fixed-position floating popup (no3366 * field anchor needed — passkeys don't require a focused input). Uses the3367 * same theme tokens and entrance animation as all other inline popup states.3368 */3369export function showPasskeyProGate(): void {3370  const domain = location.hostname.replace(/^www\./, "");33713372  const host = document.createElement("div");3373  host.setAttribute("data-peach-passkey-gate", "1");3374  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3375  const shadow = host.attachShadow({ mode: "closed" });33763377  const style = document.createElement("style");3378  style.textContent = `3379    :host { all: initial; }3380    .gate-wrap {3381      position: fixed;3382      top: 50%;3383      left: 50%;3384      transform: translate(-50%, -50%);3385      width: 280px;3386      pointer-events: auto;3387      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3388    }3389    @keyframes g-in {3390      from { opacity:0; transform: translate(-50%,-52%); }3391      to   { opacity:1; transform: translate(-50%,-50%); }3392    }3393    .gate-wrap.is-exiting {3394      animation: g-out 130ms ease-in forwards;3395    }3396    @keyframes g-out {3397      to { opacity:0; transform: translate(-50%,-52%); }3398    }3399    .gate {3400      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3401      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3402      border-radius: 12px;3403      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3404      padding: 16px;3405      font-family: Inter, sans-serif;3406    }3407    .gate-header {3408      display: flex;3409      align-items: center;3410      gap: 7px;3411      margin-bottom: 12px;3412      padding-bottom: 10px;3413      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3414    }3415    .gate-domain {3416      font-size: 12px;3417      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3418      font-family: "IBM Plex Mono", monospace;3419      overflow: hidden;3420      text-overflow: ellipsis;3421      white-space: nowrap;3422    }3423    .gate-title {3424      font-size: 14px;3425      font-weight: 500;3426      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3427      margin-bottom: 6px;3428    }3429    .gate-subtitle {3430      font-size: 12px;3431      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3432      line-height: 1.5;3433      margin-bottom: 14px;3434    }3435    .gate-btn {3436      display: block;3437      width: 100%;3438      padding: 9px 0;3439      border-radius: 8px;3440      border: none;3441      cursor: pointer;3442      font-size: 13px;3443      font-family: Inter, sans-serif;3444      font-weight: 500;3445      transition: opacity 100ms;3446      margin-bottom: 7px;3447      text-align: center;3448    }3449    .gate-btn:last-child { margin-bottom: 0; }3450    .gate-btn--accent {3451      background: ${accentHex};3452      color: #fff;3453    }3454    .gate-btn--accent:hover { opacity: 0.88; }3455    .gate-btn--ghost {3456      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3457      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3458    }3459    .gate-btn--ghost:hover { opacity: 0.75; }3460    .backdrop {3461      position: fixed;3462      inset: 0;3463      pointer-events: auto;3464    }3465  `;3466  shadow.appendChild(style);34673468  const backdrop = document.createElement("div");3469  backdrop.className = "backdrop";3470  shadow.appendChild(backdrop);34713472  const wrap = document.createElement("div");3473  wrap.className = "gate-wrap";3474  shadow.appendChild(wrap);34753476  const gate = document.createElement("div");3477  gate.className = "gate";3478  wrap.appendChild(gate);34793480  // Header: peach icon + domain3481  const header = document.createElement("div");3482  header.className = "gate-header";3483  const icon = document.createElement("span");3484  icon.innerHTML = peachIconSvg();3485  const domainEl = document.createElement("span");3486  domainEl.className = "gate-domain";3487  domainEl.textContent = domain;3488  header.append(icon, domainEl);3489  gate.appendChild(header);34903491  const title = document.createElement("div");3492  title.className = "gate-title";3493  title.textContent = "Passkeys are part of Peach Pro.";3494  gate.appendChild(title);34953496  const subtitle = document.createElement("div");3497  subtitle.className = "gate-subtitle";3498  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3499  gate.appendChild(subtitle);35003501  const upgradeBtn = document.createElement("button");3502  upgradeBtn.className = "gate-btn gate-btn--accent";3503  upgradeBtn.type = "button";3504  upgradeBtn.textContent = "Upgrade to Pro";3505  gate.appendChild(upgradeBtn);35063507  const laterBtn = document.createElement("button");3508  laterBtn.className = "gate-btn gate-btn--ghost";3509  laterBtn.type = "button";3510  laterBtn.textContent = "Not right now";3511  gate.appendChild(laterBtn);35123513  function dismiss() {3514    wrap.classList.add("is-exiting");3515    setTimeout(() => host.remove(), 130);3516  }35173518  upgradeBtn.addEventListener("click", () => {3519    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3520    dismiss();3521  });3522  laterBtn.addEventListener("click", dismiss);3523  backdrop.addEventListener("click", dismiss);35243525  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3526    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3527  });35283529  document.body.appendChild(host);3530}35313532/**3533 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3534 * detector sees the page invoke navigator.credentials.create(); content/index.ts3535 * checks vault + decline state then calls this. "Save passkey to Peach"3536 * initiates the popup-context credential flow; "Not now" records a 30-day3537 * decline for the domain so we don't re-show on every page reload.3538 */3539export function showPasskeyRegistrationOffer(args: {3540  rpId: string;3541  rpName?: string;3542  userName?: string;3543  userDisplayName?: string;3544}): void {3545  const domain = location.hostname.replace(/^www\./, "");3546  const displayName = args.rpName || domain;35473548  const host = document.createElement("div");3549  host.setAttribute("data-peach-passkey-offer", "1");3550  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3551  const shadow = host.attachShadow({ mode: "closed" });35523553  const style = document.createElement("style");3554  style.textContent = `3555    :host { all: initial; }3556    .offer-wrap {3557      position: fixed;3558      top: 16px;3559      right: 16px;3560      width: 320px;3561      pointer-events: auto;3562      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3563    }3564    @keyframes o-in {3565      from { opacity: 0; transform: translateY(-6px); }3566      to   { opacity: 1; transform: translateY(0); }3567    }3568    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3569    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3570    .offer {3571      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3572      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3573      border-radius: 12px;3574      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3575      padding: 14px 14px 12px;3576      font-family: Inter, sans-serif;3577      position: relative;3578    }3579    .offer-close {3580      position: absolute;3581      top: 8px;3582      right: 8px;3583      width: 18px;3584      height: 18px;3585      border: none;3586      background: transparent;3587      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3588      cursor: pointer;3589      font-size: 14px;3590      line-height: 1;3591      padding: 0;3592    }3593    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3594    .offer-header {3595      display: flex;3596      align-items: center;3597      gap: 7px;3598      margin-bottom: 8px;3599      padding-bottom: 8px;3600      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3601    }3602    .offer-domain {3603      font-size: 12px;3604      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3605      font-family: "IBM Plex Mono", monospace;3606      overflow: hidden;3607      text-overflow: ellipsis;3608      white-space: nowrap;3609    }3610    .offer-title {3611      font-size: 13px;3612      font-weight: 500;3613      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3614      margin-bottom: 4px;3615    }3616    .offer-subtitle {3617      font-size: 11px;3618      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3619      line-height: 1.45;3620      margin-bottom: 12px;3621    }3622    .offer-btn {3623      display: block;3624      width: 100%;3625      padding: 8px 0;3626      border-radius: 7px;3627      border: none;3628      cursor: pointer;3629      font-size: 12px;3630      font-family: Inter, sans-serif;3631      font-weight: 500;3632      transition: opacity 100ms;3633      margin-bottom: 6px;3634      text-align: center;3635    }3636    .offer-btn:last-child { margin-bottom: 0; }3637    .offer-btn--accent { background: ${accentHex}; color: #fff; }3638    .offer-btn--accent:hover { opacity: 0.88; }3639    .offer-btn--ghost {3640      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3641      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3642    }3643    .offer-btn--ghost:hover { opacity: 0.75; }3644  `;3645  shadow.appendChild(style);36463647  const wrap = document.createElement("div");3648  wrap.className = "offer-wrap";3649  shadow.appendChild(wrap);36503651  const offer = document.createElement("div");3652  offer.className = "offer";3653  wrap.appendChild(offer);36543655  const closeBtn = document.createElement("button");3656  closeBtn.className = "offer-close";3657  closeBtn.type = "button";3658  closeBtn.setAttribute("aria-label", "Dismiss");3659  closeBtn.textContent = "✕";3660  offer.appendChild(closeBtn);36613662  const header = document.createElement("div");3663  header.className = "offer-header";3664  const icon = document.createElement("span");3665  icon.innerHTML = peachIconSvg();3666  const domainEl = document.createElement("span");3667  domainEl.className = "offer-domain";3668  domainEl.textContent = domain;3669  header.append(icon, domainEl);3670  offer.appendChild(header);36713672  const title = document.createElement("div");3673  title.className = "offer-title";3674  title.textContent = "This site supports passkeys.";3675  offer.appendChild(title);36763677  const subtitle = document.createElement("div");3678  subtitle.className = "offer-subtitle";3679  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3680  offer.appendChild(subtitle);36813682  const saveBtn = document.createElement("button");3683  saveBtn.className = "offer-btn offer-btn--accent";3684  saveBtn.type = "button";3685  saveBtn.textContent = "Save passkey to Peach";3686  offer.appendChild(saveBtn);36873688  const laterBtn = document.createElement("button");3689  laterBtn.className = "offer-btn offer-btn--ghost";3690  laterBtn.type = "button";3691  laterBtn.textContent = "Not now";3692  offer.appendChild(laterBtn);36933694  function dismiss(decline: boolean) {3695    if (decline) {3696      chrome.runtime.sendMessage({3697        type: "PASSKEY_OFFER_DECLINE",3698        payload: { domain },3699      }).catch(() => {});3700    }3701    wrap.classList.add("is-exiting");3702    setTimeout(() => host.remove(), 130);3703  }37043705  saveBtn.addEventListener("click", () => {3706    chrome.runtime.sendMessage({3707      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3708      payload: {3709        rpId: args.rpId,3710        rpName: args.rpName ?? displayName,3711        userName: args.userName ?? "user",3712        userDisplayName: args.userDisplayName,3713      },3714    }).catch(() => {});3715    dismiss(false);3716  });3717  laterBtn.addEventListener("click", () => dismiss(true));3718  closeBtn.addEventListener("click", () => dismiss(true));37193720  document.body.appendChild(host);3721}37223723/**3724 * State 11 — passkey available indicator. Shown when the user lands on a3725 * domain for which they already have a stored passkey. Tells them where to3726 * find it (the entry already shows in the vault list); the "Sign in with3727 * passkey" button opens the popup so they can use the platform authenticator3728 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3729 * the actual sign-in transparently, so this banner is informational only.3730 */3731export function showPasskeyAvailable(args: {3732  rpId: string;3733  userName: string;3734  fromBrowser?: "chrome" | "firefox";3735  currentBrowser?: "chrome" | "firefox" | "unknown";3736}): void {3737  const domain = location.hostname.replace(/^www\./, "");3738  const crossBrowser =3739    args.fromBrowser &&3740    args.currentBrowser &&3741    args.currentBrowser !== "unknown" &&3742    args.fromBrowser !== args.currentBrowser;37433744  const host = document.createElement("div");3745  host.setAttribute("data-peach-passkey-available", "1");3746  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3747  const shadow = host.attachShadow({ mode: "closed" });37483749  const style = document.createElement("style");3750  style.textContent = `3751    :host { all: initial; }3752    .avail-wrap {3753      position: fixed;3754      top: 16px;3755      right: 16px;3756      width: 320px;3757      pointer-events: auto;3758      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3759    }3760    @keyframes a-in {3761      from { opacity: 0; transform: translateY(-6px); }3762      to   { opacity: 1; transform: translateY(0); }3763    }3764    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3765    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3766    .avail {3767      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3768      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3769      border-radius: 12px;3770      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3771      padding: 14px 14px 12px;3772      font-family: Inter, sans-serif;3773      position: relative;3774    }3775    .avail-close {3776      position: absolute;3777      top: 8px;3778      right: 8px;3779      width: 18px;3780      height: 18px;3781      border: none;3782      background: transparent;3783      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3784      cursor: pointer;3785      font-size: 14px;3786      line-height: 1;3787      padding: 0;3788    }3789    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3790    .avail-header {3791      display: flex;3792      align-items: center;3793      gap: 7px;3794      margin-bottom: 8px;3795      padding-bottom: 8px;3796      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3797    }3798    .avail-domain {3799      font-size: 12px;3800      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3801      font-family: "IBM Plex Mono", monospace;3802    }3803    .avail-label {3804      font-size: 9px;3805      letter-spacing: 0.16em;3806      text-transform: uppercase;3807      color: ${accentHex};3808      margin-bottom: 4px;3809    }3810    .avail-user {3811      font-size: 13px;3812      font-weight: 500;3813      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3814      margin-bottom: 12px;3815      overflow: hidden;3816      text-overflow: ellipsis;3817      white-space: nowrap;3818    }3819    .avail-cross {3820      font-size: 11px;3821      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3822      line-height: 1.45;3823      margin-bottom: 12px;3824      padding: 8px;3825      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3826      border-radius: 6px;3827    }3828    .avail-btn {3829      display: block;3830      width: 100%;3831      padding: 8px 0;3832      border-radius: 7px;3833      border: none;3834      cursor: pointer;3835      font-size: 12px;3836      font-family: Inter, sans-serif;3837      font-weight: 500;3838      transition: opacity 100ms;3839      margin-bottom: 6px;3840      text-align: center;3841    }3842    .avail-btn:last-child { margin-bottom: 0; }3843    .avail-btn--accent { background: ${accentHex}; color: #fff; }3844    .avail-btn--accent:hover { opacity: 0.88; }3845    .avail-btn--ghost {3846      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3847      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3848    }3849    .avail-btn--ghost:hover { opacity: 0.75; }3850  `;3851  shadow.appendChild(style);38523853  const wrap = document.createElement("div");3854  wrap.className = "avail-wrap";3855  shadow.appendChild(wrap);38563857  const avail = document.createElement("div");3858  avail.className = "avail";3859  wrap.appendChild(avail);38603861  const closeBtn = document.createElement("button");3862  closeBtn.className = "avail-close";3863  closeBtn.type = "button";3864  closeBtn.setAttribute("aria-label", "Dismiss");3865  closeBtn.textContent = "✕";3866  avail.appendChild(closeBtn);38673868  const header = document.createElement("div");3869  header.className = "avail-header";3870  const icon = document.createElement("span");3871  icon.innerHTML = peachIconSvg();3872  const domainEl = document.createElement("span");3873  domainEl.className = "avail-domain";3874  domainEl.textContent = domain;3875  header.append(icon, domainEl);3876  avail.appendChild(header);38773878  const label = document.createElement("div");3879  label.className = "avail-label";3880  label.textContent = "PASSKEY";3881  avail.appendChild(label);38823883  const user = document.createElement("div");3884  user.className = "avail-user";3885  user.textContent = args.userName;3886  avail.appendChild(user);38873888  if (crossBrowser) {3889    const cross = document.createElement("div");3890    cross.className = "avail-cross";3891    cross.textContent =3892      args.fromBrowser === "chrome"3893        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3894        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3895    avail.appendChild(cross);3896  }38973898  const signInBtn = document.createElement("button");3899  signInBtn.className = "avail-btn avail-btn--accent";3900  signInBtn.type = "button";3901  signInBtn.textContent = "Sign in with passkey";3902  avail.appendChild(signInBtn);39033904  const passwordBtn = document.createElement("button");3905  passwordBtn.className = "avail-btn avail-btn--ghost";3906  passwordBtn.type = "button";3907  passwordBtn.textContent = "Use password instead";3908  avail.appendChild(passwordBtn);39093910  function dismiss() {3911    wrap.classList.add("is-exiting");3912    setTimeout(() => host.remove(), 130);3913  }39143915  signInBtn.addEventListener("click", () => {3916    // On Chrome: the user clicking the page's own Sign-in button is what3917    //   triggers webAuthenticationProxy → existing background flow handles it.3918    //   Our button just dismisses since the page itself drives auth.3919    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3920    //   and surface the entry for manual reference (popup view).3921    dismiss();3922    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3923  });3924  passwordBtn.addEventListener("click", dismiss);3925  closeBtn.addEventListener("click", dismiss);39263927  document.body.appendChild(host);3928}39293930/**3931 * State 7 — card silver platter. Single-card focused fill view rendered3932 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3933 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3934 * so card and login flows render identically. Multi-card list view is a3935 * follow-up; today this picks the first card.3936 */3937export function showCardSelector(3938  anchorEl: HTMLInputElement,3939  cards: CardSelectorEntry[],3940  options: CardSelectorOptions3941): () => void {3942  if (cards.length === 0) return () => {};3943  const card = cards[0]!;3944  let capabilityActionClaimed = false;3945  const claimCapabilityAction = () => {3946    if (!options.capability) return true;3947    if (capabilityActionClaimed) return false;3948    capabilityActionClaimed = true;3949    return true;3950  };39513952  const host = document.createElement("div");3953  host.style.cssText = "position: absolute; z-index: 2147483647;";3954  host.style.setProperty("--peach-accent", accentHex);3955  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3956  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3957  const shadow = host.attachShadow({ mode: "closed" });39583959  const style = shadow.appendChild(document.createElement("style"));3960  style.textContent = SELECTOR_STYLES;39613962  const rect = anchorEl.getBoundingClientRect();3963  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3964  host.style.left = `${rect.left + window.scrollX}px`;3965  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;39663967  const container = shadow.appendChild(document.createElement("div"));3968  container.className = "peach-inline-popup";3969  container.setAttribute("data-theme", popupTheme);39703971  // Domain header — eyebrow communicates the card context, not the site3972  const domHdr = document.createElement("div");3973  domHdr.className = "domain-header";3974  const eyebrow = document.createElement("div");3975  eyebrow.className = "domain-eyebrow";3976  eyebrow.textContent = "Pay with Peach";3977  const domName = document.createElement("div");3978  domName.className = "domain-name";3979  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3980  domHdr.append(eyebrow, domName);3981  container.appendChild(domHdr);39823983  const platter = document.createElement("div");3984  platter.className = "card-platter";39853986  if (card.network && card.network !== "unknown") {3987    const net = document.createElement("div");3988    net.className = "cp-network";3989    net.textContent = card.network;3990    platter.appendChild(net);3991  }39923993  const nick = document.createElement("div");3994  nick.className = "cp-nickname";3995  nick.textContent = card.title;3996  platter.appendChild(nick);39973998  if (card.last4) {3999    const l4 = document.createElement("div");4000    l4.className = "cp-last4";4001    l4.textContent = `•••• ${card.last4}`;4002    platter.appendChild(l4);4003  }40044005  const meta = document.createElement("div");4006  meta.className = "cp-meta";4007  if (card.cardholderName) {4008    const name = document.createElement("span");4009    name.textContent = card.cardholderName;4010    meta.appendChild(name);4011  }4012  if (card.expMonth && card.expYear) {4013    if (card.cardholderName) {4014      const sep = document.createElement("span");4015      sep.className = "cp-meta-sep";4016      sep.textContent = "·";4017      meta.appendChild(sep);4018    }4019    const exp = document.createElement("span");4020    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4021    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4022    meta.appendChild(exp);4023  }4024  if (meta.childElementCount > 0) platter.appendChild(meta);40254026  const fillWrap = document.createElement("div");4027  fillWrap.className = "cp-fill-wrap";4028  const fillBtn = document.createElement("button");4029  fillBtn.className = "sp-fill-btn";4030  fillBtn.type = "button";4031  fillBtn.textContent = "Fill card details";4032  fillBtn.addEventListener("click", async () => {4033    if (fillBtn.disabled || !claimCapabilityAction()) return;4034    fillBtn.disabled = true;4035    fillBtn.classList.add("filled");4036    fillBtn.innerHTML = checkSvgStr();4037    const resp = await chrome.runtime.sendMessage({4038      type: "GET_ENTRY_FOR_FILL",4039      // MV-1: explicit user click to fill this card's details.4040      payload: { id: card.id, capability: options.capability },4041    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4042    if (resp?.ok && resp.data) options.onFill(resp.data);4043    setTimeout(() => dismiss(), 400);4044  });4045  fillWrap.appendChild(fillBtn);4046  platter.appendChild(fillWrap);40474048  // Secondary actions — copy number, copy CVC, dismiss4049  const actions = document.createElement("div");4050  actions.className = "sp-actions";40514052  function flashBtn(b: HTMLButtonElement) {4053    b.classList.add("flashed");4054    setTimeout(() => b.classList.remove("flashed"), 700);4055  }40564057  // M3/QUA-005: clipboard + background COPY both failed — show user.4058  function flashCopyError(b: HTMLButtonElement) {4059    const original = b.textContent ?? "";4060    b.textContent = "Blocked";4061    b.classList.add("flashed");4062    setTimeout(() => {4063      b.classList.remove("flashed");4064      if (b.isConnected) b.textContent = original;4065    }, 1200);4066  }40674068  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4069    if (!claimCapabilityAction()) return null;4070    const resp = await chrome.runtime.sendMessage({4071      type: "GET_ENTRY_FOR_FILL",4072      // MV-1: explicit user action on a card the user opened in Peach's UI.4073      payload: { id: card.id, capability: options.capability },4074    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4075    const full = resp?.ok && resp.data ? resp.data : null;4076    if (options.capability) dismiss();4077    return full;4078  }40794080  const copyNum = document.createElement("button");4081  copyNum.className = "sp-action-btn";4082  copyNum.type = "button";4083  copyNum.title = "Copy card number";4084  copyNum.textContent = "Copy number";4085  copyNum.addEventListener("click", async (e) => {4086    e.stopPropagation();4087    const full = await fetchFullCard();4088    if (!full?.cardNumber) return;4089    let alreadyWritten = false;4090    try {4091      await navigator.clipboard.writeText(full.cardNumber);4092      alreadyWritten = true;4093    } catch (err) {4094      console.warn("[Peach] clipboard write denied:", err);4095    }4096    const resp = await chrome.runtime.sendMessage({4097      type: "COPY",4098      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4099    }).catch(() => null) as { ok?: boolean } | null;4100    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4101    else flashCopyError(copyNum);4102  });4103  actions.appendChild(copyNum);41044105  const copyCvc = document.createElement("button");4106  copyCvc.className = "sp-action-btn";4107  copyCvc.type = "button";4108  copyCvc.title = "Copy CVC";4109  copyCvc.textContent = "Copy CVC";4110  copyCvc.addEventListener("click", async (e) => {4111    e.stopPropagation();4112    const full = await fetchFullCard();4113    if (!full?.cvc) return;4114    let alreadyWritten = false;4115    try {4116      await navigator.clipboard.writeText(full.cvc);4117      alreadyWritten = true;4118    } catch (err) {4119      console.warn("[Peach] clipboard write denied:", err);4120    }4121    const resp = await chrome.runtime.sendMessage({4122      type: "COPY",4123      payload: { text: full.cvc, label: "CVC", alreadyWritten },4124    }).catch(() => null) as { ok?: boolean } | null;4125    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4126    else flashCopyError(copyCvc);4127  });4128  actions.appendChild(copyCvc);41294130  const closeBtn = document.createElement("button");4131  closeBtn.className = "sp-action-btn";4132  closeBtn.type = "button";4133  closeBtn.title = "Dismiss";4134  closeBtn.textContent = "✕";4135  closeBtn.addEventListener("click", (e) => {4136    e.stopPropagation();4137    dismiss(true);4138  });4139  actions.appendChild(closeBtn);41404141  platter.appendChild(actions);4142  container.appendChild(platter);41434144  document.body.appendChild(host);4145  function updatePosition() {4146    const r = anchorEl.getBoundingClientRect();4147    host.style.top = `${r.bottom + window.scrollY + 5}px`;4148    host.style.left = `${r.left + window.scrollX}px`;4149  }4150  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);41514152  function onKeyDown(e: KeyboardEvent) {4153    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4154  }4155  document.addEventListener("keydown", onKeyDown);41564157  let exitScheduled = false;4158  function dismiss(userAction = false) {4159    if (exitScheduled) return;4160    exitScheduled = true;4161    stopObserving();4162    document.removeEventListener("click", outsideClick, { capture: true });4163    document.removeEventListener("keydown", onKeyDown);4164    if (userAction) options.onDismiss?.();4165    container.classList.add("is-exiting");4166    setTimeout(() => host.remove(), 130);4167  }41684169  function outsideClick(ev: MouseEvent) {4170    const path = ev.composedPath();4171    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4172  }4173  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);41744175  return dismiss;4176}