inject.ts

158.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  searchableEntries?: SelectorEntry[];56  /** True when shown on a signup form — changes header label and entry-click behaviour */57  isSignup?: boolean;58  /**59   * Identity kind the current signup field is expecting. Used to avoid60   * assuming email when the user is actually filling a username.61   */62  identityKind?: IdentityKind;63  /**64   * Derived identity list (emails then usernames) for signup mode (State 10).65   * When present, renderIdentityHelper() is used instead of renderList().66   */67  savedIdentities?: SavedIdentity[];68  /**69   * Called after the user picks a saved identity (signup mode only) or70   * after successfully saving a new entry on a signup form.71   * Lets the caller fill the visible username + password fields.72   */73  onFillFields?: (username: string, password: string) => void;74  /**75   * When true, show an inline unlock form instead of the entries list.76   * Used when the vault is locked so the user can unlock without opening77   * the popup.78   */79  locked?: boolean;80  /**81   * Called after a successful inline unlock — the caller should re-query82   * entries and re-open the selector with real data.83   */84  onUnlocked?: () => void;85  /**86   * Called when the user explicitly dismisses the selector (Escape, Tab, or87   * click outside) — NOT when an entry is selected or on auto-close.88   * Used by the caller to suppress spurious reopens on the same field.89   */90  onDismiss?: () => void;91}9293function getDomainFromUrl(url: string): string {94  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }95}9697function keySvgStr(): string {98  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>`;99}100101function plusSvgStr(): string {102  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>`;103}104105function searchSvgStr(): string {106  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>`;107}108109function backSvgStr(): string {110  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>`;111}112113function peachIconSvg(): string {114  // Peach body stays brand-peach regardless of `accentHex` — a sage or115  // sky accent must not turn the autofill icon green or blue. Accent116  // color still tints surrounding glow/hover halos below.117  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>`;118}119120function checkSvgStr(): string {121  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>`;122}123124function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {125  const { hostname, origin } = location;126  const parts = hostname.split(".");127  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",128    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",129    "oidc", "federation", "saml", "cas", "ldap"];130  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());131  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;132  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);133  return { origin, title, loginSubdomain };134}135136/**137 * Shows a bottom-of-page toast after filling credentials when the entry has138 * never matched the current site — offering to add the current origin to the139 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.140 */141export function showRememberSiteToast(142  pageDomain: string,143  entryId: string,144): void {145  const host = document.createElement("div");146  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";147  host.style.setProperty("--peach-accent", accentHex);148  const shadow = host.attachShadow({ mode: "closed" });149150  const style = document.createElement("style");151  style.textContent = `152    .bar {153      display:flex;align-items:center;gap:10px;padding:10px 14px;154      background:#131109;border:1px solid rgba(240,232,216,0.09);155      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);156      font-family:Inter,sans-serif;white-space:nowrap;157      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;158    }159    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }160    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }161    .yes {162      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;163      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;164    }165    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }166    .no {167      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;168      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;169    }170  `;171  shadow.appendChild(style);172173  const bar = document.createElement("div"); bar.className = "bar";174  const txt = document.createElement("span"); txt.className = "txt";175  txt.textContent = `Remember ${pageDomain} for this entry?`;176  const yesBtn = document.createElement("button"); yesBtn.className = "yes";177  yesBtn.textContent = "Remember";178  yesBtn.addEventListener("click", async () => {179    await chrome.runtime.sendMessage({180      type: "ADD_ADDITIONAL_URL",181      payload: { id: entryId, url: location.origin },182    });183    host.remove();184  });185  const noBtn = document.createElement("button"); noBtn.className = "no";186  noBtn.textContent = "Not now";187  noBtn.addEventListener("click", () => host.remove());188  bar.append(txt, yesBtn, noBtn);189  shadow.appendChild(bar);190  document.body.appendChild(host);191  setTimeout(() => host.remove(), 9000);192}193194interface SmartGenerator {195  root: HTMLElement;196  getPassword: () => string;197  /** Copy the current password to the clipboard with the standard pulse UX. */198  copy: () => Promise<void>;199}200201interface SmartGeneratorOptions {202  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */203  policy: PasswordPolicy;204  /**205   * Seed value: used as the displayed password without regenerating, e.g. the206   * password the user already typed into the page. The generator still207   * regenerates the moment any control changes.208   */209  initialPassword?: string;210  /** Fires every time the password regenerates (initial + on changes). */211  onChange?: (pw: string) => void;212}213214/**215 * Build the inline-popup smart-password generator. Mirrors the main popup's216 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset217 * pills + a policy hint that names the constraints Peach detected on the218 * page. Writing this in pure DOM rather than reusing the Solid component219 * keeps the content-script bundle small.220 */221function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {222  const policy = opts.policy ?? {};223224  // Start at site max (strongest password the site accepts), fall back to 64225  let length = policy.maxLength ?? 64;226  if (policy.minLength) length = Math.max(length, policy.minLength);227  if (length < 8) length = 8;228  if (length > 128) length = 128;229230  let upper = true;231  let lower = true;232  let numbers = true;233  let symbols = !policy.forbidsSymbols;234  if (policy.requiresSymbols) symbols = true;235  const forbiddenChars = policy.forbiddenChars ?? "";236237  let password = "";238239  const root = document.createElement("div");240  root.className = "pwgen-block";241242  const displayRow = root.appendChild(document.createElement("div"));243  displayRow.className = "pwgen-display-row";244  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;245  output.type = "text";246  output.className = "pwgen-output";247  output.setAttribute("autocomplete", "off");248  output.setAttribute("spellcheck", "false");249  output.setAttribute("autocorrect", "off");250  output.setAttribute("autocapitalize", "off");251252  const regenBtn = displayRow.appendChild(document.createElement("button"));253  regenBtn.className = "pwgen-icon-btn";254  regenBtn.type = "button";255  regenBtn.setAttribute("aria-label", "Regenerate password");256  regenBtn.title = "Regenerate";257  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>`;258259  const copyBtn = displayRow.appendChild(document.createElement("button"));260  copyBtn.className = "pwgen-icon-btn";261  copyBtn.type = "button";262  copyBtn.setAttribute("aria-label", "Copy password");263  copyBtn.title = "Copy";264  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>`;265266  const controls = root.appendChild(document.createElement("div"));267  controls.className = "pwgen-controls-row";268  const slider = controls.appendChild(document.createElement("input"));269  slider.type = "range";270  slider.className = "pwgen-slider";271  slider.min = "8";272  slider.max = "128";273  slider.value = String(length);274  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));275  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));276  const lenNum = controls.appendChild(document.createElement("span"));277  lenNum.className = "pwgen-len-num pwgen-len-num--edit";278  lenNum.textContent = String(length);279  lenNum.addEventListener("click", () => {280    const li = document.createElement("input");281    li.type = "text"; li.inputMode = "numeric";282    li.className = "pwgen-len-input"; li.value = String(length);283    lenNum.replaceWith(li);284    requestAnimationFrame(() => li.select());285    function commitLenEdit() {286      const n = parseInt(li.value, 10);287      if (!isNaN(n)) {288        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));289        slider.value = String(length);290        regenerate();291      }292      lenNum.textContent = String(length);293      li.replaceWith(lenNum);294    }295    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });296    li.addEventListener("blur", commitLenEdit);297  });298299  const pills = root.appendChild(document.createElement("div"));300  pills.className = "pwgen-pills";301302  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {303    const b = document.createElement("button");304    b.type = "button";305    b.className = `pwgen-pill ${on ? "is-on" : ""}`;306    b.textContent = label;307    b.addEventListener("click", () => {308      const next = !b.classList.contains("is-on");309      b.classList.toggle("is-on", next);310      onToggle(next);311    });312    return b;313  }314  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));315  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));316  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));317  pills.appendChild(makePill("!@#", symbols, (next) => {318    // The site forbids symbols — UI lets the user override but still warn.319    symbols = next;320    regenerate();321  }));322323  // Policy hint — surfaces what Peach read off the site so the user knows the324  // generator is already tuned to it. Only shows when something interesting325  // was detected.326  const hintParts: string[] = [];327  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);328  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);329  if (policy.requiresSymbols) hintParts.push("requires symbols");330  if (policy.forbidsSymbols) hintParts.push("no symbols");331  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);332  if (hintParts.length > 0) {333    const hint = root.appendChild(document.createElement("div"));334    hint.className = "pwgen-policy-hint";335    const accent = document.createElement("span");336    accent.className = "pwgen-hint-accent";337    accent.textContent = "site rules · ";338    const text = document.createTextNode(hintParts.join(" · "));339    hint.appendChild(accent);340    hint.appendChild(text);341  }342343  function regenerate() {344    // Falls back gracefully when the user toggles every charset off — the345    // shared generator forces lowercase in that case rather than throwing.346    password = generatePassword({347      length,348      includeUppercase: upper,349      includeLowercase: lower,350      includeNumbers: numbers,351      includeSymbols: symbols,352      forbiddenChars,353    });354    output.value = password;355    opts.onChange?.(password);356  }357358  output.addEventListener("input", () => {359    password = output.value;360    length = password.length;361    slider.value = String(Math.max(8, Math.min(128, length)));362    lenNum.textContent = String(length);363    opts.onChange?.(password);364  });365366  slider.addEventListener("input", () => {367    length = parseInt(slider.value, 10);368    lenNum.textContent = String(length);369    regenerate();370  });371  regenBtn.addEventListener("click", regenerate);372373  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;374  async function copy(): Promise<void> {375    try {376      await navigator.clipboard.writeText(password);377      copyBtn.classList.add("is-copied");378      if (copyResetTimer) clearTimeout(copyResetTimer);379      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);380    } catch {381      // Clipboard API may be denied — silently no-op; user still has regen UI.382    }383  }384  copyBtn.addEventListener("click", () => { void copy(); });385386  if (opts.initialPassword) {387    password = opts.initialPassword;388    output.value = password;389    opts.onChange?.(password);390  } else {391    regenerate();392  }393394  return {395    root,396    getPassword: () => password,397    copy,398  };399}400401export function observeAnchorPosition(402  anchorEl: HTMLElement,403  onUpdate: () => void404): () => void {405  let rafId = 0;406  let burstUntil = 0;407408  const runUpdate = () => {409    rafId = 0;410    onUpdate();411    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);412  };413  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };414  const scheduleBurst = (ms = 220) => {415    burstUntil = Math.max(burstUntil, performance.now() + ms);416    scheduleUpdate();417  };418419  const resizeObserver = new ResizeObserver(() => scheduleBurst());420  resizeObserver.observe(anchorEl);421  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);422423  const mutationObserver = new MutationObserver(() => scheduleBurst());424  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });425  if (anchorEl.parentElement) {426    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });427  }428429  const onScroll = () => scheduleUpdate();430  window.addEventListener("scroll", onScroll, true);431  window.addEventListener("resize", onScroll);432  window.visualViewport?.addEventListener("resize", onScroll);433  window.visualViewport?.addEventListener("scroll", onScroll);434  anchorEl.addEventListener("focus", () => scheduleBurst());435  anchorEl.addEventListener("input", () => scheduleBurst());436437  scheduleBurst(260);438439  return () => {440    if (rafId) cancelAnimationFrame(rafId);441    resizeObserver.disconnect();442    mutationObserver.disconnect();443    window.removeEventListener("scroll", onScroll, true);444    window.removeEventListener("resize", onScroll);445    window.visualViewport?.removeEventListener("resize", onScroll);446    window.visualViewport?.removeEventListener("scroll", onScroll);447  };448}449450export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {451  const button = document.createElement("button");452  button.type = "button";453  button.setAttribute("aria-label", "Peach autofill");454  button.title = "Fill with Peach";455  button.innerHTML = peachIconSvg();456  // position: fixed is load-bearing — not absolute. Absolute positioning457  // inherits the nearest positioned ancestor's box, which on sites with458  // overflow:hidden or sticky parents clips or offsets the icon. Fixed459  // anchors to the viewport and escapes all parent layout.460  button.style.cssText = `461    position: fixed; z-index: 2147483646;462    width: 26px; height: 26px; cursor: pointer;463    pointer-events: auto; border: none; padding: 3px;464    display: inline-flex; align-items: center; justify-content: center;465    background: transparent; border-radius: 999px;466    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;467    opacity: 0;468  `;469  button.addEventListener("mouseenter", () => {470    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;471    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;472    button.style.transform = "scale(1.08)";473  });474  button.addEventListener("mouseleave", () => {475    button.style.background = "transparent";476    button.style.boxShadow = "none";477    button.style.transform = "none";478  });479  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });480  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });481482  document.body.appendChild(button);483484  function updatePosition() {485    const rect = field.getBoundingClientRect();486    if (rect.width === 0 || rect.height === 0) {487      button.style.opacity = "0"; button.style.pointerEvents = "none";488      return;489    }490    const sz = 26;491    const inset = Math.max(5, Math.min(10, rect.height * 0.22));492    const top = rect.top + rect.height / 2 - sz / 2;493    // Clamp left so the icon stays fully inside the field's right edge, never494    // spilling onto an adjacent sibling button.495    const minLeft = rect.left + 4;496    const left = Math.max(minLeft, rect.right - sz - inset);497    // Hide if the field is too narrow to fit the icon cleanly (< 40px)498    if (rect.width < 40) {499      button.style.opacity = "0"; button.style.pointerEvents = "none";500      return;501    }502    button.style.top = `${top}px`;503    button.style.left = `${left}px`;504    button.style.opacity = "1"; button.style.pointerEvents = "auto";505  }506  updatePosition();507  requestAnimationFrame(() => { button.style.opacity = "1"; });508  const stopObserving = observeAnchorPosition(field, updatePosition);509  return () => { stopObserving(); button.remove(); };510}511512// All theme-dependent values resolve through tokens scoped to513// .peach-inline-popup[data-theme="dark|light"]. Accent variables514// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)515// are identical in both themes — only surface tokens differ. See516// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the517// theme switch — only literal brand-peach in peachIconSvg may stay raw.518const SELECTOR_STYLES = `519  :host { all: initial; }520  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }521522  .peach-inline-popup[data-theme="dark"] {523    --peach-bg:           #1a1410;524    --peach-bg-card:      #221c16;525    --peach-text:         #f5f0ea;526    --peach-text-dim:     #8a7a6a;527    --peach-text-muted:   #4a3a2a;528    --peach-border:       rgba(255,255,255,0.07);529    --peach-input-bg:     rgba(255,255,255,0.05);530    --peach-input-border: rgba(255,255,255,0.08);531  }532  .peach-inline-popup[data-theme="light"] {533    --peach-bg:           #fdf8f4;534    --peach-bg-card:      #f5ede4;535    --peach-text:         #1c1310;536    --peach-text-dim:     #6b5a4a;537    --peach-text-muted:   #a89080;538    --peach-border:       rgba(0,0,0,0.08);539    --peach-input-bg:     rgba(0,0,0,0.04);540    --peach-input-border: rgba(0,0,0,0.10);541  }542543  .peach-inline-popup {544    background: var(--peach-bg);545    border: 1px solid var(--peach-border-accent, var(--peach-border));546    border-radius: 14px;547    overflow: hidden;548    box-shadow:549      0 8px 40px var(--peach-glow, transparent),550      0 2px 12px rgba(0,0,0,0.5);551    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;552    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;553    transition: height 220ms cubic-bezier(0.16,1,0.3,1);554  }555  /* Light theme: shadow against a light page is too strong otherwise — drop both556     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */557  .peach-inline-popup[data-theme="light"] {558    box-shadow:559      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),560      0 2px 12px rgba(0,0,0,0.12);561  }562  .peach-inline-popup.is-exiting {563    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;564    pointer-events: none;565  }566567  @keyframes peach-enter {568    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }569    65%  { opacity: 1; filter: blur(0); }570    100% { opacity: 1; transform: translateY(0) scale(1); }571  }572  @keyframes peach-exit {573    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }574    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }575  }576  @keyframes peach-slide-in {577    from { opacity: 0; transform: translateX(12px); }578    to   { opacity: 1; transform: translateX(0); }579  }580  @keyframes peach-slide-back {581    from { opacity: 0; transform: translateX(-12px); }582    to   { opacity: 1; transform: translateX(0); }583  }584  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }585  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }586587  /* Domain header */588  .domain-header {589    padding: 9px 13px 7px;590    border-bottom: 1px solid var(--peach-border);591    display: flex; align-items: center; justify-content: space-between;592    gap: 8px;593  }594  .domain-header-text {595    display: flex; flex-direction: column; gap: 2px;596    min-width: 0; flex: 1;597  }598  .domain-eyebrow {599    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;600    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;601  }602  .domain-name {603    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);604    font-family: "IBM Plex Mono", monospace;605    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;606  }607  .domain-header-actions {608    display: inline-flex; align-items: center; gap: 5px;609    flex-shrink: 0;610  }611  .domain-add-btn,612  .domain-search-btn {613    flex-shrink: 0;614    width: 22px; height: 22px;615    display: inline-flex; align-items: center; justify-content: center;616    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);617    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);618    border-radius: 6px;619    color: var(--peach-accent);620    cursor: pointer; padding: 0;621    transition: background 120ms, border-color 120ms, transform 80ms;622    font-family: "IBM Plex Mono", monospace;623    font-size: 14px; line-height: 1;624  }625  .domain-add-btn:hover,626  .domain-search-btn:hover {627    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);628    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);629    transform: scale(1.06);630  }631  .domain-add-btn:active,632  .domain-search-btn:active { transform: scale(0.96); }633634  /* Search */635  .search-wrap {636    padding: 9px 12px 7px;637    border-bottom: 1px solid var(--peach-border);638  }639  .search {640    width: 100%; background: var(--peach-input-bg);641    border: 1px solid var(--peach-input-border);642    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;643    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;644    transition: border-color 120ms, box-shadow 120ms;645  }646  .search:focus {647    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);648    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);649  }650  .search::placeholder { color: var(--peach-text-muted); }651652  /* Results */653  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }654  .results::-webkit-scrollbar { display: none; }655656  /* Entry rows */657  .entry {658    display: flex; align-items: center; padding: 8px 12px;659    cursor: pointer; border-bottom: 1px solid var(--peach-border);660    transition: background 70ms; position: relative; outline: none;661  }662  .entry:last-child { border-bottom: none; }663  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }664  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }665  .entry.focused::before {666    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;667    width: 2px; border-radius: 2px;668    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);669  }670671  .entry-icon {672    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;673    background: var(--peach-input-bg); border: 1px solid var(--peach-border);674    display: flex; align-items: center; justify-content: center;675    overflow: hidden; margin-right: 10px;676  }677  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }678  .entry-icon.is-new {679    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);680    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);681    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);682  }683684  .entry-info { flex: 1; min-width: 0; }685  .entry-title {686    font-size: 12.5px; color: var(--peach-text);687    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;688    line-height: 1.3;689  }690  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }691  .entry-sub {692    font-size: 10px; color: var(--peach-text-dim);693    font-family: "IBM Plex Mono", monospace;694    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;695    margin-top: 1px;696  }697698  .totp-badge {699    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;700    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);701    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);702    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;703  }704  .passkey-badge {705    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;706    border-radius: 4px;707    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);708    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);709    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);710    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;711  }712713  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }714715  .empty-hint {716    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);717    font-family: "IBM Plex Mono", monospace;718  }719720  /* Create form */721  .create-form-wrap {722    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;723  }724  .create-head {725    display: flex; align-items: center; gap: 8px;726    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);727  }728  .back-btn {729    background: transparent; border: none; cursor: pointer;730    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;731    display: flex; align-items: center; line-height: 0;732    transition: color 100ms, background 100ms;733  }734  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }735  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }736  /* minmax(0, 1fr) caps the grid track at the popup width — without it,737     long monospace content (e.g. a 60-char generated password) would738     auto-size the track wider than the popup and overflow the right edge. */739  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }740  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }741  .f-label {742    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;743    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;744  }745  .f-input {746    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);747    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;748    font-size: 11px; font-family: "IBM Plex Mono", monospace;749    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;750  }751  .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); }752  .f-input::placeholder { color: var(--peach-text-muted); }753  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }754  .f-row { display: flex; gap: 6px; }755  .f-row .f-input { flex: 1; min-width: 0; }756  .gen-btn {757    padding: 0 10px; border-radius: 7px; border: none;758    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);759    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);760    font-size: 10px; font-family: "IBM Plex Mono", monospace;761    cursor: pointer; white-space: nowrap; flex-shrink: 0;762    display: flex; align-items: center; gap: 4px;763    transition: background 100ms;764  }765  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }766  .gen-toggle-link {767    background: none; border: none; padding: 2px 0;768    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);769    font-size: 10px; font-family: "IBM Plex Mono", monospace;770    cursor: pointer; text-align: left; transition: color 100ms;771  }772  .gen-toggle-link:hover { color: var(--peach-accent); }773  .save-btn {774    width: 100%; padding: 8px; border-radius: 8px; border: none;775    background: var(--peach-accent); color: #fff; font-size: 12px;776    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;777    transition: background 120ms, box-shadow 120ms, transform 80ms;778    letter-spacing: 0.01em;779  }780  .save-btn:hover {781    background: color-mix(in srgb, var(--peach-accent) 82%, #000);782    box-shadow: 0 4px 20px var(--peach-glow, transparent);783  }784  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }785  .url-hint {786    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);787    font-family: "IBM Plex Mono", monospace; font-style: italic;788  }789790  /* Success */791  .success-wrap {792    display: flex; flex-direction: column; align-items: center;793    padding: 24px 16px 20px; gap: 8px;794    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;795  }796  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }797  .success-ring {798    width: 40px; height: 40px; border-radius: 50%;799    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);800    display: flex; align-items: center; justify-content: center;801  }802  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }803  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }804805  /* Silver platter (State 1 — single match) */806  .silver-platter {807    padding: 14px 14px 12px;808    display: flex; flex-direction: column; gap: 6px;809  }810  .sp-title {811    font-size: 14px; font-weight: 500; color: var(--peach-text);812    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;813    line-height: 1.25;814  }815  .sp-identity-row {816    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;817  }818  .sp-identity-label {819    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;820    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;821  }822  .sp-username {823    font-size: 12px; color: var(--peach-text-dim);824    font-family: "IBM Plex Mono", monospace;825    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;826    margin-bottom: 0;827  }828  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }829  .sp-fill-btn {830    width: 100%; padding: 11px; border-radius: 9px; border: none;831    background: var(--peach-accent); color: #fff;832    font-size: 13px; font-weight: 500; cursor: pointer;833    font-family: Inter, sans-serif; letter-spacing: 0.01em;834    display: flex; align-items: center; justify-content: center; min-height: 38px;835    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;836  }837  .sp-fill-btn:hover {838    filter: brightness(1.1);839    box-shadow: 0 4px 20px var(--peach-glow, transparent);840    transform: translateY(-1px);841  }842  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }843  .sp-fill-btn.filled {844    background: #16a34a; transform: none; filter: none;845    box-shadow: 0 4px 16px rgba(22,163,74,0.35);846    cursor: default;847  }848  .sp-fill-btn:disabled { cursor: default; }849  .sp-actions-group {850    margin-top: 6px;851    display: flex; flex-direction: column; gap: 4px;852  }853  .sp-actions-label {854    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;855    color: var(--peach-text-muted);856    font-family: "IBM Plex Mono", monospace;857    text-align: center;858  }859  .sp-actions {860    display: flex; gap: 4px; justify-content: space-between; align-items: center;861  }862  .sp-action-btn {863    flex: 1; height: 28px; border: none; border-radius: 6px;864    background: transparent; color: var(--peach-text-dim);865    font-size: 12px; cursor: pointer;866    transition: background 120ms ease, color 120ms ease;867    font-family: Inter, sans-serif; letter-spacing: 0.04em;868    display: inline-flex; align-items: center; justify-content: center; gap: 4px;869    white-space: nowrap; overflow: hidden;870  }871  .sp-action-btn:hover:not(:disabled) {872    background: color-mix(in srgb, var(--peach-text) 5%, transparent);873    color: var(--peach-text);874  }875  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }876  .sp-action-btn.flashed {877    color: var(--peach-accent);878    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);879  }880881  /* TOTP tray — shown below the silver-platter secondary actions */882  .sp-tray {883    margin-top: 8px;884    padding: 10px 12px;885    border-radius: 9px;886    background: var(--peach-input-bg);887    border: 1px solid var(--peach-input-border);888    display: flex; align-items: center; gap: 12px;889    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;890  }891  .sp-tray-label {892    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;893    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;894    flex-shrink: 0;895  }896  .sp-totp-code {897    font-size: 18px; font-weight: 500;898    color: var(--peach-text);899    font-family: "IBM Plex Mono", monospace;900    letter-spacing: 0.12em;901    flex: 1;902    text-align: center;903  }904  .sp-totp-ring {905    width: 22px; height: 22px; flex-shrink: 0;906  }907  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }908  .sp-totp-ring .ring-fill {909    stroke: var(--peach-accent);910    transition: stroke-dashoffset 1s linear;911    transform: rotate(-90deg);912    transform-origin: center;913  }914  .sp-totp-copy {915    background: transparent; border: none; cursor: pointer;916    padding: 4px 8px; border-radius: 5px;917    color: var(--peach-text-dim); font-size: 11px;918    font-family: Inter, sans-serif;919    transition: background 120ms, color 120ms;920  }921  .sp-totp-copy:hover {922    background: color-mix(in srgb, var(--peach-text) 5%, transparent);923    color: var(--peach-text);924  }925926  /* Card silver platter (State 7) — reuses .sp-* primary action classes */927  .card-platter {928    padding: 12px 14px 10px;929    display: flex; flex-direction: column; gap: 4px;930  }931  .cp-network {932    font-size: 10px; font-weight: 600;933    color: var(--peach-accent);934    letter-spacing: 0.08em; text-transform: uppercase;935    font-family: Inter, sans-serif;936  }937  .cp-nickname {938    font-size: 14px; font-weight: 500; color: var(--peach-text);939    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;940    line-height: 1.2;941  }942  .cp-last4 {943    font-size: 12px; color: var(--peach-text-dim);944    font-family: "IBM Plex Mono", monospace;945    letter-spacing: 0.04em;946    margin-top: 2px;947  }948  .cp-meta {949    font-size: 11px; color: var(--peach-text-dim);950    font-family: "IBM Plex Mono", monospace;951    margin-top: 2px;952    display: flex; gap: 10px; align-items: center;953  }954  .cp-meta-sep { opacity: 0.5; }955  .cp-fill-wrap { margin-top: 10px; }956957  /* Locked state */958  .locked-wrap {959    display: flex; flex-direction: column; align-items: stretch;960    padding: 14px 13px 13px; gap: 9px;961  }962  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }963  .locked-icon {964    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;965    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);966    display: flex; align-items: center; justify-content: center;967  }968  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }969  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }970  .locked-input {971    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);972    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;973    font-size: 11px; font-family: "IBM Plex Mono", monospace;974    outline: none; transition: border-color 120ms, box-shadow 120ms;975  }976  .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); }977  .locked-input::placeholder { color: var(--peach-text-muted); }978  .locked-btn {979    width: 100%; padding: 8px; border-radius: 8px; border: none;980    background: var(--peach-accent); color: #fff; font-size: 12px;981    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;982    transition: background 120ms;983    letter-spacing: 0.01em;984    box-shadow: 0 2px 16px var(--peach-glow, transparent);985    animation: peach-pulse-glow 2.4s ease-in-out infinite;986  }987  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }988  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }989  .locked-error {990    font-size: 10px; color: rgba(220,80,60,0.85);991    font-family: "IBM Plex Mono", monospace;992  }993994  @keyframes peach-pulse-glow {995    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }996    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),997                            0 0 48px var(--peach-glow, transparent); }998  }9991000  /* ── State 10: identity helper ─────────────────────────────── */1001  .identity-list {1002    max-height: 192px; overflow-y: auto; padding: 4px 0;1003    scrollbar-width: none;1004  }1005  .identity-list::-webkit-scrollbar { display: none; }1006  .peach-identity-row {1007    display: flex; align-items: center; gap: 10px;1008    padding: 9px 12px; cursor: pointer; border-radius: 8px;1009    transition: background 100ms ease;1010  }1011  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1012  .peach-identity-value {1013    font-family: "IBM Plex Mono", monospace; font-size: 13px;1014    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1015  }1016  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1017  .identity-search-wrap {1018    display: flex; flex-direction: column; gap: 6px;1019  }1020  .identity-mode-toggle {1021    display: inline-flex; gap: 4px; flex-wrap: wrap;1022  }1023  .identity-mode-btn {1024    border: 1px solid var(--peach-input-border);1025    background: var(--peach-input-bg);1026    color: var(--peach-text-dim);1027    border-radius: 999px;1028    padding: 4px 9px;1029    cursor: pointer;1030    font-family: "IBM Plex Mono", monospace;1031    font-size: 9px;1032    letter-spacing: 0.03em;1033    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1034  }1035  .identity-mode-btn:hover {1036    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1037    color: var(--peach-text);1038  }1039  .identity-mode-btn.is-active {1040    color: var(--peach-accent);1041    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1042    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1043  }1044  .identity-mode-btn:active { transform: translateY(1px); }1045  .identity-custom-row {1046    display: flex; flex-direction: column; gap: 2px;1047    padding: 9px 12px; cursor: pointer; border-radius: 8px;1048    transition: background 100ms ease;1049  }1050  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1051  .identity-custom-row-title {1052    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1053  }1054  .identity-custom-row-sub {1055    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1056  }1057  .identity-empty {1058    padding: 10px 12px 2px; color: var(--peach-text-dim);1059    font-size: 10px; font-family: "IBM Plex Mono", monospace;1060  }1061  .identity-alt-row {1062    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1063    border-radius: 8px; transition: background 100ms ease;1064    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1065  }1066  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1067  .identity-escape-row {1068    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1069    border-radius: 8px; transition: background 100ms ease; outline: none;1070    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1071    margin-top: 2px;1072  }1073  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1074  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1075  .identity-alt-input-wrap.open { display: flex; }1076  .identity-alt-input {1077    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1078    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1079    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1080    outline: none; transition: border-color 120ms;1081  }1082  .identity-alt-input:focus {1083    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1084    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1085  }1086  .identity-alt-confirm {1087    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1088    background: var(--peach-accent); color: #fff; font-size: 12px;1089    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1090  }1091  /* ── Generator view (after identity picked) ────────────────── */1092  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1093  .gen-confirmed {1094    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1095    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1096    border-radius: 8px;1097  }1098  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1099  .gen-confirmed-val {1100    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1101    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1102  }1103  .gen-label {1104    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1105    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1106  }1107  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1108  .gen-pw-val {1109    flex: 1; padding: 8px 10px; border-radius: 7px;1110    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1111    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1112    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1113  }1114  .gen-regen-btn {1115    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1116    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1117    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1118    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1119  }1120  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1121  .gen-fill-btn {1122    padding: 10px; border-radius: 8px; border: none;1123    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1124    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1125    transition: filter 120ms ease, transform 80ms ease;1126  }1127  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1128  .gen-fill-btn:active { transform: translateY(0); }11291130  /* ── Smart password generator (parity with main UI compact mode) ─── */1131  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1132  .pwgen-display-row {1133    display: flex; align-items: center; gap: 6px;1134    padding: 8px 10px; border-radius: 7px;1135    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1136  }1137  .pwgen-output {1138    flex: 1; min-width: 0; width: 0;1139    font-family: "IBM Plex Mono", monospace; font-size: 12px;1140    color: var(--peach-text);1141    background: transparent; border: none; outline: none; padding: 0;1142  }1143  .pwgen-icon-btn {1144    flex-shrink: 0;1145    width: 26px; height: 26px;1146    display: inline-flex; align-items: center; justify-content: center;1147    background: transparent; border: 1px solid var(--peach-input-border);1148    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1149    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1150  }1151  .pwgen-icon-btn:hover {1152    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1153    color: var(--peach-accent);1154    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1155  }1156  .pwgen-icon-btn.is-copied {1157    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1158    color: var(--peach-accent);1159    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1160  }1161  .pwgen-controls-row {1162    display: flex; align-items: center; gap: 8px;1163    flex-wrap: wrap;1164  }1165  .pwgen-slider {1166    flex: 1; min-width: 110px;1167    accent-color: var(--peach-accent);1168    cursor: pointer; height: 2px; background: transparent;1169  }1170  .pwgen-len-num {1171    font-family: "IBM Plex Mono", monospace; font-size: 11px;1172    color: var(--peach-accent); min-width: 22px; text-align: right;1173  }1174  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1175  .pwgen-len-input {1176    font-family: "IBM Plex Mono", monospace; font-size: 11px;1177    color: var(--peach-accent); width: 28px; text-align: right;1178    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1179    outline: none; padding: 0; min-width: 22px;1180  }1181  @keyframes identity-suggest-in {1182    from { opacity: 0; transform: translateY(-4px); }1183    to   { opacity: 1; transform: none; }1184  }1185  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1186    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1187  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1188  .identity-collapse-btn {1189    margin-left: auto; background: transparent; border: none; cursor: pointer;1190    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1191    line-height: 0; border-radius: 3px;1192    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1193  }1194  .identity-collapse-btn:hover { color: var(--peach-text); }1195  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1196  .identity-rows { display: grid; grid-template-rows: 1fr;1197    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1198  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1199  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1200    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1201    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1202    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1203  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1204  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1205  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1206  .identity-filter-pill {1207    padding: 2px 7px; border-radius: 999px;1208    border: 1px solid var(--peach-input-border);1209    background: transparent; color: var(--peach-text-muted);1210    font-family: "IBM Plex Mono", monospace; font-size: 9px;1211    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1212  }1213  .identity-filter-pill.is-on {1214    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1215    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1216    color: var(--peach-accent);1217  }1218  .identity-suggest-row {1219    display: flex; align-items: center; gap: 5px;1220    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1221    background: transparent; cursor: pointer; text-align: left;1222    transition: background 80ms;1223  }1224  .identity-suggest-row:hover,1225  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1226  .identity-suggest-val {1227    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1228    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1229  }1230  .identity-suggest-type {1231    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1232    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1233  }1234  .identity-suggest-type--email {1235    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1236    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1237  }1238  .identity-suggest-type--username {1239    color: var(--peach-text-muted);1240    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1241  }1242  .identity-suggest-meta {1243    font-family: "IBM Plex Mono", monospace; font-size: 9px;1244    color: var(--peach-text-muted); flex-shrink: 0;1245  }1246  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1247  .pwgen-pill {1248    padding: 3px 8px; border-radius: 999px;1249    border: 1px solid var(--peach-input-border);1250    background: transparent; color: var(--peach-text-muted);1251    font-family: "IBM Plex Mono", monospace; font-size: 9px;1252    letter-spacing: 0.06em; cursor: pointer;1253    transition: all 130ms ease;1254  }1255  .pwgen-pill.is-on {1256    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1257    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1258    color: var(--peach-accent);1259  }1260  .pwgen-pill:not(.is-on):hover {1261    color: var(--peach-text-dim);1262    border-color: var(--peach-text-muted);1263  }1264  .pwgen-policy-hint {1265    font-size: 10px; color: var(--peach-text-muted);1266    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1267    line-height: 1.3;1268  }1269  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }12701271  /* ── Save offer (after password filled) ───────────────────── */1272  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1273  .save-offer-title {1274    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1275  }1276  .save-offer-row {1277    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1278    border-radius: 7px; background: var(--peach-input-bg);1279    border: 1px solid var(--peach-input-border);1280  }1281  .save-offer-lbl {1282    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1283    font-family: "IBM Plex Mono", monospace;1284  }1285  .save-offer-val {1286    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1287    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1288  }1289  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1290  .save-offer-save {1291    flex: 1; padding: 9px; border-radius: 8px; border: none;1292    background: var(--peach-accent); color: #fff; font-size: 13px;1293    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1294  }1295  .save-offer-save:hover { filter: brightness(1.08); }1296  .save-offer-skip {1297    flex: 1; padding: 9px; border-radius: 8px; border: none;1298    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1299    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1300    font-family: Inter, sans-serif; transition: background 100ms ease;1301  }1302  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1303`;13041305export function showAutofillSelector(1306  anchorEl: HTMLInputElement,1307  entries: SelectorEntry[],1308  onSelect: (id: string) => void,1309  options: SelectorOptions = {}1310): () => void {1311  const host = document.createElement("div");1312  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1313  // when Peach's internal inputs gain focus, immediately blurring them and closing1314  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1315  // as in-bounds (v3.6.131).1316  //1317  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1318  // A plain login page whose card uses transform/filter/backdrop-filter establishes1319  // a containing block for position:fixed, so a host mounted inside it lands offset1320  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1321  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1322  // the popup ~400px off the field and clipped it behind overflow:clip — the user1323  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1324  // everything else mounts at the document root, where fixed == viewport.1325  const modalAncestor = (1326    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1327    (() => {1328      let cur: HTMLElement | null = anchorEl.parentElement;1329      while (cur && cur !== document.body) {1330        if (window.getComputedStyle(cur).position === 'fixed') return cur;1331        cur = cur.parentElement;1332      }1333      return null;1334    })()1335  );1336  host.style.cssText = `position: fixed; z-index: 2147483647;`;1337  host.style.setProperty("--peach-accent", accentHex);1338  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1339  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1340  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1341  const shadow = host.attachShadow({ mode: "closed" });13421343  const style = shadow.appendChild(document.createElement("style"));1344  style.textContent = SELECTOR_STYLES;13451346  const rect = anchorEl.getBoundingClientRect();1347  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1348  // applying containing-block compensation once host.parentElement is known.1349  host.style.top = `${rect.bottom + 5}px`;1350  host.style.left = `${rect.left}px`;1351  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1352  // wide single-input fields (e.g. centered email input on signup pages).1353  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1354  // expand the host after the initial measurement.1355  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1356  host.style.width = `${popupWidth}px`;13571358  const container = shadow.appendChild(document.createElement("div"));1359  container.className = "peach-inline-popup";1360  container.setAttribute("data-theme", popupTheme);13611362  const searchableEntries = options.searchableEntries ?? [];1363  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();13641365  let query = "";1366  let focusedIndex = -1;1367  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" = "list";1368  let searchInput: HTMLInputElement | null = null;1369  let identityMode: IdentityFilterMode = "both";1370  // Tracks the silver-platter entry the user pivoted away from, so the1371  // search/list header can offer a one-click way back to it. null when the1372  // popup never showed a single-match platter (e.g. multi-match list view).1373  let silverPlatterOrigin: SelectorEntry | null = null;1374  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1375  // setInterval. Add to this list — don't fan out the dismiss function.1376  const cleanupHooks: Array<() => void> = [];13771378  // Smooth height transitions whenever content changes height.1379  // ResizeObserver fires on natural height changes; we freeze the old height,1380  // then animate to the new one so the surface never jumps.1381  {1382    let prevH = 0;1383    let blocked = false;1384    const heightRo = new ResizeObserver(([entry]) => {1385      if (blocked) return;1386      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1387      if (prevH > 0 && Math.abs(h - prevH) > 1) {1388        blocked = true;1389        container.style.height = `${prevH}px`;1390        requestAnimationFrame(() => requestAnimationFrame(() => {1391          container.style.height = `${h}px`;1392          prevH = h;1393          const onEnd = (e: TransitionEvent) => {1394            if (e.propertyName !== "height") return;1395            container.style.height = "";1396            blocked = false;1397            container.removeEventListener("transitionend", onEnd);1398          };1399          container.addEventListener("transitionend", onEnd);1400        }));1401      } else {1402        prevH = h;1403      }1404    });1405    heightRo.observe(container);1406    cleanupHooks.push(() => heightRo.disconnect());1407  }14081409  // Pre-capture the anchor field value for username prefill1410  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1411  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1412  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";14131414  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1415    const seen = new Set<string>();1416    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1417  }14181419  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1420    const q = value.trim().toLowerCase();1421    const deduped = uniqueEntries(source);1422    if (!q) return deduped.slice(0, 8);1423    return deduped.filter(e =>1424      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1425    ).slice(0, 12);1426  }14271428  function activeEntries(): SelectorEntry[] {1429    // When user is typing a search, filter across all known entries (domain matches + vault)1430    if (query.trim()) {1431      const merged = uniqueEntries([...entries, ...searchableEntries]);1432      return filterEntries(merged, query);1433    }1434    // Default: show domain matches; fall back to vault search when no matches1435    if (entries.length > 0) return entries;1436    return filterEntries(searchableEntries, "").slice(0, 8);1437  }14381439  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1440    const icon = document.createElement("div");1441    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1442    if (isNew) {1443      icon.innerHTML = plusSvgStr();1444    } else {1445      // Use the generic key glyph for all entries in the page-injected selector.1446      // Avoids disclosing vault domains to any third party and avoids needing1447      // to expose the browser favicon API to page context via web_accessible_resources.1448      void url;1449      icon.innerHTML = keySvgStr();1450    }1451    return icon;1452  }14531454  function renderIdentityHelper() {1455    currentMode = "identity-helper";1456    container.innerHTML = "";1457    focusedIndex = -1;1458    searchInput = null;14591460    const fallbackKind: IdentityKind = options.identityKind ?? "username";1461    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1462    const typedQuery = query.trim();1463    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);14641465    function applyIdentity(identity: string) {1466      options.onFillFields?.(identity, "");1467      renderGenerator(identity);1468    }14691470    function applyCustomIdentity(identity: string) {1471      const trimmed = identity.trim();1472      if (!trimmed) return;1473      applyIdentity(trimmed);1474    }14751476    // Header: "NEW ACCOUNT" + domain name1477    const hdr = container.appendChild(document.createElement("div"));1478    hdr.className = "domain-header";1479    const headText = hdr.appendChild(document.createElement("div"));1480    headText.className = "domain-header-text";1481    const eyebrow = headText.appendChild(document.createElement("div"));1482    eyebrow.className = "domain-eyebrow";1483    eyebrow.textContent = "NEW ACCOUNT";1484    const domName = headText.appendChild(document.createElement("div"));1485    domName.className = "domain-name";1486    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14871488    const actions = hdr.appendChild(document.createElement("div"));1489    actions.className = "identity-mode-toggle";1490    for (const mode of ["both", "email", "username"] as const) {1491      const btn = actions.appendChild(document.createElement("button"));1492      btn.type = "button";1493      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1494      btn.textContent = identityFilterLabel(mode);1495      btn.setAttribute("aria-pressed", String(identityMode === mode));1496      btn.addEventListener("click", () => {1497        identityMode = mode;1498        renderIdentityHelper();1499      });1500    }15011502    const searchWrap = container.appendChild(document.createElement("div"));1503    searchWrap.className = "search-wrap identity-search-wrap";1504    const search = searchWrap.appendChild(document.createElement("input"));1505    search.className = "search";1506    search.placeholder = "search identities…";1507    search.value = query;1508    search.addEventListener("input", () => {1509      query = search.value;1510      renderIdentityHelper();1511      searchInput?.focus();1512      searchInput?.setSelectionRange(query.length, query.length);1513    });1514    search.addEventListener("keydown", (e) => {1515      if (e.key === "Escape") {1516        e.preventDefault();1517        dismiss(true);1518        return;1519      }1520      if (e.key !== "Enter") return;1521      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1522      if (exact) {1523        e.preventDefault();1524        applyIdentity(exact.value);1525        return;1526      }1527      if (!typedQuery || identities.length > 0) return;1528      e.preventDefault();1529      applyCustomIdentity(typedQuery);1530    });1531    const searchTools = searchWrap.appendChild(document.createElement("div"));1532    searchTools.className = "identity-mode-toggle";1533    const sortHint = searchTools.appendChild(document.createElement("div"));1534    sortHint.className = "identity-empty";1535    sortHint.style.padding = "0";1536    sortHint.textContent = "sorted by recent use";1537    searchInput = search;1538    const customLabel = identityMode === "both"1539      ? customKind1540      : identityMode;15411542    // Identity rows1543    const list = container.appendChild(document.createElement("div"));1544    list.className = "identity-list";1545    if (typedQuery && identities.length === 0) {1546      const empty = list.appendChild(document.createElement("div"));1547      empty.className = "identity-empty";1548      empty.textContent = identityMode === "both"1549        ? `No match for “${typedQuery}”.`1550        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1551      const custom = list.appendChild(document.createElement("div"));1552      custom.className = "identity-custom-row";1553      const customTitle = custom.appendChild(document.createElement("div"));1554      customTitle.className = "identity-custom-row-title";1555      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1556      const customSub = custom.appendChild(document.createElement("div"));1557      customSub.className = "identity-custom-row-sub";1558      customSub.textContent = "Press Enter or click to continue.";1559      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1560    }1561    for (const id of identities) {1562      const row = list.appendChild(document.createElement("div"));1563      row.className = "peach-identity-row";1564      row.setAttribute("tabindex", "-1");1565      const val = row.appendChild(document.createElement("div"));1566      val.className = "peach-identity-value";1567      val.textContent = id.value;1568      const meta = row.appendChild(document.createElement("div"));1569      meta.className = "peach-identity-meta";1570      meta.textContent = `used ${id.useCount}×`;1571      row.addEventListener("click", () => {1572        applyIdentity(id.value);1573      });1574    }15751576    // Divider before "Use a different email…"1577    if (identities.length > 0) {1578      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1579    }15801581    // "Use a different email/username…" expandable row1582    const altRow = container.appendChild(document.createElement("div"));1583    altRow.className = "identity-alt-row";1584    altRow.textContent = `+ Use a different ${customLabel}…`;15851586    const altInputWrap = container.appendChild(document.createElement("div"));1587    altInputWrap.className = "identity-alt-input-wrap";1588    const altInput = altInputWrap.appendChild(document.createElement("input"));1589    altInput.className = "identity-alt-input";1590    altInput.type = "text";1591    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1592    altInput.setAttribute("autocomplete", "off");1593    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1594    altConfirm.className = "identity-alt-confirm";1595    altConfirm.type = "button";1596    altConfirm.textContent = "✓";15971598    function fillCustomIdentity() {1599      const v = altInput.value.trim();1600      if (!v) return;1601      applyCustomIdentity(v);1602    }16031604    altRow.addEventListener("click", () => {1605      altRow.style.display = "none";1606      altInputWrap.classList.add("open");1607      altInput.value = typedQuery || altInput.value;1608      altInput.focus();1609      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1610    });1611    altConfirm.addEventListener("click", fillCustomIdentity);1612    altInput.addEventListener("keydown", (e) => {1613      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1614    });16151616    // Escape hatch: user already has a vault entry for this site but it1617    // wasn't detected (different domain, old entry, etc.). Tapping this1618    // switches to the full searchable list so they can find and fill it;1619    // selecting an entry there will trigger the remember-site toast if1620    // the domain isn't already associated.1621    if ((options.searchableEntries?.length ?? 0) > 0) {1622      const escapeRow = container.appendChild(document.createElement("div"));1623      escapeRow.className = "identity-escape-row";1624      escapeRow.textContent = "I already have an account →";1625      escapeRow.setAttribute("tabindex", "0");1626      escapeRow.addEventListener("click", () => renderList());1627      escapeRow.addEventListener("keydown", (e) => {1628        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1629      });1630    }16311632    requestAnimationFrame(() => {1633      search.focus();1634      search.setSelectionRange(query.length, query.length);1635    });1636  }16371638  function renderGenerator(filledEmail: string) {1639    container.innerHTML = "";1640    const sitePolicy = detectPasswordPolicy();16411642    const wrap = container.appendChild(document.createElement("div"));1643    wrap.className = "gen-view";16441645    // Header: domain + NEW ACCOUNT1646    const hdrRow = wrap.appendChild(document.createElement("div"));1647    hdrRow.className = "domain-header";1648    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1649    eyebrow2.className = "domain-eyebrow";1650    eyebrow2.textContent = "NEW ACCOUNT";1651    const domName2 = hdrRow.appendChild(document.createElement("div"));1652    domName2.className = "domain-name";1653    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");16541655    // Confirmed email row1656    const conf = wrap.appendChild(document.createElement("div"));1657    conf.className = "gen-confirmed";1658    const confCheck = conf.appendChild(document.createElement("span"));1659    confCheck.className = "gen-confirmed-check";1660    confCheck.textContent = "✓";1661    const confVal = conf.appendChild(document.createElement("div"));1662    confVal.className = "gen-confirmed-val";1663    confVal.textContent = filledEmail;16641665    const lbl = wrap.appendChild(document.createElement("div"));1666    lbl.className = "gen-label";1667    lbl.textContent = "Generate a password";16681669    let currentPw = "";1670    const smartGen = createSmartGenerator({1671      policy: sitePolicy,1672      onChange: (pw) => { currentPw = pw; },1673    });1674    wrap.appendChild(smartGen.root);16751676    const fillBtn = wrap.appendChild(document.createElement("button"));1677    fillBtn.className = "gen-fill-btn";1678    fillBtn.type = "button";1679    fillBtn.textContent = "Copy & fill";1680    fillBtn.addEventListener("click", () => {1681      if (!currentPw) return;1682      options.onFillFields?.("", currentPw);1683      renderSaveOffer(filledEmail, currentPw);1684    });1685  }16861687  function renderSaveOffer(filledEmail: string, filledPassword: string) {1688    container.innerHTML = "";1689    const domain = options.domain ?? location.hostname.replace(/^www\./, "");16901691    const wrap = container.appendChild(document.createElement("div"));1692    wrap.className = "save-offer";16931694    const title = wrap.appendChild(document.createElement("div"));1695    title.className = "save-offer-title";1696    title.textContent = "Save this login to Peach?";16971698    function detailRow(label: string, value: string) {1699      const row = wrap.appendChild(document.createElement("div"));1700      row.className = "save-offer-row";1701      const lbl = row.appendChild(document.createElement("div"));1702      lbl.className = "save-offer-lbl";1703      lbl.textContent = label;1704      const val = row.appendChild(document.createElement("div"));1705      val.className = "save-offer-val";1706      val.textContent = value;1707    }17081709    detailRow("site", domain);1710    detailRow("email", filledEmail);1711    detailRow("password", "••••••••••••••••");17121713    const btns = wrap.appendChild(document.createElement("div"));1714    btns.className = "save-offer-btns";17151716    const saveBtn = btns.appendChild(document.createElement("button"));1717    saveBtn.className = "save-offer-save";1718    saveBtn.type = "button";1719    saveBtn.textContent = "Save";1720    saveBtn.addEventListener("click", async () => {1721      saveBtn.disabled = true;1722      saveBtn.textContent = "Saving…";1723      try {1724        const res = await chrome.runtime.sendMessage({1725          type: "ADD_ENTRY",1726          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1727        });1728        if ((res as { ok?: boolean }).ok) {1729          showSuccess(sTitle);1730        } else {1731          saveBtn.disabled = false;1732          saveBtn.textContent = "Save";1733        }1734      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1735    });17361737    const skipBtn = btns.appendChild(document.createElement("button"));1738    skipBtn.className = "save-offer-skip";1739    skipBtn.type = "button";1740    skipBtn.textContent = "Not now";1741    skipBtn.addEventListener("click", () => { dismiss(true); });1742  }17431744  function renderList() {1745    container.innerHTML = "";1746    focusedIndex = -1;1747    searchInput = null;1748    currentMode = "list";17491750    const current = activeEntries();17511752    // Domain header (always show) — eyebrow + domain on the left,1753    // a "+" shortcut to the create form on the right so the user is never1754    // trapped in the search list when they want to make a new entry.1755    const domHdr = document.createElement("div");1756    domHdr.className = "domain-header";1757    const headText = document.createElement("div");1758    headText.className = "domain-header-text";1759    const eyebrow = document.createElement("div");1760    eyebrow.className = "domain-eyebrow";1761    eyebrow.textContent = options.isSignup1762      ? "Sign up as"1763      : entries.length > 0 ? "Saved for this site" : "No saved login";1764    const domName = document.createElement("div");1765    domName.className = "domain-name";1766    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1767    headText.append(eyebrow, domName);1768    domHdr.appendChild(headText);17691770    if (!options.isSignup) {1771      const actions = document.createElement("div");1772      actions.className = "domain-header-actions";17731774      // Back arrow takes the place of the silver-platter's search icon when1775      // the user has pivoted away from a single-match platter — gives them1776      // a one-click way back to the original recommendation.1777      if (silverPlatterOrigin) {1778        const backBtn = document.createElement("button");1779        backBtn.className = "domain-search-btn";1780        backBtn.type = "button";1781        backBtn.setAttribute("aria-label", "Back to suggested entry");1782        backBtn.title = "Back to suggested entry";1783        backBtn.innerHTML = backSvgStr();1784        backBtn.addEventListener("click", (e) => {1785          e.stopPropagation();1786          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);1787        });1788        actions.appendChild(backBtn);1789      }17901791      const addBtn = document.createElement("button");1792      addBtn.className = "domain-add-btn";1793      addBtn.type = "button";1794      addBtn.setAttribute("aria-label", "Create new entry");1795      addBtn.title = "Create new entry";1796      addBtn.textContent = "+";1797      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1798      actions.appendChild(addBtn);17991800      domHdr.appendChild(actions);1801    }18021803    container.appendChild(domHdr);18041805    // Search — always show so user can find entries beyond the domain matches1806    const sw = document.createElement("div"); sw.className = "search-wrap";1807    searchInput = document.createElement("input");1808    searchInput.className = "search";1809    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1810    searchInput.value = query;1811    searchInput.addEventListener("input", () => {1812      query = searchInput?.value ?? "";1813      renderList();1814      searchInput?.focus();1815      searchInput?.setSelectionRange(query.length, query.length);1816    });1817    sw.appendChild(searchInput);1818    container.appendChild(sw);18191820    // Results1821    const results = document.createElement("div");1822    results.className = "results";1823    container.appendChild(results);18241825    if (current.length === 0 && entries.length > 0) {1826      // Show a hint but don't render empty entries1827    }18281829    for (let i = 0; i < current.length; i++) {1830      const e = current[i]!;1831      const entryEl = document.createElement("div");1832      entryEl.className = "entry";1833      entryEl.dataset.id = e.id;1834      entryEl.dataset.index = String(i);1835      entryEl.setAttribute("tabindex", "-1");18361837      entryEl.appendChild(makeEntryIcon(e.url));18381839      const info = document.createElement("div"); info.className = "entry-info";1840      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1841      const subEl = document.createElement("div"); subEl.className = "entry-sub";1842      const domain = e.url ? getDomainFromUrl(e.url) : "";1843      subEl.textContent = domain || e.username || "";1844      info.append(titleEl, subEl);1845      entryEl.appendChild(info);18461847      if (e.hasTotp) {1848        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1849        entryEl.appendChild(badge);1850      }1851      if (e.hasPasskey) {1852        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1853        entryEl.appendChild(badge);1854      }18551856      entryEl.addEventListener("click", () => {1857        if (options.isSignup && options.onFillFields) {1858          // Signup mode: clicking a saved identity fills the username field1859          options.onFillFields(e.username ?? "", "");1860          dismiss();1861        } else {1862          onSelect(e.id);1863          dismiss();1864        }1865      });1866      results.appendChild(entryEl);1867    }18681869    // Divider before "New entry"1870    if (current.length > 0) {1871      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1872    }18731874    // "New entry" row — always present1875    const newEl = document.createElement("div");1876    newEl.className = "entry";1877    newEl.setAttribute("tabindex", "-1");1878    newEl.appendChild(makeEntryIcon(undefined, true));18791880    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1881    const newTitle = document.createElement("div");1882    newTitle.className = "entry-title is-new";1883    newTitle.textContent = `New entry for ${sTitle}`;1884    const newSub = document.createElement("div");1885    newSub.className = "entry-sub";1886    newSub.textContent = sOrigin;1887    newInfo.append(newTitle, newSub);1888    newEl.appendChild(newInfo);1889    newEl.addEventListener("click", showCreateForm);1890    results.appendChild(newEl);18911892    // Focus search if present1893    if (searchInput) {1894      requestAnimationFrame(() => {1895        searchInput?.focus();1896        // Seed query (from type-to-search or domain-search-btn) lands at the1897        // end so the next keystroke extends it, not overwrites.1898        searchInput?.setSelectionRange(query.length, query.length);1899      });1900    }1901  }19021903  function setFocused(idx: number) {1904    const all = container.querySelectorAll<HTMLElement>(".entry");1905    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1906    focusedIndex = idx;1907    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1908  }19091910  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1911    const typed = identities.filter(s => s.type === fieldType);1912    if (!typed.length) return;1913    let collapsed = false;1914    let suppressNextFocus = false;19151916    const list = g.appendChild(document.createElement("div"));1917    list.className = "identity-suggest-list";1918    list.style.display = "none";19191920    // Collapse toggle — sits alone now that filter pills are gone1921    const collapseRow = list.appendChild(document.createElement("div"));1922    collapseRow.className = "identity-filter-row";1923    collapseRow.style.justifyContent = "flex-end";1924    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1925    collapseBtn.type = "button";1926    collapseBtn.className = "identity-collapse-btn";1927    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>`;1928    collapseBtn.addEventListener("mousedown", (e) => {1929      e.preventDefault();1930      collapsed = !collapsed;1931      collapseBtn.classList.toggle("is-collapsed", collapsed);1932      rowsWrapper.classList.toggle("is-collapsed", collapsed);1933    });19341935    const rowsWrapper = list.appendChild(document.createElement("div"));1936    rowsWrapper.className = "identity-rows";1937    const rows = rowsWrapper.appendChild(document.createElement("div"));1938    rows.className = "identity-rows-inner";19391940    // Hides the list and removes the document-level click watcher.1941    function hideList() {1942      list.style.display = "none";1943      document.removeEventListener("mousedown", onDocMousedown, { capture: true });1944    }19451946    // Dismiss list on any mousedown that originates outside the popup's shadow1947    // DOM. This is the ONLY close trigger for the list — blur is intentionally1948    // NOT used, because modal focus traps fire blur without a mousedown (they1949    // call element.focus() programmatically in response to focusin/focusout),1950    // which caused the list to vanish before the user could pick from it.1951    function onDocMousedown(e: MouseEvent) {1952      if (e.composedPath().includes(host)) return;1953      hideList();1954    }19551956    function pick(value: string) {1957      inp.value = value;1958      hideList();1959      suppressNextFocus = true;1960      inp.focus();1961      // If a focus trap intercepts inp.focus() and redirects to anchorEl before1962      // inp ever fires its focus event, suppressNextFocus would strand the user.1963      // Clear after a short window so subsequent clicks still work.1964      setTimeout(() => { suppressNextFocus = false; }, 120);1965    }19661967    function render() {1968      const q = inp.value.toLowerCase();1969      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1970      rows.innerHTML = "";1971      if (!filtered.length) { hideList(); return; }1972      for (const s of filtered) {1973        const row = rows.appendChild(document.createElement("button"));1974        row.type = "button"; row.className = "identity-suggest-row";1975        const val = row.appendChild(document.createElement("span"));1976        val.className = "identity-suggest-val"; val.textContent = s.value;1977        const meta = row.appendChild(document.createElement("span"));1978        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1979        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1980        row.addEventListener("keydown", (e) => {1981          if (e.key === "ArrowDown") {1982            e.preventDefault();1983            (row.nextElementSibling as HTMLElement | null)?.focus();1984          } else if (e.key === "ArrowUp") {1985            e.preventDefault();1986            const prev = row.previousElementSibling as HTMLElement | null;1987            if (prev) prev.focus();1988            else inp.focus();1989          } else if (e.key === "Enter" || e.key === " ") {1990            e.preventDefault();1991            pick(s.value);1992          } else if (e.key === "Escape") {1993            e.preventDefault();1994            hideList();1995            suppressNextFocus = true;1996            inp.focus();1997          }1998        });1999        // Row blur only fires during keyboard navigation (arrow keys / Tab).2000        // Focus traps don't produce row blur events since rows aren't focused2001        // when the trap fires; this handler is therefore trap-safe.2002        row.addEventListener("blur", (e) => {2003          const rt = (e as FocusEvent).relatedTarget as Node | null;2004          if (rt && (rt === inp || list.contains(rt))) return;2005          setTimeout(() => { hideList(); }, 150);2006        });2007      }2008      list.style.display = "";2009      // Register the close-on-outside-click watcher each time the list shows.2010      // addEventListener deduplicates identical (fn, options) pairs, so2011      // re-rendering on input events does not stack up listeners.2012      document.addEventListener("mousedown", onDocMousedown, { capture: true });2013    }20142015    inp.addEventListener("focus", () => {2016      if (suppressNextFocus) { suppressNextFocus = false; return; }2017      render();2018    });2019    inp.addEventListener("input", render);2020    inp.addEventListener("keydown", (e) => {2021      if (list.style.display === "none") return;2022      if (e.key === "ArrowDown" && !collapsed) {2023        e.preventDefault();2024        (rows.firstElementChild as HTMLElement | null)?.focus();2025      } else if (e.key === "Escape") {2026        e.preventDefault();2027        hideList();2028      } else if (e.key === "Tab") {2029        // Tab moves focus away intentionally — close the list.2030        hideList();2031      }2032    });2033    // No blur handler on inp. Blur fires for ANY focus movement including2034    // programmatic focus() calls from modal focus traps, which caused the list2035    // to close before the user could interact. The document mousedown listener2036    // (registered in render()) handles intentional click-outside dismissal,2037    // and the keydown handler above covers keyboard Tab/Escape.20382039    // Ensure the watcher is removed if the main popup is dismissed while the2040    // list is visible.2041    cleanupHooks.push(hideList);2042  }20432044  async function showCreateForm() {2045    currentMode = "create";2046    container.innerHTML = "";20472048    // Guard: the service worker may lock the vault between when the selector2049    // opens and when the user clicks "New entry". Show the inline unlock form2050    // instead of silently failing on save.2051    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2052    if (!statusRes?.unlocked) {2053      renderLocked();2054      return;2055    }20562057    // Detect page password policy once for this form — reused on every2058    // regenerate click so the user always gets a compliant password.2059    const sitePolicy = detectPasswordPolicy();20602061    // Fetch identities on-demand — they're passed in signup context but not2062    // in login/search context where the user still clicks "New entry".2063    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];2064    if (!formIdentities.length) {2065      try {2066        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;2067        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;2068      } catch { /* silent fallback */ }2069    }20702071    const wrap = document.createElement("div");2072    wrap.className = "create-form-wrap";20732074    // Header2075    const head = document.createElement("div"); head.className = "create-head";2076    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2077    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>`;2078    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2079    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2080    head.append(backBtn, lbl);20812082    // Body2083    const body = document.createElement("div"); body.className = "create-body";20842085    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2086      const g = document.createElement("div"); g.className = "f-group";2087      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2088      const inp = document.createElement("input"); inp.className = "f-input";2089      g.append(l, inp); return { g, inp };2090    }20912092    // Title2093    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2094    body.appendChild(tg.g);20952096    // URL2097    const ug = fGroup("website");2098    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2099    if (loginSubdomain) {2100      const h = document.createElement("div"); h.className = "url-hint";2101      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2102    }2103    body.appendChild(ug.g);21042105    // Username — pre-fill from anchor if it doesn't look like an email2106    const xg = fGroup("username");2107    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2108    xg.inp.placeholder = "johndoe";2109    xg.inp.setAttribute("autocomplete", "off");2110    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2111    body.appendChild(xg.g);21122113    // Email — pre-fill from anchor if it looks like an email2114    const eg = fGroup("email");2115    (eg.inp as HTMLInputElement).type = "email";2116    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2117    eg.inp.placeholder = "[email protected]";2118    eg.inp.setAttribute("autocomplete", "off");2119    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2120    body.appendChild(eg.g);21212122    // Password — full smart generator with charset pills + length slider +2123    // policy hint. Mirrors the main UI's compact generator so users get the2124    // same controls inline as in the popup.2125    const pg = fGroup("password");2126    pg.inp.remove(); // smartGen provides its own display — no separate input needed2127    let currentPassword = prePassword || "";2128    const smartGen = createSmartGenerator({2129      policy: sitePolicy,2130      initialPassword: prePassword || undefined,2131      onChange: (pw) => { currentPassword = pw; },2132    });2133    pg.g.appendChild(smartGen.root);2134    body.appendChild(pg.g);21352136    // Save2137    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2138    saveBtn.textContent = "Save entry";2139    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2140    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2141    saveBtn.addEventListener("click", async () => {2142      const title = tg.inp.value.trim();2143      const pw = currentPassword.trim();2144      const username = xg.inp.value.trim();2145      const email = eg.inp.value.trim();2146      if (!title) {2147        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2148        showFormError("Entry needs a title");2149        return;2150      }2151      if (!pw) {2152        showFormError("Entry needs a password — tap regen to make one");2153        return;2154      }2155      errEl.style.display = "none";2156      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2157      try {2158        const res = await chrome.runtime.sendMessage({2159          type: "ADD_ENTRY",2160          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2161        });2162        if ((res as { ok?: boolean }).ok) {2163          // Fill the detected form. onFillFields uses whichever identity the2164          // page anchored on — the vault captures both username and email.2165          options.onFillFields?.(username || email, pw);2166          showSuccess(title);2167        } else {2168          const err = (res as { error?: string })?.error;2169          const errMsg = err === "vault_locked"2170            ? "Vault locked — open Peach to save"2171            : err === "STORAGE_QUOTA_EXCEEDED"2172              ? "Out of storage — open Peach → Settings to free space"2173              : err2174                ? `Could not save: ${err}`2175                : "Could not save entry";2176          showFormError(errMsg);2177          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2178        }2179      } catch (e) {2180        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2181        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2182      }2183    });2184    body.appendChild(saveBtn);2185    body.appendChild(errEl);21862187    wrap.append(head, body);2188    container.appendChild(wrap);2189    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2190  }21912192  function showSuccess(title: string) {2193    currentMode = "success";2194    container.innerHTML = "";2195    const wrap = document.createElement("div"); wrap.className = "success-wrap";2196    const ring = document.createElement("div"); ring.className = "success-ring";2197    ring.innerHTML = checkSvgStr();2198    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2199    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2200    wrap.append(ring, t, s);2201    container.appendChild(wrap);2202    setTimeout(() => dismiss(), 1600);2203  }22042205  function flashActionBtn(btn: HTMLButtonElement) {2206    btn.classList.add("flashed");2207    setTimeout(() => btn.classList.remove("flashed"), 700);2208  }22092210  // M3/QUA-005: when both the direct clipboard write and the background COPY2211  // fallback fail, briefly show the user that the copy did not happen.2212  function flashCopyError(btn: HTMLButtonElement) {2213    const original = btn.textContent ?? "";2214    btn.textContent = "Blocked";2215    btn.classList.add("flashed");2216    setTimeout(() => {2217      btn.classList.remove("flashed");2218      if (btn.isConnected) btn.textContent = original;2219    }, 1200);2220  }22212222  function renderSilverPlatter(entry: SelectorEntry) {2223    container.innerHTML = "";2224    searchInput = null;2225    focusedIndex = -1;2226    currentMode = "silver-platter";2227    silverPlatterOrigin = entry;22282229    const domHdr = document.createElement("div");2230    domHdr.className = "domain-header";2231    const headText = document.createElement("div");2232    headText.className = "domain-header-text";2233    const eyebrow = document.createElement("div");2234    eyebrow.className = "domain-eyebrow";2235    eyebrow.textContent = "Saved for this site";2236    const domName = document.createElement("div");2237    domName.className = "domain-name";2238    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2239    headText.append(eyebrow, domName);2240    domHdr.appendChild(headText);2241    if (!options.isSignup) {2242      const actions = document.createElement("div");2243      actions.className = "domain-header-actions";22442245      // Search shortcut — same idea as type-to-search below, but visible so2246      // the user can discover that another entry is reachable from a2247      // single-match platter. Sits to the left of the create button.2248      const searchBtn = document.createElement("button");2249      searchBtn.className = "domain-search-btn";2250      searchBtn.type = "button";2251      searchBtn.setAttribute("aria-label", "Search for a different entry");2252      searchBtn.title = "Search for a different entry";2253      searchBtn.innerHTML = searchSvgStr();2254      searchBtn.addEventListener("click", (e) => {2255        e.stopPropagation();2256        query = "";2257        renderList();2258      });2259      actions.appendChild(searchBtn);22602261      const addBtn = document.createElement("button");2262      addBtn.className = "domain-add-btn";2263      addBtn.type = "button";2264      addBtn.setAttribute("aria-label", "Create new entry");2265      addBtn.title = "Create new entry";2266      addBtn.textContent = "+";2267      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2268      actions.appendChild(addBtn);22692270      domHdr.appendChild(actions);2271    }2272    container.appendChild(domHdr);22732274    const platter = document.createElement("div");2275    platter.className = "silver-platter";22762277    const titleEl = document.createElement("div");2278    titleEl.className = "sp-title";2279    titleEl.textContent = entry.title;2280    platter.appendChild(titleEl);22812282    if (entry.email) {2283      const emailEl = document.createElement("div");2284      emailEl.className = "sp-identity-row";2285      const emailLbl = document.createElement("span");2286      emailLbl.className = "sp-identity-label";2287      emailLbl.textContent = "email";2288      const emailVal = document.createElement("span");2289      emailVal.className = "sp-username";2290      emailVal.textContent = entry.email;2291      emailEl.append(emailLbl, emailVal);2292      platter.appendChild(emailEl);2293    }22942295    if (entry.username) {2296      const userEl = document.createElement("div");2297      userEl.className = "sp-identity-row";2298      const userLbl = document.createElement("span");2299      userLbl.className = "sp-identity-label";2300      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2301      const userVal = document.createElement("span");2302      userVal.className = "sp-username";2303      userVal.textContent = entry.username;2304      userEl.append(userLbl, userVal);2305      platter.appendChild(userEl);2306    }23072308    const fillBtn = document.createElement("button");2309    fillBtn.className = "sp-fill-btn";2310    fillBtn.type = "button";2311    fillBtn.textContent = "Fill credentials";2312    fillBtn.addEventListener("click", () => {2313      if (fillBtn.disabled) return;2314      fillBtn.disabled = true;2315      fillBtn.classList.add("filled");2316      fillBtn.innerHTML = checkSvgStr();2317      // Fire the fill, then exit via the standard exit animation. The fill2318      // itself is async (handled in index.ts) — by 400ms the form is filled2319      // and the popup begins its exit. Total dwell from click to host2320      // removal: 400ms + 130ms (exit animation) = 530ms.2321      onSelect(entry.id);2322      setTimeout(() => dismiss(), 400);2323    });2324    platter.appendChild(fillBtn);23252326    const actionsGroup = document.createElement("div");2327    actionsGroup.className = "sp-actions-group";2328    const actionsLabel = document.createElement("div");2329    actionsLabel.className = "sp-actions-label";2330    actionsLabel.textContent = "Copy";2331    actionsGroup.appendChild(actionsLabel);23322333    const actions = document.createElement("div");2334    actions.className = "sp-actions";2335    actionsGroup.appendChild(actions);23362337    if (entry.email) {2338      const copyEmail = document.createElement("button");2339      copyEmail.className = "sp-action-btn";2340      copyEmail.type = "button";2341      copyEmail.title = "Copy email";2342      copyEmail.textContent = "Email";2343      copyEmail.addEventListener("click", async (e) => {2344        e.stopPropagation();2345        let alreadyWritten = false;2346        try {2347          await navigator.clipboard.writeText(entry.email!);2348          alreadyWritten = true;2349        } catch (err) {2350          console.warn("[Peach] clipboard write denied:", err);2351        }2352        const resp = await chrome.runtime.sendMessage({2353          type: "COPY",2354          payload: { text: entry.email, label: "Email", alreadyWritten },2355        }).catch(() => null) as { ok?: boolean } | null;2356        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2357        else flashCopyError(copyEmail);2358      });2359      actions.appendChild(copyEmail);2360    }23612362    const copyU = document.createElement("button");2363    copyU.className = "sp-action-btn";2364    copyU.type = "button";2365    const usernameIsEmail = entry.username?.includes("@") ?? false;2366    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2367    copyU.textContent = usernameIsEmail ? "Email" : "Username";2368    copyU.disabled = !entry.username;2369    copyU.addEventListener("click", async (e) => {2370      e.stopPropagation();2371      if (!entry.username) return;2372      let alreadyWritten = false;2373      try {2374        await navigator.clipboard.writeText(entry.username);2375        alreadyWritten = true;2376      } catch (err) {2377        console.warn("[Peach] clipboard write denied:", err);2378      }2379      const resp = await chrome.runtime.sendMessage({2380        type: "COPY",2381        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2382      }).catch(() => null) as { ok?: boolean } | null;2383      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2384      else flashCopyError(copyU);2385    });2386    actions.appendChild(copyU);23872388    const copyP = document.createElement("button");2389    copyP.className = "sp-action-btn";2390    copyP.type = "button";2391    copyP.title = "Copy password";2392    copyP.textContent = "Password";2393    copyP.addEventListener("click", async (e) => {2394      e.stopPropagation();2395      const resp = await chrome.runtime.sendMessage({2396        type: "GET_ENTRY_FOR_FILL",2397        payload: { id: entry.id },2398      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2399      if (!resp?.ok || !resp.data?.password) return;2400      let alreadyWritten = false;2401      try {2402        await navigator.clipboard.writeText(resp.data.password);2403        alreadyWritten = true;2404      } catch (err) {2405        console.warn("[Peach] clipboard write denied:", err);2406      }2407      const copyResp = await chrome.runtime.sendMessage({2408        type: "COPY",2409        payload: { text: resp.data.password, label: "Password", alreadyWritten },2410      }).catch(() => null) as { ok?: boolean } | null;2411      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2412      else flashCopyError(copyP);2413    });2414    actions.appendChild(copyP);24152416    let trayEl: HTMLDivElement | null = null;2417    let trayInterval: ReturnType<typeof setInterval> | null = null;24182419    function closeTray() {2420      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2421      trayEl?.remove();2422      trayEl = null;2423    }2424    // Register so dismiss() will close the tray and clear the interval2425    // even if the user dismisses without explicitly closing the tray.2426    cleanupHooks.push(closeTray);24272428    async function openTOTPTray() {2429      // Fetch the current TOTP code from the background. The raw base32 seed2430      // never enters the content script (SEV-3-C): we receive the live 6-digit2431      // code plus the seconds remaining, count down locally, and re-fetch a2432      // fresh code only when the 30s window rolls over.2433      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2434        const r = await chrome.runtime.sendMessage({2435          type: "GET_ENTRY_FOR_FILL",2436          payload: { id: entry.id },2437        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2438        if (!r?.ok || !r.data?.totpCode) return null;2439        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2440      }2441      let current = await fetchCode();2442      if (!current) return;24432444      trayEl = document.createElement("div");2445      trayEl.className = "sp-tray";24462447      const label = document.createElement("span");2448      label.className = "sp-tray-label";2449      label.textContent = "2FA";2450      trayEl.appendChild(label);24512452      const codeEl = document.createElement("div");2453      codeEl.className = "sp-totp-code";2454      trayEl.appendChild(codeEl);24552456      const ringNs = "http://www.w3.org/2000/svg";2457      const ring = document.createElementNS(ringNs, "svg");2458      ring.setAttribute("class", "sp-totp-ring");2459      ring.setAttribute("viewBox", "0 0 24 24");2460      const trackC = document.createElementNS(ringNs, "circle");2461      trackC.setAttribute("class", "ring-track");2462      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2463      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2464      const fillC = document.createElementNS(ringNs, "circle");2465      fillC.setAttribute("class", "ring-fill");2466      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2467      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2468      fillC.setAttribute("stroke-linecap", "round");2469      fillC.setAttribute("stroke-dasharray", "62.83");2470      ring.append(trackC, fillC);2471      trayEl.appendChild(ring);24722473      const copyBtn = document.createElement("button");2474      copyBtn.className = "sp-totp-copy";2475      copyBtn.type = "button";2476      copyBtn.textContent = "Copy";2477      trayEl.appendChild(copyBtn);24782479      function render() {2480        const { code, remaining } = current!;2481        // Group as "847 291" — easier to read than "847291"2482        codeEl.textContent = code.length === 62483          ? `${code.slice(0, 3)} ${code.slice(3)}`2484          : code;2485        // Ring fills counter-clockwise as time elapses: dashoffset goes from2486        // 0 (full ring) to 62.83 (empty) over the 30s window.2487        const fraction = (30 - remaining) / 30;2488        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2489      }2490      render();2491      trayInterval = setInterval(async () => {2492        if (!current) return;2493        current = { code: current.code, remaining: current.remaining - 1 };2494        // Window rolled over — pull a fresh code from the background.2495        if (current.remaining <= 0) {2496          const next = await fetchCode();2497          current = next ?? { code: current.code, remaining: 30 };2498        }2499        render();2500      }, 1000);25012502      copyBtn.addEventListener("click", async (e) => {2503        e.stopPropagation();2504        const code = current?.code;2505        if (!code) return;2506        let alreadyWritten = false;2507        try {2508          await navigator.clipboard.writeText(code);2509          alreadyWritten = true;2510        } catch (err) {2511          console.warn("[Peach] clipboard write denied:", err);2512        }2513        const resp = await chrome.runtime.sendMessage({2514          type: "COPY",2515          payload: { text: code, label: "TOTP", alreadyWritten },2516        }).catch(() => null) as { ok?: boolean } | null;2517        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2518        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2519      });25202521      platter.appendChild(trayEl);2522    }25232524    const editBtn = document.createElement("button");2525    editBtn.className = "sp-action-btn sp-action-edit";2526    editBtn.type = "button";2527    editBtn.title = "Edit entry";2528    editBtn.textContent = "Edit";2529    editBtn.addEventListener("click", (e) => {2530      e.stopPropagation();2531      closeTray();2532      void renderInlineEdit(entry);2533    });2534    actions.appendChild(editBtn);25352536    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2537    // "···" toggle was zero-savings (the toggle button took the same space2538    // the "2FA" label needed) and made the code one extra click away.2539    if (entry.hasTotp) void openTOTPTray();25402541    platter.appendChild(actionsGroup);2542    container.appendChild(platter);2543  }25442545  /**2546   * Inline-popup edit mode. Swaps the silver platter for an editable form2547   * over the same shadow-DOM surface so the user never leaves the page.2548   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2549   * with the new fields. Cancel returns without writing.2550   */2551  async function renderInlineEdit(summary: SelectorEntry) {2552    container.innerHTML = "";2553    const wrap = document.createElement("div");2554    wrap.className = "create-form-wrap";25552556    const head = document.createElement("div");2557    head.className = "create-head";2558    const back = document.createElement("button");2559    back.className = "back-btn";2560    back.type = "button";2561    back.title = "Cancel";2562    back.innerHTML = `<svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M7 2L3 5.5L7 9"/></svg>`;2563    back.addEventListener("click", () => renderSilverPlatter(summary));2564    head.appendChild(back);2565    const headLbl = document.createElement("div");2566    headLbl.className = "create-label";2567    headLbl.textContent = "Edit entry";2568    head.appendChild(headLbl);2569    wrap.appendChild(head);25702571    const body = document.createElement("div");2572    body.className = "create-body";25732574    // Loading shimmer while we fetch the full entry2575    const loading = document.createElement("div");2576    loading.className = "empty-hint";2577    loading.textContent = "loading…";2578    body.appendChild(loading);2579    wrap.appendChild(body);2580    container.appendChild(wrap);25812582    const [res, idRes] = await Promise.all([2583      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2584      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2585      chrome.runtime.sendMessage({2586        type: "GET_ENTRY_FOR_EDIT",2587        payload: { id: summary.id },2588      }).catch(() => null),2589      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2590    ]);2591    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2592    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];25932594    if (!entryRes || !entryRes.ok || !entryRes.data) {2595      loading.textContent = "couldn't load this entry. try again from the popup.";2596      return;2597    }2598    body.innerHTML = "";25992600    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2601      const group = document.createElement("div");2602      group.className = "f-group";2603      const lbl = document.createElement("div");2604      lbl.className = "f-label";2605      lbl.textContent = label;2606      const input = document.createElement("input");2607      input.className = "f-input";2608      input.type = type;2609      input.value = value;2610      input.autocomplete = "off";2611      group.append(lbl, input);2612      body.appendChild(group);2613      return { g: group, inp: input };2614    }26152616    const titleInput = field("title", entryRes.data.title ?? "").inp;2617    const urlInput = field("url", entryRes.data.url ?? "").inp;2618    urlInput.classList.add("url-f");2619    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2620    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2621    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2622    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2623    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");26242625    // Password row with reveal toggle + generator2626    const pwGroup = document.createElement("div");2627    pwGroup.className = "f-group";2628    const pwLbl = document.createElement("div");2629    pwLbl.className = "f-label";2630    pwLbl.textContent = "password";2631    const pwRow = document.createElement("div");2632    pwRow.className = "f-row";2633    const pwInput = document.createElement("input");2634    pwInput.className = "f-input";2635    pwInput.type = "password";2636    pwInput.value = entryRes.data.password ?? "";2637    pwInput.autocomplete = "new-password";2638    const revealBtn = document.createElement("button");2639    revealBtn.className = "gen-btn";2640    revealBtn.type = "button";2641    revealBtn.textContent = "show";2642    revealBtn.addEventListener("click", () => {2643      const reveal = pwInput.type === "password";2644      pwInput.type = reveal ? "text" : "password";2645      revealBtn.textContent = reveal ? "hide" : "show";2646    });2647    pwRow.append(pwInput, revealBtn);2648    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2649    editSmartGen.root.style.display = "none";2650    let editGenVisible = false;2651    const genToggleBtn = document.createElement("button");2652    genToggleBtn.className = "gen-toggle-link";2653    genToggleBtn.type = "button";2654    genToggleBtn.textContent = "⚙ generate";2655    genToggleBtn.addEventListener("click", () => {2656      editGenVisible = !editGenVisible;2657      pwRow.style.display = editGenVisible ? "none" : "";2658      editSmartGen.root.style.display = editGenVisible ? "" : "none";2659      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2660    });2661    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2662    body.appendChild(pwGroup);26632664    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;26652666    // Notes2667    const notesGroup = document.createElement("div");2668    notesGroup.className = "f-group";2669    const notesLbl = document.createElement("div");2670    notesLbl.className = "f-label";2671    notesLbl.textContent = "notes";2672    const notesInput = document.createElement("textarea");2673    notesInput.className = "f-input";2674    notesInput.rows = 3;2675    notesInput.value = entryRes.data.notes ?? "";2676    notesInput.style.fontFamily = "Inter, sans-serif";2677    notesInput.style.resize = "vertical";2678    notesGroup.append(notesLbl, notesInput);2679    body.appendChild(notesGroup);26802681    // Save / Cancel row2682    const actionsRow = document.createElement("div");2683    actionsRow.className = "f-row";2684    const saveBtn = document.createElement("button");2685    saveBtn.className = "save-btn";2686    saveBtn.type = "button";2687    saveBtn.textContent = "Save changes";2688    saveBtn.style.flex = "1";2689    const cancelBtn = document.createElement("button");2690    cancelBtn.className = "gen-btn";2691    cancelBtn.type = "button";2692    cancelBtn.textContent = "cancel";2693    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2694    actionsRow.append(saveBtn, cancelBtn);2695    body.appendChild(actionsRow);26962697    saveBtn.addEventListener("click", async () => {2698      saveBtn.disabled = true;2699      const originalLabel = saveBtn.textContent;2700      saveBtn.textContent = "Saving…";2701      const patch: Record<string, unknown> = {2702        title: titleInput.value.trim(),2703        url: urlInput.value.trim(),2704        username: usernameInput.value.trim(),2705        email: emailInput.value.trim() || undefined,2706        password: pwInput.value,2707        totp: totpInput.value.trim(),2708        notes: notesInput.value,2709      };2710      const updateRes = (await chrome.runtime.sendMessage({2711        type: "UPDATE_ENTRY",2712        payload: { id: summary.id, patch },2713      }).catch(() => null)) as { ok: boolean; error?: string } | null;2714      if (!updateRes?.ok) {2715        saveBtn.disabled = false;2716        saveBtn.textContent = originalLabel;2717        const err = document.createElement("div");2718        err.className = "empty-hint";2719        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2720        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2721        body.appendChild(err);2722        setTimeout(() => err.remove(), 3000);2723        return;2724      }2725      // Refresh the platter with updated summary fields2726      const refreshed: SelectorEntry = {2727        id: summary.id,2728        title: patch.title as string,2729        username: patch.username as string,2730        email: patch.email as string | undefined,2731        url: patch.url as string,2732        hasTotp: Boolean(patch.totp),2733        hasPasskey: summary.hasPasskey,2734      };2735      renderSilverPlatter(refreshed);2736    });27372738    queueMicrotask(() => titleInput.focus());2739  }27402741  function renderLocked() {2742    container.innerHTML = "";27432744    // Domain header (same as list view)2745    const domHdr = document.createElement("div");2746    domHdr.className = "domain-header";2747    const eyebrow = document.createElement("div");2748    eyebrow.className = "domain-eyebrow";2749    eyebrow.textContent = "vault locked";2750    const domName = document.createElement("div");2751    domName.className = "domain-name";2752    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2753    domHdr.append(eyebrow, domName);2754    container.appendChild(domHdr);27552756    const wrap = document.createElement("div");2757    wrap.className = "locked-wrap";27582759    // Icon + label row2760    const head = document.createElement("div"); head.className = "locked-head";2761    const icon = document.createElement("div"); icon.className = "locked-icon";2762    icon.innerHTML = keySvgStr();2763    const title = document.createElement("div"); title.className = "locked-title";2764    title.textContent = "unlock to autofill";2765    head.append(icon, title);27662767    // The master password is NEVER collected in page-hosted DOM. A malicious2768    // page can observe keystrokes on the shared DOM event stream (a capture-2769    // phase listener registered before Peach injects sees every key before any2770    // stopImmediatePropagation), which would leak the vault's root secret2771    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2772    // where keystrokes are isolated from the page. After the user unlocks2773    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2774    // automatically (see content/index.ts), so the flow resumes on its own.2775    const sub = document.createElement("div");2776    sub.className = "locked-sub";2777    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";27782779    const openBtn = document.createElement("button");2780    openBtn.className = "locked-btn";2781    openBtn.type = "button";2782    openBtn.textContent = "Open Peach to unlock";2783    openBtn.addEventListener("click", () => {2784      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2785      openBtn.textContent = "opening Peach…";2786      openBtn.disabled = true;2787      // openPopup() can't always open programmatically (browser/version/gesture2788      // limits); reset so the user can retry or click the toolbar icon.2789      setTimeout(() => {2790        if (openBtn.isConnected) {2791          openBtn.textContent = "Open Peach to unlock";2792          openBtn.disabled = false;2793        }2794      }, 2500);2795    });27962797    wrap.append(head, sub, openBtn);2798    container.appendChild(wrap);2799  }28002801  function handleKeyDown(e: KeyboardEvent) {2802    if (options.locked) {2803      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2804      return;2805    }2806    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper") {2807      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2808      return;2809    }2810    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2811    const count = allEntryEls.length;2812    const activeElement = shadow.activeElement ?? document.activeElement;2813    if (activeElement === searchInput) {2814      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2815      if (count === 0) return;2816      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2817    }2818    if (count === 0) return;2819    switch (e.key) {2820      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2821      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2822      case "Enter": {2823        if (focusedIndex >= 0) {2824          const el = allEntryEls[focusedIndex] as HTMLElement;2825          const id = el.dataset.id;2826          if (id) { onSelect(id); dismiss(); }2827          else if (el.classList.contains("is-new") || !id) {2828            // "New entry" row (last item, no data-id)2829            showCreateForm();2830          }2831        }2832        break;2833      }2834      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2835    }2836  }28372838  document.addEventListener("keydown", handleKeyDown);28392840  // Type-to-search from the silver platter. A printable single-character2841  // keystroke (no modifier) seeds the search query and switches into the2842  // list view, so the user can pivot to a different entry without first2843  // clicking the search icon. Capture phase so the anchor input does not2844  // receive the character before we hijack it.2845  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2846    if (currentMode !== "silver-platter") return;2847    if (e.ctrlKey || e.metaKey || e.altKey) return;2848    if (e.key.length !== 1) return;2849    e.preventDefault();2850    e.stopImmediatePropagation();2851    query = e.key;2852    renderList();2853  };2854  document.addEventListener("keydown", silverPlatterTypeHandler, true);2855  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));28562857  const identityHelperTypeHandler = (e: KeyboardEvent) => {2858    if (currentMode !== "identity-helper") return;2859    if (e.ctrlKey || e.metaKey || e.altKey) return;2860    const active = (shadow.activeElement ?? document.activeElement) as Element | null;2861    if (active === searchInput) return;2862    if (2863      active instanceof HTMLInputElement ||2864      active instanceof HTMLTextAreaElement ||2865      (active instanceof HTMLElement && active.isContentEditable)2866    ) {2867      return;2868    }2869    if (e.key.length !== 1) return;2870    e.preventDefault();2871    e.stopImmediatePropagation();2872    query = e.key;2873    renderIdentityHelper();2874  };2875  document.addEventListener("keydown", identityHelperTypeHandler, true);2876  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));28772878  (modalAncestor ?? document.body).appendChild(host);28792880  // position:fixed normally resolves to the viewport, but an ancestor with2881  // transform / filter / backdrop-filter / perspective / contain / will-change2882  // establishes a containing block, so "fixed" then resolves to that ancestor's2883  // padding box instead. When the host is mounted inside such an ancestor (a2884  // modal) we subtract its border-box origin so the popup still lands at the2885  // field's true viewport position. At the document root there is no such2886  // ancestor and the offset is zero.2887  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {2888    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };2889    return (2890      has("transform") || has("perspective") || has("translate") ||2891      has("rotate") || has("scale") || has("filter") ||2892      has("backdrop-filter") || has("-webkit-backdrop-filter") ||2893      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||2894      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))2895    );2896  }2897  function containingBlockOffset(): { dx: number; dy: number } {2898    let el: HTMLElement | null = host.parentElement;2899    while (el && el !== document.documentElement) {2900      const s = getComputedStyle(el);2901      if (establishesFixedContainingBlock(s)) {2902        const r = el.getBoundingClientRect();2903        return {2904          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),2905          dy: r.top + (parseFloat(s.borderTopWidth) || 0),2906        };2907      }2908      el = el.parentElement;2909    }2910    return { dx: 0, dy: 0 };2911  }29122913  function updatePosition() {2914    const r = anchorEl.getBoundingClientRect();2915    const { dx, dy } = containingBlockOffset();2916    host.style.top = `${r.bottom - dy + 5}px`;2917    host.style.left = `${r.left - dx}px`;2918    host.style.width = `${popupWidth}px`;2919  }2920  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);2921  updatePosition();29222923  if (options.locked) {2924    renderLocked();2925  } else if (options.isSignup && options.savedIdentities) {2926    // State 10: identity helper — signup form detected, show derived2927    // identity list (emails then usernames) instead of vault entry list.2928    renderIdentityHelper();2929  } else if (entries.length === 1 && !options.isSignup) {2930    // Silver platter (State 1): single domain match → focused fill view.2931    // Multi-match goes through renderList instead.2932    renderSilverPlatter(entries[0]!);2933  } else {2934    renderList();2935  }29362937  let exitScheduled = false;2938  function dismiss(userAction = false) {2939    // Idempotent: dismiss() can be called from multiple paths (Escape,2940    // outside click, entry select, fill success, host page nav). The exit2941    // animation must only play once and host.remove() must run exactly once.2942    if (exitScheduled) return;2943    exitScheduled = true;2944    // Detach listeners synchronously so nothing can re-trigger during the2945    // 130ms exit window (a focusin firing here would race against the2946    // dismiss-lock work in Pass 2).2947    stopObserving();2948    document.removeEventListener("click", outsideClick, { capture: true });2949    document.removeEventListener("keydown", handleKeyDown);2950    for (const cleanup of cleanupHooks) {2951      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2952    }2953    if (userAction) options.onDismiss?.();2954    container.classList.add("is-exiting");2955    setTimeout(() => host.remove(), 130);2956  }29572958  function outsideClick(ev: MouseEvent) {2959    const path = ev.composedPath();2960    // Never dismiss when clicking the anchor field itself — that click is2961    // what triggered the selector to open, and the user may click the field2962    // again to re-focus it without intending to close the selector.2963    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2964  }2965  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2966  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);29672968  return dismiss;2969}29702971export function showTOTPSelector(2972  anchorEl: HTMLInputElement,2973  entries: SelectorEntry[],2974  onFill: (id: string) => void,2975  options: { domain?: string; onDismiss?: () => void } = {}2976): () => void {2977  const host = document.createElement("div");2978  host.style.cssText = "position: absolute; z-index: 2147483647;";2979  host.style.setProperty("--peach-accent", accentHex);2980  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2981  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2982  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2983  const shadow = host.attachShadow({ mode: "closed" });29842985  const style = shadow.appendChild(document.createElement("style"));2986  style.textContent = SELECTOR_STYLES;29872988  const rect = anchorEl.getBoundingClientRect();2989  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2990  host.style.left = `${rect.left + window.scrollX}px`;2991  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2992  host.style.width = `${popupWidth}px`;29932994  const container = shadow.appendChild(document.createElement("div"));2995  container.className = "peach-inline-popup";2996  container.setAttribute("data-theme", popupTheme);29972998  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2999  const current = entries.filter((entry) => entry.hasTotp);3000  let focusedIndex = current.length === 1 ? 0 : -1;30013002  function updatePosition() {3003    const r = anchorEl.getBoundingClientRect();3004    host.style.top = `${r.bottom + window.scrollY + 5}px`;3005    host.style.left = `${r.left + window.scrollX}px`;3006    host.style.width = `${popupWidth}px`;3007  }30083009  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);30103011  function choose(entry: SelectorEntry) {3012    onFill(entry.id);3013    dismiss();3014  }30153016  function render() {3017    container.innerHTML = "";30183019    const domHdr = document.createElement("div");3020    domHdr.className = "domain-header";3021    const headText = document.createElement("div");3022    headText.className = "domain-header-text";3023    const eyebrow = document.createElement("div");3024    eyebrow.className = "domain-eyebrow";3025    eyebrow.textContent = "2FA code";3026    const domName = document.createElement("div");3027    domName.className = "domain-name";3028    domName.textContent = domain;3029    headText.append(eyebrow, domName);3030    domHdr.appendChild(headText);3031    container.appendChild(domHdr);30323033    if (current.length === 1) {3034      const entry = current[0]!;3035      const platter = document.createElement("div");3036      platter.className = "silver-platter";30373038      const title = document.createElement("div");3039      title.className = "sp-title";3040      title.textContent = entry.title;3041      platter.appendChild(title);30423043      const sub = document.createElement("div");3044      sub.className = "sp-username";3045      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3046      platter.appendChild(sub);30473048      const fill = document.createElement("button");3049      fill.className = "sp-fill-btn";3050      fill.type = "button";3051      fill.textContent = "Fill 2FA code";3052      fill.addEventListener("click", () => choose(entry));3053      platter.appendChild(fill);30543055      container.appendChild(platter);3056      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3057      return;3058    }30593060    const results = document.createElement("div");3061    results.className = "results";3062    container.appendChild(results);30633064    for (let i = 0; i < current.length; i++) {3065      const entry = current[i]!;3066      const row = document.createElement("div");3067      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3068      row.dataset.index = String(i);3069      row.setAttribute("tabindex", "-1");30703071      const icon = document.createElement("div");3072      icon.className = "entry-icon";3073      icon.innerHTML = keySvgStr();3074      row.appendChild(icon);3075      const info = document.createElement("div");3076      info.className = "entry-info";3077      const title = document.createElement("div");3078      title.className = "entry-title";3079      title.textContent = entry.title;3080      const sub = document.createElement("div");3081      sub.className = "entry-sub";3082      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3083      info.append(title, sub);3084      row.appendChild(info);30853086      const badge = document.createElement("span");3087      badge.className = "totp-badge";3088      badge.textContent = "Fill";3089      row.appendChild(badge);3090      row.addEventListener("click", () => choose(entry));3091      results.appendChild(row);3092    }3093  }30943095  function setFocused(index: number) {3096    focusedIndex = index;3097    container.querySelectorAll(".entry").forEach((el, i) => {3098      el.classList.toggle("focused", i === focusedIndex);3099      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3100    });3101  }31023103  function handleKeyDown(e: KeyboardEvent) {3104    if (e.key === "Escape" || e.key === "Tab") {3105      e.preventDefault();3106      dismiss(true);3107      return;3108    }3109    if (current.length === 0) return;3110    if (e.key === "Enter") {3111      e.preventDefault();3112      choose(current[Math.max(0, focusedIndex)]!);3113      return;3114    }3115    if (current.length === 1) return;3116    if (e.key === "ArrowDown") {3117      e.preventDefault();3118      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3119    } else if (e.key === "ArrowUp") {3120      e.preventDefault();3121      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3122    }3123  }31243125  let exitScheduled = false;3126  function dismiss(userAction = false) {3127    if (exitScheduled) return;3128    exitScheduled = true;3129    stopObserving();3130    document.removeEventListener("click", outsideClick, { capture: true });3131    document.removeEventListener("keydown", handleKeyDown);3132    if (userAction) options.onDismiss?.();3133    container.classList.add("is-exiting");3134    setTimeout(() => host.remove(), 130);3135  }31363137  function outsideClick(ev: MouseEvent) {3138    const path = ev.composedPath();3139    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3140  }31413142  document.addEventListener("keydown", handleKeyDown);3143  document.body.appendChild(host);3144  render();3145  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);31463147  return dismiss;3148}31493150export interface CardSelectorEntry {3151  id: string;3152  title: string;3153  cardholderName?: string;3154  last4?: string;3155  expMonth?: string;3156  expYear?: string;3157  network?: import("../shared/types").CardNetwork;3158}31593160interface CardSelectorOptions {3161  domain?: string;3162  /** Caller-provided fill — receives the full CardEntry payload from the SW. */3163  onFill: (entry: import("../shared/types").VaultEntry) => void;3164  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3165  onDismiss?: () => void;3166}31673168/**3169 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3170 * passkey create or get. Renders as a fixed-position floating popup (no3171 * field anchor needed — passkeys don't require a focused input). Uses the3172 * same theme tokens and entrance animation as all other inline popup states.3173 */3174export function showPasskeyProGate(): void {3175  const domain = location.hostname.replace(/^www\./, "");31763177  const host = document.createElement("div");3178  host.setAttribute("data-peach-passkey-gate", "1");3179  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3180  const shadow = host.attachShadow({ mode: "closed" });31813182  const style = document.createElement("style");3183  style.textContent = `3184    :host { all: initial; }3185    .gate-wrap {3186      position: fixed;3187      top: 50%;3188      left: 50%;3189      transform: translate(-50%, -50%);3190      width: 280px;3191      pointer-events: auto;3192      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3193    }3194    @keyframes g-in {3195      from { opacity:0; transform: translate(-50%,-52%); }3196      to   { opacity:1; transform: translate(-50%,-50%); }3197    }3198    .gate-wrap.is-exiting {3199      animation: g-out 130ms ease-in forwards;3200    }3201    @keyframes g-out {3202      to { opacity:0; transform: translate(-50%,-52%); }3203    }3204    .gate {3205      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3206      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3207      border-radius: 12px;3208      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3209      padding: 16px;3210      font-family: Inter, sans-serif;3211    }3212    .gate-header {3213      display: flex;3214      align-items: center;3215      gap: 7px;3216      margin-bottom: 12px;3217      padding-bottom: 10px;3218      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3219    }3220    .gate-domain {3221      font-size: 12px;3222      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3223      font-family: "IBM Plex Mono", monospace;3224      overflow: hidden;3225      text-overflow: ellipsis;3226      white-space: nowrap;3227    }3228    .gate-title {3229      font-size: 14px;3230      font-weight: 500;3231      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3232      margin-bottom: 6px;3233    }3234    .gate-subtitle {3235      font-size: 12px;3236      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3237      line-height: 1.5;3238      margin-bottom: 14px;3239    }3240    .gate-btn {3241      display: block;3242      width: 100%;3243      padding: 9px 0;3244      border-radius: 8px;3245      border: none;3246      cursor: pointer;3247      font-size: 13px;3248      font-family: Inter, sans-serif;3249      font-weight: 500;3250      transition: opacity 100ms;3251      margin-bottom: 7px;3252      text-align: center;3253    }3254    .gate-btn:last-child { margin-bottom: 0; }3255    .gate-btn--accent {3256      background: ${accentHex};3257      color: #fff;3258    }3259    .gate-btn--accent:hover { opacity: 0.88; }3260    .gate-btn--ghost {3261      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3262      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3263    }3264    .gate-btn--ghost:hover { opacity: 0.75; }3265    .backdrop {3266      position: fixed;3267      inset: 0;3268      pointer-events: auto;3269    }3270  `;3271  shadow.appendChild(style);32723273  const backdrop = document.createElement("div");3274  backdrop.className = "backdrop";3275  shadow.appendChild(backdrop);32763277  const wrap = document.createElement("div");3278  wrap.className = "gate-wrap";3279  shadow.appendChild(wrap);32803281  const gate = document.createElement("div");3282  gate.className = "gate";3283  wrap.appendChild(gate);32843285  // Header: peach icon + domain3286  const header = document.createElement("div");3287  header.className = "gate-header";3288  const icon = document.createElement("span");3289  icon.innerHTML = peachIconSvg();3290  const domainEl = document.createElement("span");3291  domainEl.className = "gate-domain";3292  domainEl.textContent = domain;3293  header.append(icon, domainEl);3294  gate.appendChild(header);32953296  const title = document.createElement("div");3297  title.className = "gate-title";3298  title.textContent = "Passkeys are part of Peach Pro.";3299  gate.appendChild(title);33003301  const subtitle = document.createElement("div");3302  subtitle.className = "gate-subtitle";3303  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3304  gate.appendChild(subtitle);33053306  const upgradeBtn = document.createElement("button");3307  upgradeBtn.className = "gate-btn gate-btn--accent";3308  upgradeBtn.type = "button";3309  upgradeBtn.textContent = "Upgrade to Pro";3310  gate.appendChild(upgradeBtn);33113312  const laterBtn = document.createElement("button");3313  laterBtn.className = "gate-btn gate-btn--ghost";3314  laterBtn.type = "button";3315  laterBtn.textContent = "Not right now";3316  gate.appendChild(laterBtn);33173318  function dismiss() {3319    wrap.classList.add("is-exiting");3320    setTimeout(() => host.remove(), 130);3321  }33223323  upgradeBtn.addEventListener("click", () => {3324    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3325    dismiss();3326  });3327  laterBtn.addEventListener("click", dismiss);3328  backdrop.addEventListener("click", dismiss);33293330  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3331    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3332  });33333334  document.body.appendChild(host);3335}33363337/**3338 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3339 * detector sees the page invoke navigator.credentials.create(); content/index.ts3340 * checks vault + decline state then calls this. "Save passkey to Peach"3341 * initiates the popup-context credential flow; "Not now" records a 30-day3342 * decline for the domain so we don't re-show on every page reload.3343 */3344export function showPasskeyRegistrationOffer(args: {3345  rpId: string;3346  rpName?: string;3347  userName?: string;3348  userDisplayName?: string;3349}): void {3350  const domain = location.hostname.replace(/^www\./, "");3351  const displayName = args.rpName || domain;33523353  const host = document.createElement("div");3354  host.setAttribute("data-peach-passkey-offer", "1");3355  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3356  const shadow = host.attachShadow({ mode: "closed" });33573358  const style = document.createElement("style");3359  style.textContent = `3360    :host { all: initial; }3361    .offer-wrap {3362      position: fixed;3363      top: 16px;3364      right: 16px;3365      width: 320px;3366      pointer-events: auto;3367      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3368    }3369    @keyframes o-in {3370      from { opacity: 0; transform: translateY(-6px); }3371      to   { opacity: 1; transform: translateY(0); }3372    }3373    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3374    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3375    .offer {3376      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3377      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3378      border-radius: 12px;3379      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3380      padding: 14px 14px 12px;3381      font-family: Inter, sans-serif;3382      position: relative;3383    }3384    .offer-close {3385      position: absolute;3386      top: 8px;3387      right: 8px;3388      width: 18px;3389      height: 18px;3390      border: none;3391      background: transparent;3392      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3393      cursor: pointer;3394      font-size: 14px;3395      line-height: 1;3396      padding: 0;3397    }3398    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3399    .offer-header {3400      display: flex;3401      align-items: center;3402      gap: 7px;3403      margin-bottom: 8px;3404      padding-bottom: 8px;3405      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3406    }3407    .offer-domain {3408      font-size: 12px;3409      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3410      font-family: "IBM Plex Mono", monospace;3411      overflow: hidden;3412      text-overflow: ellipsis;3413      white-space: nowrap;3414    }3415    .offer-title {3416      font-size: 13px;3417      font-weight: 500;3418      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3419      margin-bottom: 4px;3420    }3421    .offer-subtitle {3422      font-size: 11px;3423      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3424      line-height: 1.45;3425      margin-bottom: 12px;3426    }3427    .offer-btn {3428      display: block;3429      width: 100%;3430      padding: 8px 0;3431      border-radius: 7px;3432      border: none;3433      cursor: pointer;3434      font-size: 12px;3435      font-family: Inter, sans-serif;3436      font-weight: 500;3437      transition: opacity 100ms;3438      margin-bottom: 6px;3439      text-align: center;3440    }3441    .offer-btn:last-child { margin-bottom: 0; }3442    .offer-btn--accent { background: ${accentHex}; color: #fff; }3443    .offer-btn--accent:hover { opacity: 0.88; }3444    .offer-btn--ghost {3445      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3446      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3447    }3448    .offer-btn--ghost:hover { opacity: 0.75; }3449  `;3450  shadow.appendChild(style);34513452  const wrap = document.createElement("div");3453  wrap.className = "offer-wrap";3454  shadow.appendChild(wrap);34553456  const offer = document.createElement("div");3457  offer.className = "offer";3458  wrap.appendChild(offer);34593460  const closeBtn = document.createElement("button");3461  closeBtn.className = "offer-close";3462  closeBtn.type = "button";3463  closeBtn.setAttribute("aria-label", "Dismiss");3464  closeBtn.textContent = "✕";3465  offer.appendChild(closeBtn);34663467  const header = document.createElement("div");3468  header.className = "offer-header";3469  const icon = document.createElement("span");3470  icon.innerHTML = peachIconSvg();3471  const domainEl = document.createElement("span");3472  domainEl.className = "offer-domain";3473  domainEl.textContent = domain;3474  header.append(icon, domainEl);3475  offer.appendChild(header);34763477  const title = document.createElement("div");3478  title.className = "offer-title";3479  title.textContent = "This site supports passkeys.";3480  offer.appendChild(title);34813482  const subtitle = document.createElement("div");3483  subtitle.className = "offer-subtitle";3484  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3485  offer.appendChild(subtitle);34863487  const saveBtn = document.createElement("button");3488  saveBtn.className = "offer-btn offer-btn--accent";3489  saveBtn.type = "button";3490  saveBtn.textContent = "Save passkey to Peach";3491  offer.appendChild(saveBtn);34923493  const laterBtn = document.createElement("button");3494  laterBtn.className = "offer-btn offer-btn--ghost";3495  laterBtn.type = "button";3496  laterBtn.textContent = "Not now";3497  offer.appendChild(laterBtn);34983499  function dismiss(decline: boolean) {3500    if (decline) {3501      chrome.runtime.sendMessage({3502        type: "PASSKEY_OFFER_DECLINE",3503        payload: { domain },3504      }).catch(() => {});3505    }3506    wrap.classList.add("is-exiting");3507    setTimeout(() => host.remove(), 130);3508  }35093510  saveBtn.addEventListener("click", () => {3511    chrome.runtime.sendMessage({3512      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3513      payload: {3514        rpId: args.rpId,3515        rpName: args.rpName ?? displayName,3516        userName: args.userName ?? "user",3517        userDisplayName: args.userDisplayName,3518      },3519    }).catch(() => {});3520    dismiss(false);3521  });3522  laterBtn.addEventListener("click", () => dismiss(true));3523  closeBtn.addEventListener("click", () => dismiss(true));35243525  document.body.appendChild(host);3526}35273528/**3529 * State 11 — passkey available indicator. Shown when the user lands on a3530 * domain for which they already have a stored passkey. Tells them where to3531 * find it (the entry already shows in the vault list); the "Sign in with3532 * passkey" button opens the popup so they can use the platform authenticator3533 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3534 * the actual sign-in transparently, so this banner is informational only.3535 */3536export function showPasskeyAvailable(args: {3537  rpId: string;3538  userName: string;3539  fromBrowser?: "chrome" | "firefox";3540  currentBrowser?: "chrome" | "firefox" | "unknown";3541}): void {3542  const domain = location.hostname.replace(/^www\./, "");3543  const crossBrowser =3544    args.fromBrowser &&3545    args.currentBrowser &&3546    args.currentBrowser !== "unknown" &&3547    args.fromBrowser !== args.currentBrowser;35483549  const host = document.createElement("div");3550  host.setAttribute("data-peach-passkey-available", "1");3551  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3552  const shadow = host.attachShadow({ mode: "closed" });35533554  const style = document.createElement("style");3555  style.textContent = `3556    :host { all: initial; }3557    .avail-wrap {3558      position: fixed;3559      top: 16px;3560      right: 16px;3561      width: 320px;3562      pointer-events: auto;3563      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3564    }3565    @keyframes a-in {3566      from { opacity: 0; transform: translateY(-6px); }3567      to   { opacity: 1; transform: translateY(0); }3568    }3569    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3570    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3571    .avail {3572      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3573      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3574      border-radius: 12px;3575      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3576      padding: 14px 14px 12px;3577      font-family: Inter, sans-serif;3578      position: relative;3579    }3580    .avail-close {3581      position: absolute;3582      top: 8px;3583      right: 8px;3584      width: 18px;3585      height: 18px;3586      border: none;3587      background: transparent;3588      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3589      cursor: pointer;3590      font-size: 14px;3591      line-height: 1;3592      padding: 0;3593    }3594    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3595    .avail-header {3596      display: flex;3597      align-items: center;3598      gap: 7px;3599      margin-bottom: 8px;3600      padding-bottom: 8px;3601      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3602    }3603    .avail-domain {3604      font-size: 12px;3605      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3606      font-family: "IBM Plex Mono", monospace;3607    }3608    .avail-label {3609      font-size: 9px;3610      letter-spacing: 0.16em;3611      text-transform: uppercase;3612      color: ${accentHex};3613      margin-bottom: 4px;3614    }3615    .avail-user {3616      font-size: 13px;3617      font-weight: 500;3618      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3619      margin-bottom: 12px;3620      overflow: hidden;3621      text-overflow: ellipsis;3622      white-space: nowrap;3623    }3624    .avail-cross {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      padding: 8px;3630      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3631      border-radius: 6px;3632    }3633    .avail-btn {3634      display: block;3635      width: 100%;3636      padding: 8px 0;3637      border-radius: 7px;3638      border: none;3639      cursor: pointer;3640      font-size: 12px;3641      font-family: Inter, sans-serif;3642      font-weight: 500;3643      transition: opacity 100ms;3644      margin-bottom: 6px;3645      text-align: center;3646    }3647    .avail-btn:last-child { margin-bottom: 0; }3648    .avail-btn--accent { background: ${accentHex}; color: #fff; }3649    .avail-btn--accent:hover { opacity: 0.88; }3650    .avail-btn--ghost {3651      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3652      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3653    }3654    .avail-btn--ghost:hover { opacity: 0.75; }3655  `;3656  shadow.appendChild(style);36573658  const wrap = document.createElement("div");3659  wrap.className = "avail-wrap";3660  shadow.appendChild(wrap);36613662  const avail = document.createElement("div");3663  avail.className = "avail";3664  wrap.appendChild(avail);36653666  const closeBtn = document.createElement("button");3667  closeBtn.className = "avail-close";3668  closeBtn.type = "button";3669  closeBtn.setAttribute("aria-label", "Dismiss");3670  closeBtn.textContent = "✕";3671  avail.appendChild(closeBtn);36723673  const header = document.createElement("div");3674  header.className = "avail-header";3675  const icon = document.createElement("span");3676  icon.innerHTML = peachIconSvg();3677  const domainEl = document.createElement("span");3678  domainEl.className = "avail-domain";3679  domainEl.textContent = domain;3680  header.append(icon, domainEl);3681  avail.appendChild(header);36823683  const label = document.createElement("div");3684  label.className = "avail-label";3685  label.textContent = "PASSKEY";3686  avail.appendChild(label);36873688  const user = document.createElement("div");3689  user.className = "avail-user";3690  user.textContent = args.userName;3691  avail.appendChild(user);36923693  if (crossBrowser) {3694    const cross = document.createElement("div");3695    cross.className = "avail-cross";3696    cross.textContent =3697      args.fromBrowser === "chrome"3698        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3699        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3700    avail.appendChild(cross);3701  }37023703  const signInBtn = document.createElement("button");3704  signInBtn.className = "avail-btn avail-btn--accent";3705  signInBtn.type = "button";3706  signInBtn.textContent = "Sign in with passkey";3707  avail.appendChild(signInBtn);37083709  const passwordBtn = document.createElement("button");3710  passwordBtn.className = "avail-btn avail-btn--ghost";3711  passwordBtn.type = "button";3712  passwordBtn.textContent = "Use password instead";3713  avail.appendChild(passwordBtn);37143715  function dismiss() {3716    wrap.classList.add("is-exiting");3717    setTimeout(() => host.remove(), 130);3718  }37193720  signInBtn.addEventListener("click", () => {3721    // On Chrome: the user clicking the page's own Sign-in button is what3722    //   triggers webAuthenticationProxy → existing background flow handles it.3723    //   Our button just dismisses since the page itself drives auth.3724    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3725    //   and surface the entry for manual reference (popup view).3726    dismiss();3727    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3728  });3729  passwordBtn.addEventListener("click", dismiss);3730  closeBtn.addEventListener("click", dismiss);37313732  document.body.appendChild(host);3733}37343735/**3736 * State 7 — card silver platter. Single-card focused fill view rendered3737 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3738 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3739 * so card and login flows render identically. Multi-card list view is a3740 * follow-up; today this picks the first card.3741 */3742export function showCardSelector(3743  anchorEl: HTMLInputElement,3744  cards: CardSelectorEntry[],3745  options: CardSelectorOptions3746): () => void {3747  if (cards.length === 0) return () => {};3748  const card = cards[0]!;37493750  const host = document.createElement("div");3751  host.style.cssText = "position: absolute; z-index: 2147483647;";3752  host.style.setProperty("--peach-accent", accentHex);3753  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3754  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3755  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3756  const shadow = host.attachShadow({ mode: "closed" });37573758  const style = shadow.appendChild(document.createElement("style"));3759  style.textContent = SELECTOR_STYLES;37603761  const rect = anchorEl.getBoundingClientRect();3762  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3763  host.style.left = `${rect.left + window.scrollX}px`;3764  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;37653766  const container = shadow.appendChild(document.createElement("div"));3767  container.className = "peach-inline-popup";3768  container.setAttribute("data-theme", popupTheme);37693770  // Domain header — eyebrow communicates the card context, not the site3771  const domHdr = document.createElement("div");3772  domHdr.className = "domain-header";3773  const eyebrow = document.createElement("div");3774  eyebrow.className = "domain-eyebrow";3775  eyebrow.textContent = "Pay with Peach";3776  const domName = document.createElement("div");3777  domName.className = "domain-name";3778  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3779  domHdr.append(eyebrow, domName);3780  container.appendChild(domHdr);37813782  const platter = document.createElement("div");3783  platter.className = "card-platter";37843785  if (card.network && card.network !== "unknown") {3786    const net = document.createElement("div");3787    net.className = "cp-network";3788    net.textContent = card.network;3789    platter.appendChild(net);3790  }37913792  const nick = document.createElement("div");3793  nick.className = "cp-nickname";3794  nick.textContent = card.title;3795  platter.appendChild(nick);37963797  if (card.last4) {3798    const l4 = document.createElement("div");3799    l4.className = "cp-last4";3800    l4.textContent = `•••• ${card.last4}`;3801    platter.appendChild(l4);3802  }38033804  const meta = document.createElement("div");3805  meta.className = "cp-meta";3806  if (card.cardholderName) {3807    const name = document.createElement("span");3808    name.textContent = card.cardholderName;3809    meta.appendChild(name);3810  }3811  if (card.expMonth && card.expYear) {3812    if (card.cardholderName) {3813      const sep = document.createElement("span");3814      sep.className = "cp-meta-sep";3815      sep.textContent = "·";3816      meta.appendChild(sep);3817    }3818    const exp = document.createElement("span");3819    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3820    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3821    meta.appendChild(exp);3822  }3823  if (meta.childElementCount > 0) platter.appendChild(meta);38243825  const fillWrap = document.createElement("div");3826  fillWrap.className = "cp-fill-wrap";3827  const fillBtn = document.createElement("button");3828  fillBtn.className = "sp-fill-btn";3829  fillBtn.type = "button";3830  fillBtn.textContent = "Fill card details";3831  fillBtn.addEventListener("click", async () => {3832    if (fillBtn.disabled) return;3833    fillBtn.disabled = true;3834    fillBtn.classList.add("filled");3835    fillBtn.innerHTML = checkSvgStr();3836    const resp = await chrome.runtime.sendMessage({3837      type: "GET_ENTRY_FOR_FILL",3838      payload: { id: card.id },3839    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3840    if (resp?.ok && resp.data) options.onFill(resp.data);3841    setTimeout(() => dismiss(), 400);3842  });3843  fillWrap.appendChild(fillBtn);3844  platter.appendChild(fillWrap);38453846  // Secondary actions — copy number, copy CVC, dismiss3847  const actions = document.createElement("div");3848  actions.className = "sp-actions";38493850  function flashBtn(b: HTMLButtonElement) {3851    b.classList.add("flashed");3852    setTimeout(() => b.classList.remove("flashed"), 700);3853  }38543855  // M3/QUA-005: clipboard + background COPY both failed — show user.3856  function flashCopyError(b: HTMLButtonElement) {3857    const original = b.textContent ?? "";3858    b.textContent = "Blocked";3859    b.classList.add("flashed");3860    setTimeout(() => {3861      b.classList.remove("flashed");3862      if (b.isConnected) b.textContent = original;3863    }, 1200);3864  }38653866  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3867    const resp = await chrome.runtime.sendMessage({3868      type: "GET_ENTRY_FOR_FILL",3869      payload: { id: card.id },3870    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3871    return resp?.ok && resp.data ? resp.data : null;3872  }38733874  const copyNum = document.createElement("button");3875  copyNum.className = "sp-action-btn";3876  copyNum.type = "button";3877  copyNum.title = "Copy card number";3878  copyNum.textContent = "Copy number";3879  copyNum.addEventListener("click", async (e) => {3880    e.stopPropagation();3881    const full = await fetchFullCard();3882    if (!full?.cardNumber) return;3883    let alreadyWritten = false;3884    try {3885      await navigator.clipboard.writeText(full.cardNumber);3886      alreadyWritten = true;3887    } catch (err) {3888      console.warn("[Peach] clipboard write denied:", err);3889    }3890    const resp = await chrome.runtime.sendMessage({3891      type: "COPY",3892      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3893    }).catch(() => null) as { ok?: boolean } | null;3894    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3895    else flashCopyError(copyNum);3896  });3897  actions.appendChild(copyNum);38983899  const copyCvc = document.createElement("button");3900  copyCvc.className = "sp-action-btn";3901  copyCvc.type = "button";3902  copyCvc.title = "Copy CVC";3903  copyCvc.textContent = "Copy CVC";3904  copyCvc.addEventListener("click", async (e) => {3905    e.stopPropagation();3906    const full = await fetchFullCard();3907    if (!full?.cvc) return;3908    let alreadyWritten = false;3909    try {3910      await navigator.clipboard.writeText(full.cvc);3911      alreadyWritten = true;3912    } catch (err) {3913      console.warn("[Peach] clipboard write denied:", err);3914    }3915    const resp = await chrome.runtime.sendMessage({3916      type: "COPY",3917      payload: { text: full.cvc, label: "CVC", alreadyWritten },3918    }).catch(() => null) as { ok?: boolean } | null;3919    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3920    else flashCopyError(copyCvc);3921  });3922  actions.appendChild(copyCvc);39233924  const closeBtn = document.createElement("button");3925  closeBtn.className = "sp-action-btn";3926  closeBtn.type = "button";3927  closeBtn.title = "Dismiss";3928  closeBtn.textContent = "✕";3929  closeBtn.addEventListener("click", (e) => {3930    e.stopPropagation();3931    dismiss(true);3932  });3933  actions.appendChild(closeBtn);39343935  platter.appendChild(actions);3936  container.appendChild(platter);39373938  document.body.appendChild(host);3939  function updatePosition() {3940    const r = anchorEl.getBoundingClientRect();3941    host.style.top = `${r.bottom + window.scrollY + 5}px`;3942    host.style.left = `${r.left + window.scrollX}px`;3943  }3944  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);39453946  function onKeyDown(e: KeyboardEvent) {3947    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3948  }3949  document.addEventListener("keydown", onKeyDown);39503951  let exitScheduled = false;3952  function dismiss(userAction = false) {3953    if (exitScheduled) return;3954    exitScheduled = true;3955    stopObserving();3956    document.removeEventListener("click", outsideClick, { capture: true });3957    document.removeEventListener("keydown", onKeyDown);3958    if (userAction) options.onDismiss?.();3959    container.classList.add("is-exiting");3960    setTimeout(() => host.remove(), 130);3961  }39623963  function outsideClick(ev: MouseEvent) {3964    const path = ev.composedPath();3965    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3966  }3967  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);39683969  return dismiss;3970}