inject.ts

168.1 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    // Fetch identities on-demand — they're passed in signup context but not2415    // in login/search context where the user still clicks "New entry".2416    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];2417    if (!formIdentities.length) {2418      try {2419        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;2420        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;2421      } catch { /* silent fallback */ }2422    }24232424    const wrap = document.createElement("div");2425    wrap.className = "create-form-wrap";24262427    // Header2428    const head = document.createElement("div"); head.className = "create-head";2429    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2430    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>`;2431    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2432    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2433    head.append(backBtn, lbl);24342435    // Body2436    const body = document.createElement("div"); body.className = "create-body";24372438    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2439      const g = document.createElement("div"); g.className = "f-group";2440      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2441      const inp = document.createElement("input"); inp.className = "f-input";2442      g.append(l, inp); return { g, inp };2443    }24442445    // Title2446    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2447    body.appendChild(tg.g);24482449    // URL2450    const ug = fGroup("website");2451    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2452    if (loginSubdomain) {2453      const h = document.createElement("div"); h.className = "url-hint";2454      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2455    }2456    body.appendChild(ug.g);24572458    // Username — pre-fill from anchor if it doesn't look like an email2459    const xg = fGroup("username");2460    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2461    xg.inp.placeholder = "johndoe";2462    xg.inp.setAttribute("autocomplete", "off");2463    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2464    body.appendChild(xg.g);24652466    // Email — pre-fill from anchor if it looks like an email2467    const eg = fGroup("email");2468    (eg.inp as HTMLInputElement).type = "email";2469    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2470    eg.inp.placeholder = "[email protected]";2471    eg.inp.setAttribute("autocomplete", "off");2472    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2473    body.appendChild(eg.g);24742475    // Password — full smart generator with charset pills + length slider +2476    // policy hint. Mirrors the main UI's compact generator so users get the2477    // same controls inline as in the popup.2478    const pg = fGroup("password");2479    pg.inp.remove(); // smartGen provides its own display — no separate input needed2480    let currentPassword = prePassword || "";2481    const smartGen = createSmartGenerator({2482      policy: sitePolicy,2483      initialPassword: prePassword || undefined,2484      onChange: (pw) => { currentPassword = pw; },2485    });2486    pg.g.appendChild(smartGen.root);2487    body.appendChild(pg.g);24882489    // Save2490    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2491    saveBtn.textContent = "Save entry";2492    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2493    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2494    saveBtn.addEventListener("click", async () => {2495      const title = tg.inp.value.trim();2496      const pw = currentPassword.trim();2497      const username = xg.inp.value.trim();2498      const email = eg.inp.value.trim();2499      if (!title) {2500        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2501        showFormError("Entry needs a title");2502        return;2503      }2504      if (!pw) {2505        showFormError("Entry needs a password — tap regen to make one");2506        return;2507      }2508      errEl.style.display = "none";2509      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2510      try {2511        const res = await chrome.runtime.sendMessage({2512          type: "ADD_ENTRY",2513          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2514        });2515        if ((res as { ok?: boolean }).ok) {2516          // Fill the detected form. onFillFields uses whichever identity the2517          // page anchored on — the vault captures both username and email.2518          options.onFillFields?.(username || email, pw);2519          showSuccess(title);2520        } else {2521          const err = (res as { error?: string })?.error;2522          const errMsg = err === "vault_locked"2523            ? "Vault locked — open Peach to save"2524            : err === "STORAGE_QUOTA_EXCEEDED"2525              ? "Out of storage — open Peach → Settings to free space"2526              : err2527                ? `Could not save: ${err}`2528                : "Could not save entry";2529          showFormError(errMsg);2530          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2531        }2532      } catch (e) {2533        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2534        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2535      }2536    });2537    body.appendChild(saveBtn);2538    body.appendChild(errEl);25392540    wrap.append(head, body);2541    container.appendChild(wrap);2542    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2543  }25442545  function showSuccess(title: string) {2546    currentMode = "success";2547    container.innerHTML = "";2548    const wrap = document.createElement("div"); wrap.className = "success-wrap";2549    const ring = document.createElement("div"); ring.className = "success-ring";2550    ring.innerHTML = checkSvgStr();2551    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2552    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2553    wrap.append(ring, t, s);2554    container.appendChild(wrap);2555    setTimeout(() => dismiss(), 1600);2556  }25572558  function flashActionBtn(btn: HTMLButtonElement) {2559    btn.classList.add("flashed");2560    setTimeout(() => btn.classList.remove("flashed"), 700);2561  }25622563  // M3/QUA-005: when both the direct clipboard write and the background COPY2564  // fallback fail, briefly show the user that the copy did not happen.2565  function flashCopyError(btn: HTMLButtonElement) {2566    const original = btn.textContent ?? "";2567    btn.textContent = "Blocked";2568    btn.classList.add("flashed");2569    setTimeout(() => {2570      btn.classList.remove("flashed");2571      if (btn.isConnected) btn.textContent = original;2572    }, 1200);2573  }25742575  function renderSilverPlatter(entry: SelectorEntry) {2576    container.innerHTML = "";2577    searchInput = null;2578    focusedIndex = -1;2579    currentMode = "silver-platter";2580    silverPlatterOrigin = entry;25812582    const domHdr = document.createElement("div");2583    domHdr.className = "domain-header";2584    const headText = document.createElement("div");2585    headText.className = "domain-header-text";2586    const eyebrow = document.createElement("div");2587    eyebrow.className = "domain-eyebrow";2588    eyebrow.textContent = "Saved for this site";2589    const domName = document.createElement("div");2590    domName.className = "domain-name";2591    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2592    headText.append(eyebrow, domName);2593    domHdr.appendChild(headText);2594    if (!options.isSignup) {2595      const actions = document.createElement("div");2596      actions.className = "domain-header-actions";25972598      // Search shortcut — same idea as type-to-search below, but visible so2599      // the user can discover that another entry is reachable from a2600      // single-match platter. Sits to the left of the create button.2601      const searchBtn = document.createElement("button");2602      searchBtn.className = "domain-search-btn";2603      searchBtn.type = "button";2604      searchBtn.setAttribute("aria-label", "Search for a different entry");2605      searchBtn.title = "Search for a different entry";2606      searchBtn.innerHTML = searchSvgStr();2607      searchBtn.addEventListener("click", (e) => {2608        e.stopPropagation();2609        query = "";2610        renderList();2611      });2612      actions.appendChild(searchBtn);26132614      const addBtn = document.createElement("button");2615      addBtn.className = "domain-add-btn";2616      addBtn.type = "button";2617      addBtn.setAttribute("aria-label", "Create new entry");2618      addBtn.title = "Create new entry";2619      addBtn.textContent = "+";2620      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2621      actions.appendChild(addBtn);26222623      domHdr.appendChild(actions);2624    }2625    container.appendChild(domHdr);26262627    const platter = document.createElement("div");2628    platter.className = "silver-platter";2629    let capabilityActionClaimed = false;2630    const claimCapabilityAction = () => {2631      if (!options.capability) return true;2632      if (capabilityActionClaimed) return false;2633      capabilityActionClaimed = true;2634      return true;2635    };26362637    const titleEl = document.createElement("div");2638    titleEl.className = "sp-title";2639    titleEl.textContent = entry.title;2640    platter.appendChild(titleEl);26412642    if (entry.email) {2643      const emailEl = document.createElement("div");2644      emailEl.className = "sp-identity-row";2645      const emailLbl = document.createElement("span");2646      emailLbl.className = "sp-identity-label";2647      emailLbl.textContent = "email";2648      const emailVal = document.createElement("span");2649      emailVal.className = "sp-username";2650      emailVal.textContent = entry.email;2651      emailEl.append(emailLbl, emailVal);2652      platter.appendChild(emailEl);2653    }26542655    if (entry.username) {2656      const userEl = document.createElement("div");2657      userEl.className = "sp-identity-row";2658      const userLbl = document.createElement("span");2659      userLbl.className = "sp-identity-label";2660      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2661      const userVal = document.createElement("span");2662      userVal.className = "sp-username";2663      userVal.textContent = entry.username;2664      userEl.append(userLbl, userVal);2665      platter.appendChild(userEl);2666    }26672668    const fillBtn = document.createElement("button");2669    fillBtn.className = "sp-fill-btn";2670    fillBtn.type = "button";2671    fillBtn.textContent = "Fill credentials";2672    fillBtn.addEventListener("click", () => {2673      if (fillBtn.disabled || !claimCapabilityAction()) return;2674      fillBtn.disabled = true;2675      fillBtn.classList.add("filled");2676      fillBtn.innerHTML = checkSvgStr();2677      // Fire the fill, then exit via the standard exit animation. The fill2678      // itself is async (handled in index.ts) — by 400ms the form is filled2679      // and the popup begins its exit. Total dwell from click to host2680      // removal: 400ms + 130ms (exit animation) = 530ms.2681      onSelect(entry.id);2682      setTimeout(() => dismiss(), 400);2683    });2684    platter.appendChild(fillBtn);26852686    const actionsGroup = document.createElement("div");2687    actionsGroup.className = "sp-actions-group";2688    const actionsLabel = document.createElement("div");2689    actionsLabel.className = "sp-actions-label";2690    actionsLabel.textContent = "Copy";2691    actionsGroup.appendChild(actionsLabel);26922693    const actions = document.createElement("div");2694    actions.className = "sp-actions";2695    actionsGroup.appendChild(actions);26962697    if (entry.email) {2698      const copyEmail = document.createElement("button");2699      copyEmail.className = "sp-action-btn";2700      copyEmail.type = "button";2701      copyEmail.title = "Copy email";2702      copyEmail.textContent = "Email";2703      copyEmail.addEventListener("click", async (e) => {2704        e.stopPropagation();2705        let alreadyWritten = false;2706        try {2707          await navigator.clipboard.writeText(entry.email!);2708          alreadyWritten = true;2709        } catch (err) {2710          console.warn("[Peach] clipboard write denied:", err);2711        }2712        const resp = await chrome.runtime.sendMessage({2713          type: "COPY",2714          payload: { text: entry.email, label: "Email", alreadyWritten },2715        }).catch(() => null) as { ok?: boolean } | null;2716        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2717        else flashCopyError(copyEmail);2718      });2719      actions.appendChild(copyEmail);2720    }27212722    const copyU = document.createElement("button");2723    copyU.className = "sp-action-btn";2724    copyU.type = "button";2725    const usernameIsEmail = entry.username?.includes("@") ?? false;2726    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2727    copyU.textContent = usernameIsEmail ? "Email" : "Username";2728    copyU.disabled = !entry.username;2729    copyU.addEventListener("click", async (e) => {2730      e.stopPropagation();2731      if (!entry.username) return;2732      let alreadyWritten = false;2733      try {2734        await navigator.clipboard.writeText(entry.username);2735        alreadyWritten = true;2736      } catch (err) {2737        console.warn("[Peach] clipboard write denied:", err);2738      }2739      const resp = await chrome.runtime.sendMessage({2740        type: "COPY",2741        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2742      }).catch(() => null) as { ok?: boolean } | null;2743      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2744      else flashCopyError(copyU);2745    });2746    actions.appendChild(copyU);27472748    const copyP = document.createElement("button");2749    copyP.className = "sp-action-btn";2750    copyP.type = "button";2751    copyP.title = "Copy password";2752    copyP.textContent = "Password";2753    copyP.addEventListener("click", async (e) => {2754      e.stopPropagation();2755      if (!claimCapabilityAction()) return;2756      const resp = await chrome.runtime.sendMessage({2757        type: "GET_ENTRY_FOR_FILL",2758        payload: { id: entry.id, capability: options.capability },2759      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2760      if (!resp?.ok || !resp.data?.password) {2761        if (options.capability) dismiss();2762        return;2763      }2764      let alreadyWritten = false;2765      try {2766        await navigator.clipboard.writeText(resp.data.password);2767        alreadyWritten = true;2768      } catch (err) {2769        console.warn("[Peach] clipboard write denied:", err);2770      }2771      const copyResp = await chrome.runtime.sendMessage({2772        type: "COPY",2773        payload: { text: resp.data.password, label: "Password", alreadyWritten },2774      }).catch(() => null) as { ok?: boolean } | null;2775      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2776      else flashCopyError(copyP);2777      if (options.capability) dismiss();2778    });2779    actions.appendChild(copyP);27802781    let trayEl: HTMLDivElement | null = null;2782    let trayInterval: ReturnType<typeof setInterval> | null = null;27832784    function closeTray() {2785      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2786      trayEl?.remove();2787      trayEl = null;2788    }2789    // Register so dismiss() will close the tray and clear the interval2790    // even if the user dismisses without explicitly closing the tray.2791    cleanupHooks.push(closeTray);27922793    async function openTOTPTray() {2794      // Fetch the current TOTP code from the background. The raw base32 seed2795      // never enters the content script (SEV-3-C): we receive the live 6-digit2796      // code plus the seconds remaining, count down locally, and re-fetch a2797      // fresh code only when the 30s window rolls over.2798      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2799        const r = await chrome.runtime.sendMessage({2800          type: "GET_ENTRY_FOR_FILL",2801          payload: { id: entry.id, capability: options.capability },2802        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2803        if (!r?.ok || !r.data?.totpCode) return null;2804        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2805      }2806      let current = await fetchCode();2807      if (!current) return;28082809      trayEl = document.createElement("div");2810      trayEl.className = "sp-tray";28112812      const label = document.createElement("span");2813      label.className = "sp-tray-label";2814      label.textContent = "2FA";2815      trayEl.appendChild(label);28162817      const codeEl = document.createElement("div");2818      codeEl.className = "sp-totp-code";2819      trayEl.appendChild(codeEl);28202821      const ringNs = "http://www.w3.org/2000/svg";2822      const ring = document.createElementNS(ringNs, "svg");2823      ring.setAttribute("class", "sp-totp-ring");2824      ring.setAttribute("viewBox", "0 0 24 24");2825      const trackC = document.createElementNS(ringNs, "circle");2826      trackC.setAttribute("class", "ring-track");2827      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2828      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2829      const fillC = document.createElementNS(ringNs, "circle");2830      fillC.setAttribute("class", "ring-fill");2831      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2832      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2833      fillC.setAttribute("stroke-linecap", "round");2834      fillC.setAttribute("stroke-dasharray", "62.83");2835      ring.append(trackC, fillC);2836      trayEl.appendChild(ring);28372838      const copyBtn = document.createElement("button");2839      copyBtn.className = "sp-totp-copy";2840      copyBtn.type = "button";2841      copyBtn.textContent = "Copy";2842      trayEl.appendChild(copyBtn);28432844      function render() {2845        const { code, remaining } = current!;2846        // Group as "847 291" — easier to read than "847291"2847        codeEl.textContent = code.length === 62848          ? `${code.slice(0, 3)} ${code.slice(3)}`2849          : code;2850        // Ring fills counter-clockwise as time elapses: dashoffset goes from2851        // 0 (full ring) to 62.83 (empty) over the 30s window.2852        const fraction = (30 - remaining) / 30;2853        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2854      }2855      render();2856      trayInterval = setInterval(async () => {2857        if (!current) return;2858        current = { code: current.code, remaining: current.remaining - 1 };2859        // Window rolled over — pull a fresh code from the background.2860        if (current.remaining <= 0) {2861          const next = await fetchCode();2862          current = next ?? { code: current.code, remaining: 30 };2863        }2864        render();2865      }, 1000);28662867      copyBtn.addEventListener("click", async (e) => {2868        e.stopPropagation();2869        const code = current?.code;2870        if (!code) return;2871        let alreadyWritten = false;2872        try {2873          await navigator.clipboard.writeText(code);2874          alreadyWritten = true;2875        } catch (err) {2876          console.warn("[Peach] clipboard write denied:", err);2877        }2878        const resp = await chrome.runtime.sendMessage({2879          type: "COPY",2880          payload: { text: code, label: "TOTP", alreadyWritten },2881        }).catch(() => null) as { ok?: boolean } | null;2882        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2883        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2884      });28852886      platter.appendChild(trayEl);2887    }28882889    const editBtn = document.createElement("button");2890    editBtn.className = "sp-action-btn sp-action-edit";2891    editBtn.type = "button";2892    editBtn.title = "Edit entry";2893    editBtn.textContent = "Edit";2894    editBtn.addEventListener("click", (e) => {2895      e.stopPropagation();2896      closeTray();2897      void renderInlineEdit(entry);2898    });2899    actions.appendChild(editBtn);29002901    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2902    // "···" toggle was zero-savings (the toggle button took the same space2903    // the "2FA" label needed) and made the code one extra click away.2904    if (entry.hasTotp && !options.capability) void openTOTPTray();29052906    platter.appendChild(actionsGroup);2907    container.appendChild(platter);2908  }29092910  /** Raw TOTP seeds and password history stay inside the extension popup. */2911  async function renderInlineEdit(summary: SelectorEntry) {2912    await chrome.runtime.sendMessage({2913      type: "OPEN_POPUP",2914      payload: { entryId: summary.id },2915    }).catch(() => null);2916    dismiss();2917  }29182919  function renderLocked() {2920    container.innerHTML = "";29212922    // Domain header (same as list view)2923    const domHdr = document.createElement("div");2924    domHdr.className = "domain-header";2925    const eyebrow = document.createElement("div");2926    eyebrow.className = "domain-eyebrow";2927    eyebrow.textContent = "vault locked";2928    const domName = document.createElement("div");2929    domName.className = "domain-name";2930    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2931    domHdr.append(eyebrow, domName);2932    container.appendChild(domHdr);29332934    const wrap = document.createElement("div");2935    wrap.className = "locked-wrap";29362937    // Icon + label row2938    const head = document.createElement("div"); head.className = "locked-head";2939    const icon = document.createElement("div"); icon.className = "locked-icon";2940    icon.innerHTML = keySvgStr();2941    const title = document.createElement("div"); title.className = "locked-title";2942    title.textContent = "unlock to autofill";2943    head.append(icon, title);29442945    // The master password is NEVER collected in page-hosted DOM. A malicious2946    // page can observe keystrokes on the shared DOM event stream (a capture-2947    // phase listener registered before Peach injects sees every key before any2948    // stopImmediatePropagation), which would leak the vault's root secret2949    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2950    // where keystrokes are isolated from the page. After the user unlocks2951    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2952    // automatically (see content/index.ts), so the flow resumes on its own.2953    const sub = document.createElement("div");2954    sub.className = "locked-sub";2955    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";29562957    const openBtn = document.createElement("button");2958    openBtn.className = "locked-btn";2959    openBtn.type = "button";2960    openBtn.textContent = "Open Peach to unlock";2961    openBtn.addEventListener("click", () => {2962      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2963      openBtn.textContent = "opening Peach…";2964      openBtn.disabled = true;2965      // openPopup() can't always open programmatically (browser/version/gesture2966      // limits); reset so the user can retry or click the toolbar icon.2967      setTimeout(() => {2968        if (openBtn.isConnected) {2969          openBtn.textContent = "Open Peach to unlock";2970          openBtn.disabled = false;2971        }2972      }, 2500);2973    });29742975    wrap.append(head, sub, openBtn);2976    container.appendChild(wrap);2977  }29782979  function handleKeyDown(e: KeyboardEvent) {2980    // PCH-01-007: reject page-synthesised KeyboardEvents — only genuine2981    // keystrokes may drive selection/fill. A page hosting an open selector could2982    // otherwise dispatch ArrowDown/Enter at `document` to fill without user intent.2983    if (!e.isTrusted) return;2984    if (options.locked) {2985      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2986      return;2987    }2988    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {2989      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2990      return;2991    }2992    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2993    const count = allEntryEls.length;2994    const activeElement = shadow.activeElement ?? document.activeElement;2995    if (activeElement === searchInput) {2996      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2997      if (count === 0) return;2998      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2999    }3000    if (count === 0) return;3001    switch (e.key) {3002      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3003      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3004      case "Enter": {3005        if (focusedIndex >= 0) {3006          const el = allEntryEls[focusedIndex] as HTMLElement;3007          const id = el.dataset.id;3008          if (id) { onSelect(id); dismiss(); }3009          else if (el.classList.contains("is-new") || !id) {3010            // "New entry" row (last item, no data-id)3011            showCreateForm();3012          }3013        }3014        break;3015      }3016      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3017    }3018  }30193020  document.addEventListener("keydown", handleKeyDown);30213022  // Type-to-search from the silver platter. A printable single-character3023  // keystroke (no modifier) seeds the search query and switches into the3024  // list view, so the user can pivot to a different entry without first3025  // clicking the search icon. Capture phase so the anchor input does not3026  // receive the character before we hijack it.3027  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3028    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3029    if (currentMode !== "silver-platter") return;3030    if (e.ctrlKey || e.metaKey || e.altKey) return;3031    if (e.key.length !== 1) return;3032    e.preventDefault();3033    e.stopImmediatePropagation();3034    query = e.key;3035    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3036    void ensureSearchableLoaded(renderList);3037    renderList();3038  };3039  document.addEventListener("keydown", silverPlatterTypeHandler, true);3040  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));30413042  const identityHelperTypeHandler = (e: KeyboardEvent) => {3043    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3044    if (currentMode !== "identity-helper") return;3045    if (e.ctrlKey || e.metaKey || e.altKey) return;3046    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3047    if (active === searchInput) return;3048    if (3049      active instanceof HTMLInputElement ||3050      active instanceof HTMLTextAreaElement ||3051      (active instanceof HTMLElement && active.isContentEditable)3052    ) {3053      return;3054    }3055    if (e.key.length !== 1) return;3056    e.preventDefault();3057    e.stopImmediatePropagation();3058    query = e.key;3059    renderIdentityHelper();3060  };3061  document.addEventListener("keydown", identityHelperTypeHandler, true);3062  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));30633064  (modalAncestor ?? document.body).appendChild(host);30653066  // position:fixed normally resolves to the viewport, but an ancestor with3067  // transform / filter / backdrop-filter / perspective / contain / will-change3068  // establishes a containing block, so "fixed" then resolves to that ancestor's3069  // padding box instead. When the host is mounted inside such an ancestor (a3070  // modal) we subtract its border-box origin so the popup still lands at the3071  // field's true viewport position. At the document root there is no such3072  // ancestor and the offset is zero.3073  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3074    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3075    return (3076      has("transform") || has("perspective") || has("translate") ||3077      has("rotate") || has("scale") || has("filter") ||3078      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3079      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3080      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3081    );3082  }3083  function containingBlockOffset(): { dx: number; dy: number } {3084    let el: HTMLElement | null = host.parentElement;3085    while (el && el !== document.documentElement) {3086      const s = getComputedStyle(el);3087      if (establishesFixedContainingBlock(s)) {3088        const r = el.getBoundingClientRect();3089        return {3090          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3091          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3092        };3093      }3094      el = el.parentElement;3095    }3096    return { dx: 0, dy: 0 };3097  }30983099  function updatePosition() {3100    const r = anchorEl.getBoundingClientRect();3101    const { dx, dy } = containingBlockOffset();3102    host.style.top = `${r.bottom - dy + 5}px`;3103    host.style.left = `${r.left - dx}px`;3104    host.style.width = `${popupWidth}px`;3105  }3106  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3107  updatePosition();31083109  // observeAnchorPosition listens on window scroll, but a modal with its own3110  // internal scroll container doesn't move the window — track the modal's scroll3111  // too so the popup follows the field inside it.3112  if (modalAncestor) {3113    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3114    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3115  }31163117  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3118  // swap) removes the field without firing blur/click, so none of the normal3119  // dismiss triggers fire and the popup would otherwise linger over nothing.3120  const removalObserver = new MutationObserver(() => {3121    if (!document.contains(anchorEl)) dismiss();3122  });3123  removalObserver.observe(document.body, { childList: true, subtree: true });3124  cleanupHooks.push(() => removalObserver.disconnect());31253126  if (options.locked) {3127    renderLocked();3128  } else if (options.isSignup && options.savedIdentities) {3129    // State 10: identity helper — signup form detected, show derived3130    // identity list (emails then usernames) instead of vault entry list.3131    renderIdentityHelper();3132  } else if (entries.length === 1 && !options.isSignup) {3133    // Silver platter (State 1): single domain match → focused fill view.3134    // Multi-match goes through renderList instead.3135    renderSilverPlatter(entries[0]!);3136  } else {3137    renderList();3138  }31393140  let exitScheduled = false;3141  function dismiss(userAction = false) {3142    // Idempotent: dismiss() can be called from multiple paths (Escape,3143    // outside click, entry select, fill success, host page nav). The exit3144    // animation must only play once and host.remove() must run exactly once.3145    if (exitScheduled) return;3146    exitScheduled = true;3147    // Detach listeners synchronously so nothing can re-trigger during the3148    // 130ms exit window (a focusin firing here would race against the3149    // dismiss-lock work in Pass 2).3150    stopObserving();3151    document.removeEventListener("click", outsideClick, { capture: true });3152    document.removeEventListener("keydown", handleKeyDown);3153    for (const cleanup of cleanupHooks) {3154      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3155    }3156    if (userAction) options.onDismiss?.();3157    container.classList.add("is-exiting");3158    setTimeout(() => host.remove(), 130);3159  }31603161  function outsideClick(ev: MouseEvent) {3162    const path = ev.composedPath();3163    // Never dismiss when clicking the anchor field itself — that click is3164    // what triggered the selector to open, and the user may click the field3165    // again to re-focus it without intending to close the selector.3166    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3167  }3168  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3169  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);31703171  return dismiss;3172}31733174export function showTOTPSelector(3175  anchorEl: HTMLInputElement,3176  entries: SelectorEntry[],3177  onFill: (id: string) => void,3178  options: { domain?: string; onDismiss?: () => void } = {}3179): () => void {3180  const host = document.createElement("div");3181  host.style.cssText = "position: absolute; z-index: 2147483647;";3182  host.style.setProperty("--peach-accent", accentHex);3183  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3184  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3185  const shadow = host.attachShadow({ mode: "closed" });31863187  const style = shadow.appendChild(document.createElement("style"));3188  style.textContent = SELECTOR_STYLES;31893190  const rect = anchorEl.getBoundingClientRect();3191  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3192  host.style.left = `${rect.left + window.scrollX}px`;3193  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3194  host.style.width = `${popupWidth}px`;31953196  const container = shadow.appendChild(document.createElement("div"));3197  container.className = "peach-inline-popup";3198  container.setAttribute("data-theme", popupTheme);31993200  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3201  const current = entries.filter((entry) => entry.hasTotp);3202  let focusedIndex = current.length === 1 ? 0 : -1;32033204  function updatePosition() {3205    const r = anchorEl.getBoundingClientRect();3206    host.style.top = `${r.bottom + window.scrollY + 5}px`;3207    host.style.left = `${r.left + window.scrollX}px`;3208    host.style.width = `${popupWidth}px`;3209  }32103211  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);32123213  function choose(entry: SelectorEntry) {3214    onFill(entry.id);3215    dismiss();3216  }32173218  function render() {3219    container.innerHTML = "";32203221    const domHdr = document.createElement("div");3222    domHdr.className = "domain-header";3223    const headText = document.createElement("div");3224    headText.className = "domain-header-text";3225    const eyebrow = document.createElement("div");3226    eyebrow.className = "domain-eyebrow";3227    eyebrow.textContent = "2FA code";3228    const domName = document.createElement("div");3229    domName.className = "domain-name";3230    domName.textContent = domain;3231    headText.append(eyebrow, domName);3232    domHdr.appendChild(headText);3233    container.appendChild(domHdr);32343235    if (current.length === 1) {3236      const entry = current[0]!;3237      const platter = document.createElement("div");3238      platter.className = "silver-platter";32393240      const title = document.createElement("div");3241      title.className = "sp-title";3242      title.textContent = entry.title;3243      platter.appendChild(title);32443245      const sub = document.createElement("div");3246      sub.className = "sp-username";3247      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3248      platter.appendChild(sub);32493250      const fill = document.createElement("button");3251      fill.className = "sp-fill-btn";3252      fill.type = "button";3253      fill.textContent = "Fill 2FA code";3254      fill.addEventListener("click", () => choose(entry));3255      platter.appendChild(fill);32563257      container.appendChild(platter);3258      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3259      return;3260    }32613262    const results = document.createElement("div");3263    results.className = "results";3264    container.appendChild(results);32653266    for (let i = 0; i < current.length; i++) {3267      const entry = current[i]!;3268      const row = document.createElement("div");3269      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3270      row.dataset.index = String(i);3271      row.setAttribute("tabindex", "-1");32723273      const icon = document.createElement("div");3274      icon.className = "entry-icon";3275      icon.innerHTML = keySvgStr();3276      row.appendChild(icon);3277      const info = document.createElement("div");3278      info.className = "entry-info";3279      const title = document.createElement("div");3280      title.className = "entry-title";3281      title.textContent = entry.title;3282      const sub = document.createElement("div");3283      sub.className = "entry-sub";3284      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3285      info.append(title, sub);3286      row.appendChild(info);32873288      const badge = document.createElement("span");3289      badge.className = "totp-badge";3290      badge.textContent = "Fill";3291      row.appendChild(badge);3292      row.addEventListener("click", () => choose(entry));3293      results.appendChild(row);3294    }3295  }32963297  function setFocused(index: number) {3298    focusedIndex = index;3299    container.querySelectorAll(".entry").forEach((el, i) => {3300      el.classList.toggle("focused", i === focusedIndex);3301      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3302    });3303  }33043305  function handleKeyDown(e: KeyboardEvent) {3306    if (e.key === "Escape" || e.key === "Tab") {3307      e.preventDefault();3308      dismiss(true);3309      return;3310    }3311    if (current.length === 0) return;3312    if (e.key === "Enter") {3313      e.preventDefault();3314      choose(current[Math.max(0, focusedIndex)]!);3315      return;3316    }3317    if (current.length === 1) return;3318    if (e.key === "ArrowDown") {3319      e.preventDefault();3320      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3321    } else if (e.key === "ArrowUp") {3322      e.preventDefault();3323      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3324    }3325  }33263327  let exitScheduled = false;3328  function dismiss(userAction = false) {3329    if (exitScheduled) return;3330    exitScheduled = true;3331    stopObserving();3332    document.removeEventListener("click", outsideClick, { capture: true });3333    document.removeEventListener("keydown", handleKeyDown);3334    if (userAction) options.onDismiss?.();3335    container.classList.add("is-exiting");3336    setTimeout(() => host.remove(), 130);3337  }33383339  function outsideClick(ev: MouseEvent) {3340    const path = ev.composedPath();3341    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3342  }33433344  document.addEventListener("keydown", handleKeyDown);3345  document.body.appendChild(host);3346  render();3347  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33483349  return dismiss;3350}33513352export interface CardSelectorEntry {3353  id: string;3354  title: string;3355  cardholderName?: string;3356  last4?: string;3357  expMonth?: string;3358  expYear?: string;3359  network?: import("../shared/types").CardNetwork;3360}33613362interface CardSelectorOptions {3363  domain?: string;3364  capability?: string;3365  /** Caller-provided fill — receives the full card payload from the SW. */3366  onFill: (entry: import("../shared/types").VaultEntry) => void;3367  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3368  onDismiss?: () => void;3369}33703371/**3372 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3373 * passkey create or get. Renders as a fixed-position floating popup (no3374 * field anchor needed — passkeys don't require a focused input). Uses the3375 * same theme tokens and entrance animation as all other inline popup states.3376 */3377export function showPasskeyProGate(): void {3378  const domain = location.hostname.replace(/^www\./, "");33793380  const host = document.createElement("div");3381  host.setAttribute("data-peach-passkey-gate", "1");3382  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3383  const shadow = host.attachShadow({ mode: "closed" });33843385  const style = document.createElement("style");3386  style.textContent = `3387    :host { all: initial; }3388    .gate-wrap {3389      position: fixed;3390      top: 50%;3391      left: 50%;3392      transform: translate(-50%, -50%);3393      width: 280px;3394      pointer-events: auto;3395      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3396    }3397    @keyframes g-in {3398      from { opacity:0; transform: translate(-50%,-52%); }3399      to   { opacity:1; transform: translate(-50%,-50%); }3400    }3401    .gate-wrap.is-exiting {3402      animation: g-out 130ms ease-in forwards;3403    }3404    @keyframes g-out {3405      to { opacity:0; transform: translate(-50%,-52%); }3406    }3407    .gate {3408      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3409      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3410      border-radius: 12px;3411      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3412      padding: 16px;3413      font-family: Inter, sans-serif;3414    }3415    .gate-header {3416      display: flex;3417      align-items: center;3418      gap: 7px;3419      margin-bottom: 12px;3420      padding-bottom: 10px;3421      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3422    }3423    .gate-domain {3424      font-size: 12px;3425      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3426      font-family: "IBM Plex Mono", monospace;3427      overflow: hidden;3428      text-overflow: ellipsis;3429      white-space: nowrap;3430    }3431    .gate-title {3432      font-size: 14px;3433      font-weight: 500;3434      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3435      margin-bottom: 6px;3436    }3437    .gate-subtitle {3438      font-size: 12px;3439      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3440      line-height: 1.5;3441      margin-bottom: 14px;3442    }3443    .gate-btn {3444      display: block;3445      width: 100%;3446      padding: 9px 0;3447      border-radius: 8px;3448      border: none;3449      cursor: pointer;3450      font-size: 13px;3451      font-family: Inter, sans-serif;3452      font-weight: 500;3453      transition: opacity 100ms;3454      margin-bottom: 7px;3455      text-align: center;3456    }3457    .gate-btn:last-child { margin-bottom: 0; }3458    .gate-btn--accent {3459      background: ${accentHex};3460      color: #fff;3461    }3462    .gate-btn--accent:hover { opacity: 0.88; }3463    .gate-btn--ghost {3464      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3465      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3466    }3467    .gate-btn--ghost:hover { opacity: 0.75; }3468    .backdrop {3469      position: fixed;3470      inset: 0;3471      pointer-events: auto;3472    }3473  `;3474  shadow.appendChild(style);34753476  const backdrop = document.createElement("div");3477  backdrop.className = "backdrop";3478  shadow.appendChild(backdrop);34793480  const wrap = document.createElement("div");3481  wrap.className = "gate-wrap";3482  shadow.appendChild(wrap);34833484  const gate = document.createElement("div");3485  gate.className = "gate";3486  wrap.appendChild(gate);34873488  // Header: peach icon + domain3489  const header = document.createElement("div");3490  header.className = "gate-header";3491  const icon = document.createElement("span");3492  icon.innerHTML = peachIconSvg();3493  const domainEl = document.createElement("span");3494  domainEl.className = "gate-domain";3495  domainEl.textContent = domain;3496  header.append(icon, domainEl);3497  gate.appendChild(header);34983499  const title = document.createElement("div");3500  title.className = "gate-title";3501  title.textContent = "Passkeys are part of Peach Pro.";3502  gate.appendChild(title);35033504  const subtitle = document.createElement("div");3505  subtitle.className = "gate-subtitle";3506  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3507  gate.appendChild(subtitle);35083509  const upgradeBtn = document.createElement("button");3510  upgradeBtn.className = "gate-btn gate-btn--accent";3511  upgradeBtn.type = "button";3512  upgradeBtn.textContent = "Upgrade to Pro";3513  gate.appendChild(upgradeBtn);35143515  const laterBtn = document.createElement("button");3516  laterBtn.className = "gate-btn gate-btn--ghost";3517  laterBtn.type = "button";3518  laterBtn.textContent = "Not right now";3519  gate.appendChild(laterBtn);35203521  function dismiss() {3522    wrap.classList.add("is-exiting");3523    setTimeout(() => host.remove(), 130);3524  }35253526  upgradeBtn.addEventListener("click", () => {3527    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3528    dismiss();3529  });3530  laterBtn.addEventListener("click", dismiss);3531  backdrop.addEventListener("click", dismiss);35323533  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3534    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3535  });35363537  document.body.appendChild(host);3538}35393540/**3541 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3542 * detector sees the page invoke navigator.credentials.create(); content/index.ts3543 * checks vault + decline state then calls this. "Save passkey to Peach"3544 * initiates the popup-context credential flow; "Not now" records a 30-day3545 * decline for the domain so we don't re-show on every page reload.3546 */3547export function showPasskeyRegistrationOffer(args: {3548  rpId: string;3549  rpName?: string;3550  userName?: string;3551  userDisplayName?: string;3552}): void {3553  const domain = location.hostname.replace(/^www\./, "");3554  const displayName = args.rpName || domain;35553556  const host = document.createElement("div");3557  host.setAttribute("data-peach-passkey-offer", "1");3558  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3559  const shadow = host.attachShadow({ mode: "closed" });35603561  const style = document.createElement("style");3562  style.textContent = `3563    :host { all: initial; }3564    .offer-wrap {3565      position: fixed;3566      top: 16px;3567      right: 16px;3568      width: 320px;3569      pointer-events: auto;3570      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3571    }3572    @keyframes o-in {3573      from { opacity: 0; transform: translateY(-6px); }3574      to   { opacity: 1; transform: translateY(0); }3575    }3576    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3577    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3578    .offer {3579      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3580      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3581      border-radius: 12px;3582      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3583      padding: 14px 14px 12px;3584      font-family: Inter, sans-serif;3585      position: relative;3586    }3587    .offer-close {3588      position: absolute;3589      top: 8px;3590      right: 8px;3591      width: 18px;3592      height: 18px;3593      border: none;3594      background: transparent;3595      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3596      cursor: pointer;3597      font-size: 14px;3598      line-height: 1;3599      padding: 0;3600    }3601    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3602    .offer-header {3603      display: flex;3604      align-items: center;3605      gap: 7px;3606      margin-bottom: 8px;3607      padding-bottom: 8px;3608      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3609    }3610    .offer-domain {3611      font-size: 12px;3612      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3613      font-family: "IBM Plex Mono", monospace;3614      overflow: hidden;3615      text-overflow: ellipsis;3616      white-space: nowrap;3617    }3618    .offer-title {3619      font-size: 13px;3620      font-weight: 500;3621      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3622      margin-bottom: 4px;3623    }3624    .offer-subtitle {3625      font-size: 11px;3626      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3627      line-height: 1.45;3628      margin-bottom: 12px;3629    }3630    .offer-btn {3631      display: block;3632      width: 100%;3633      padding: 8px 0;3634      border-radius: 7px;3635      border: none;3636      cursor: pointer;3637      font-size: 12px;3638      font-family: Inter, sans-serif;3639      font-weight: 500;3640      transition: opacity 100ms;3641      margin-bottom: 6px;3642      text-align: center;3643    }3644    .offer-btn:last-child { margin-bottom: 0; }3645    .offer-btn--accent { background: ${accentHex}; color: #fff; }3646    .offer-btn--accent:hover { opacity: 0.88; }3647    .offer-btn--ghost {3648      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3649      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3650    }3651    .offer-btn--ghost:hover { opacity: 0.75; }3652  `;3653  shadow.appendChild(style);36543655  const wrap = document.createElement("div");3656  wrap.className = "offer-wrap";3657  shadow.appendChild(wrap);36583659  const offer = document.createElement("div");3660  offer.className = "offer";3661  wrap.appendChild(offer);36623663  const closeBtn = document.createElement("button");3664  closeBtn.className = "offer-close";3665  closeBtn.type = "button";3666  closeBtn.setAttribute("aria-label", "Dismiss");3667  closeBtn.textContent = "✕";3668  offer.appendChild(closeBtn);36693670  const header = document.createElement("div");3671  header.className = "offer-header";3672  const icon = document.createElement("span");3673  icon.innerHTML = peachIconSvg();3674  const domainEl = document.createElement("span");3675  domainEl.className = "offer-domain";3676  domainEl.textContent = domain;3677  header.append(icon, domainEl);3678  offer.appendChild(header);36793680  const title = document.createElement("div");3681  title.className = "offer-title";3682  title.textContent = "This site supports passkeys.";3683  offer.appendChild(title);36843685  const subtitle = document.createElement("div");3686  subtitle.className = "offer-subtitle";3687  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3688  offer.appendChild(subtitle);36893690  const saveBtn = document.createElement("button");3691  saveBtn.className = "offer-btn offer-btn--accent";3692  saveBtn.type = "button";3693  saveBtn.textContent = "Save passkey to Peach";3694  offer.appendChild(saveBtn);36953696  const laterBtn = document.createElement("button");3697  laterBtn.className = "offer-btn offer-btn--ghost";3698  laterBtn.type = "button";3699  laterBtn.textContent = "Not now";3700  offer.appendChild(laterBtn);37013702  function dismiss(decline: boolean) {3703    if (decline) {3704      chrome.runtime.sendMessage({3705        type: "PASSKEY_OFFER_DECLINE",3706        payload: { domain },3707      }).catch(() => {});3708    }3709    wrap.classList.add("is-exiting");3710    setTimeout(() => host.remove(), 130);3711  }37123713  saveBtn.addEventListener("click", () => {3714    chrome.runtime.sendMessage({3715      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3716      payload: {3717        rpId: args.rpId,3718        rpName: args.rpName ?? displayName,3719        userName: args.userName ?? "user",3720        userDisplayName: args.userDisplayName,3721      },3722    }).catch(() => {});3723    dismiss(false);3724  });3725  laterBtn.addEventListener("click", () => dismiss(true));3726  closeBtn.addEventListener("click", () => dismiss(true));37273728  document.body.appendChild(host);3729}37303731/**3732 * State 11 — passkey available indicator. Shown when the user lands on a3733 * domain for which they already have a stored passkey. Tells them where to3734 * find it (the entry already shows in the vault list); the "Sign in with3735 * passkey" button opens the popup so they can use the platform authenticator3736 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3737 * the actual sign-in transparently, so this banner is informational only.3738 */3739export function showPasskeyAvailable(args: {3740  rpId: string;3741  userName: string;3742  fromBrowser?: "chrome" | "firefox";3743  currentBrowser?: "chrome" | "firefox" | "unknown";3744}): void {3745  const domain = location.hostname.replace(/^www\./, "");3746  const crossBrowser =3747    args.fromBrowser &&3748    args.currentBrowser &&3749    args.currentBrowser !== "unknown" &&3750    args.fromBrowser !== args.currentBrowser;37513752  const host = document.createElement("div");3753  host.setAttribute("data-peach-passkey-available", "1");3754  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3755  const shadow = host.attachShadow({ mode: "closed" });37563757  const style = document.createElement("style");3758  style.textContent = `3759    :host { all: initial; }3760    .avail-wrap {3761      position: fixed;3762      top: 16px;3763      right: 16px;3764      width: 320px;3765      pointer-events: auto;3766      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3767    }3768    @keyframes a-in {3769      from { opacity: 0; transform: translateY(-6px); }3770      to   { opacity: 1; transform: translateY(0); }3771    }3772    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3773    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3774    .avail {3775      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3776      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3777      border-radius: 12px;3778      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3779      padding: 14px 14px 12px;3780      font-family: Inter, sans-serif;3781      position: relative;3782    }3783    .avail-close {3784      position: absolute;3785      top: 8px;3786      right: 8px;3787      width: 18px;3788      height: 18px;3789      border: none;3790      background: transparent;3791      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3792      cursor: pointer;3793      font-size: 14px;3794      line-height: 1;3795      padding: 0;3796    }3797    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3798    .avail-header {3799      display: flex;3800      align-items: center;3801      gap: 7px;3802      margin-bottom: 8px;3803      padding-bottom: 8px;3804      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3805    }3806    .avail-domain {3807      font-size: 12px;3808      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3809      font-family: "IBM Plex Mono", monospace;3810    }3811    .avail-label {3812      font-size: 9px;3813      letter-spacing: 0.16em;3814      text-transform: uppercase;3815      color: ${accentHex};3816      margin-bottom: 4px;3817    }3818    .avail-user {3819      font-size: 13px;3820      font-weight: 500;3821      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3822      margin-bottom: 12px;3823      overflow: hidden;3824      text-overflow: ellipsis;3825      white-space: nowrap;3826    }3827    .avail-cross {3828      font-size: 11px;3829      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3830      line-height: 1.45;3831      margin-bottom: 12px;3832      padding: 8px;3833      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3834      border-radius: 6px;3835    }3836    .avail-btn {3837      display: block;3838      width: 100%;3839      padding: 8px 0;3840      border-radius: 7px;3841      border: none;3842      cursor: pointer;3843      font-size: 12px;3844      font-family: Inter, sans-serif;3845      font-weight: 500;3846      transition: opacity 100ms;3847      margin-bottom: 6px;3848      text-align: center;3849    }3850    .avail-btn:last-child { margin-bottom: 0; }3851    .avail-btn--accent { background: ${accentHex}; color: #fff; }3852    .avail-btn--accent:hover { opacity: 0.88; }3853    .avail-btn--ghost {3854      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3855      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3856    }3857    .avail-btn--ghost:hover { opacity: 0.75; }3858  `;3859  shadow.appendChild(style);38603861  const wrap = document.createElement("div");3862  wrap.className = "avail-wrap";3863  shadow.appendChild(wrap);38643865  const avail = document.createElement("div");3866  avail.className = "avail";3867  wrap.appendChild(avail);38683869  const closeBtn = document.createElement("button");3870  closeBtn.className = "avail-close";3871  closeBtn.type = "button";3872  closeBtn.setAttribute("aria-label", "Dismiss");3873  closeBtn.textContent = "✕";3874  avail.appendChild(closeBtn);38753876  const header = document.createElement("div");3877  header.className = "avail-header";3878  const icon = document.createElement("span");3879  icon.innerHTML = peachIconSvg();3880  const domainEl = document.createElement("span");3881  domainEl.className = "avail-domain";3882  domainEl.textContent = domain;3883  header.append(icon, domainEl);3884  avail.appendChild(header);38853886  const label = document.createElement("div");3887  label.className = "avail-label";3888  label.textContent = "PASSKEY";3889  avail.appendChild(label);38903891  const user = document.createElement("div");3892  user.className = "avail-user";3893  user.textContent = args.userName;3894  avail.appendChild(user);38953896  if (crossBrowser) {3897    const cross = document.createElement("div");3898    cross.className = "avail-cross";3899    cross.textContent =3900      args.fromBrowser === "chrome"3901        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3902        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3903    avail.appendChild(cross);3904  }39053906  const signInBtn = document.createElement("button");3907  signInBtn.className = "avail-btn avail-btn--accent";3908  signInBtn.type = "button";3909  signInBtn.textContent = "Sign in with passkey";3910  avail.appendChild(signInBtn);39113912  const passwordBtn = document.createElement("button");3913  passwordBtn.className = "avail-btn avail-btn--ghost";3914  passwordBtn.type = "button";3915  passwordBtn.textContent = "Use password instead";3916  avail.appendChild(passwordBtn);39173918  function dismiss() {3919    wrap.classList.add("is-exiting");3920    setTimeout(() => host.remove(), 130);3921  }39223923  signInBtn.addEventListener("click", () => {3924    // On Chrome: the user clicking the page's own Sign-in button is what3925    //   triggers webAuthenticationProxy → existing background flow handles it.3926    //   Our button just dismisses since the page itself drives auth.3927    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3928    //   and surface the entry for manual reference (popup view).3929    dismiss();3930    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3931  });3932  passwordBtn.addEventListener("click", dismiss);3933  closeBtn.addEventListener("click", dismiss);39343935  document.body.appendChild(host);3936}39373938/**3939 * State 7 — card silver platter. Single-card focused fill view rendered3940 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3941 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3942 * so card and login flows render identically. Multi-card list view is a3943 * follow-up; today this picks the first card.3944 */3945export function showCardSelector(3946  anchorEl: HTMLInputElement,3947  cards: CardSelectorEntry[],3948  options: CardSelectorOptions3949): () => void {3950  if (cards.length === 0) return () => {};3951  const card = cards[0]!;3952  let capabilityActionClaimed = false;3953  const claimCapabilityAction = () => {3954    if (!options.capability) return true;3955    if (capabilityActionClaimed) return false;3956    capabilityActionClaimed = true;3957    return true;3958  };39593960  const host = document.createElement("div");3961  host.style.cssText = "position: absolute; z-index: 2147483647;";3962  host.style.setProperty("--peach-accent", accentHex);3963  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3964  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3965  const shadow = host.attachShadow({ mode: "closed" });39663967  const style = shadow.appendChild(document.createElement("style"));3968  style.textContent = SELECTOR_STYLES;39693970  const rect = anchorEl.getBoundingClientRect();3971  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3972  host.style.left = `${rect.left + window.scrollX}px`;3973  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;39743975  const container = shadow.appendChild(document.createElement("div"));3976  container.className = "peach-inline-popup";3977  container.setAttribute("data-theme", popupTheme);39783979  // Domain header — eyebrow communicates the card context, not the site3980  const domHdr = document.createElement("div");3981  domHdr.className = "domain-header";3982  const eyebrow = document.createElement("div");3983  eyebrow.className = "domain-eyebrow";3984  eyebrow.textContent = "Pay with Peach";3985  const domName = document.createElement("div");3986  domName.className = "domain-name";3987  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3988  domHdr.append(eyebrow, domName);3989  container.appendChild(domHdr);39903991  const platter = document.createElement("div");3992  platter.className = "card-platter";39933994  if (card.network && card.network !== "unknown") {3995    const net = document.createElement("div");3996    net.className = "cp-network";3997    net.textContent = card.network;3998    platter.appendChild(net);3999  }40004001  const nick = document.createElement("div");4002  nick.className = "cp-nickname";4003  nick.textContent = card.title;4004  platter.appendChild(nick);40054006  if (card.last4) {4007    const l4 = document.createElement("div");4008    l4.className = "cp-last4";4009    l4.textContent = `•••• ${card.last4}`;4010    platter.appendChild(l4);4011  }40124013  const meta = document.createElement("div");4014  meta.className = "cp-meta";4015  if (card.cardholderName) {4016    const name = document.createElement("span");4017    name.textContent = card.cardholderName;4018    meta.appendChild(name);4019  }4020  if (card.expMonth && card.expYear) {4021    if (card.cardholderName) {4022      const sep = document.createElement("span");4023      sep.className = "cp-meta-sep";4024      sep.textContent = "·";4025      meta.appendChild(sep);4026    }4027    const exp = document.createElement("span");4028    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4029    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4030    meta.appendChild(exp);4031  }4032  if (meta.childElementCount > 0) platter.appendChild(meta);40334034  const fillWrap = document.createElement("div");4035  fillWrap.className = "cp-fill-wrap";4036  const fillBtn = document.createElement("button");4037  fillBtn.className = "sp-fill-btn";4038  fillBtn.type = "button";4039  fillBtn.textContent = "Fill card details";4040  fillBtn.addEventListener("click", async () => {4041    if (fillBtn.disabled || !claimCapabilityAction()) return;4042    fillBtn.disabled = true;4043    fillBtn.classList.add("filled");4044    fillBtn.innerHTML = checkSvgStr();4045    const resp = await chrome.runtime.sendMessage({4046      type: "GET_ENTRY_FOR_FILL",4047      // MV-1: explicit user click to fill this card's details.4048      payload: { id: card.id, capability: options.capability },4049    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4050    if (resp?.ok && resp.data) options.onFill(resp.data);4051    setTimeout(() => dismiss(), 400);4052  });4053  fillWrap.appendChild(fillBtn);4054  platter.appendChild(fillWrap);40554056  // Secondary actions — copy number, copy CVC, dismiss4057  const actions = document.createElement("div");4058  actions.className = "sp-actions";40594060  function flashBtn(b: HTMLButtonElement) {4061    b.classList.add("flashed");4062    setTimeout(() => b.classList.remove("flashed"), 700);4063  }40644065  // M3/QUA-005: clipboard + background COPY both failed — show user.4066  function flashCopyError(b: HTMLButtonElement) {4067    const original = b.textContent ?? "";4068    b.textContent = "Blocked";4069    b.classList.add("flashed");4070    setTimeout(() => {4071      b.classList.remove("flashed");4072      if (b.isConnected) b.textContent = original;4073    }, 1200);4074  }40754076  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4077    if (!claimCapabilityAction()) return null;4078    const resp = await chrome.runtime.sendMessage({4079      type: "GET_ENTRY_FOR_FILL",4080      // MV-1: explicit user action on a card the user opened in Peach's UI.4081      payload: { id: card.id, capability: options.capability },4082    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4083    const full = resp?.ok && resp.data ? resp.data : null;4084    if (options.capability) dismiss();4085    return full;4086  }40874088  const copyNum = document.createElement("button");4089  copyNum.className = "sp-action-btn";4090  copyNum.type = "button";4091  copyNum.title = "Copy card number";4092  copyNum.textContent = "Copy number";4093  copyNum.addEventListener("click", async (e) => {4094    e.stopPropagation();4095    const full = await fetchFullCard();4096    if (!full?.cardNumber) return;4097    let alreadyWritten = false;4098    try {4099      await navigator.clipboard.writeText(full.cardNumber);4100      alreadyWritten = true;4101    } catch (err) {4102      console.warn("[Peach] clipboard write denied:", err);4103    }4104    const resp = await chrome.runtime.sendMessage({4105      type: "COPY",4106      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4107    }).catch(() => null) as { ok?: boolean } | null;4108    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4109    else flashCopyError(copyNum);4110  });4111  actions.appendChild(copyNum);41124113  const copyCvc = document.createElement("button");4114  copyCvc.className = "sp-action-btn";4115  copyCvc.type = "button";4116  copyCvc.title = "Copy CVC";4117  copyCvc.textContent = "Copy CVC";4118  copyCvc.addEventListener("click", async (e) => {4119    e.stopPropagation();4120    const full = await fetchFullCard();4121    if (!full?.cvc) return;4122    let alreadyWritten = false;4123    try {4124      await navigator.clipboard.writeText(full.cvc);4125      alreadyWritten = true;4126    } catch (err) {4127      console.warn("[Peach] clipboard write denied:", err);4128    }4129    const resp = await chrome.runtime.sendMessage({4130      type: "COPY",4131      payload: { text: full.cvc, label: "CVC", alreadyWritten },4132    }).catch(() => null) as { ok?: boolean } | null;4133    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4134    else flashCopyError(copyCvc);4135  });4136  actions.appendChild(copyCvc);41374138  const closeBtn = document.createElement("button");4139  closeBtn.className = "sp-action-btn";4140  closeBtn.type = "button";4141  closeBtn.title = "Dismiss";4142  closeBtn.textContent = "✕";4143  closeBtn.addEventListener("click", (e) => {4144    e.stopPropagation();4145    dismiss(true);4146  });4147  actions.appendChild(closeBtn);41484149  platter.appendChild(actions);4150  container.appendChild(platter);41514152  document.body.appendChild(host);4153  function updatePosition() {4154    const r = anchorEl.getBoundingClientRect();4155    host.style.top = `${r.bottom + window.scrollY + 5}px`;4156    host.style.left = `${r.left + window.scrollX}px`;4157  }4158  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);41594160  function onKeyDown(e: KeyboardEvent) {4161    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4162  }4163  document.addEventListener("keydown", onKeyDown);41644165  let exitScheduled = false;4166  function dismiss(userAction = false) {4167    if (exitScheduled) return;4168    exitScheduled = true;4169    stopObserving();4170    document.removeEventListener("click", outsideClick, { capture: true });4171    document.removeEventListener("keydown", onKeyDown);4172    if (userAction) options.onDismiss?.();4173    container.classList.add("is-exiting");4174    setTimeout(() => host.remove(), 130);4175  }41764177  function outsideClick(ev: MouseEvent) {4178    const path = ev.composedPath();4179    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4180  }4181  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);41824183  return dismiss;4184}