inject.ts

159.8 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  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1202  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1203  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1204  .identity-filter-pill {1205    padding: 2px 7px; border-radius: 999px;1206    border: 1px solid var(--peach-input-border);1207    background: transparent; color: var(--peach-text-muted);1208    font-family: "IBM Plex Mono", monospace; font-size: 9px;1209    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1210  }1211  .identity-filter-pill.is-on {1212    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1213    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1214    color: var(--peach-accent);1215  }1216  .identity-suggest-row {1217    display: flex; align-items: center; gap: 5px;1218    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1219    background: transparent; cursor: pointer; text-align: left;1220    transition: background 80ms;1221  }1222  .identity-suggest-row:hover,1223  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1224  .identity-suggest-val {1225    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1226    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1227  }1228  .identity-suggest-type {1229    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1230    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1231  }1232  .identity-suggest-type--email {1233    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1234    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1235  }1236  .identity-suggest-type--username {1237    color: var(--peach-text-muted);1238    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1239  }1240  .identity-suggest-meta {1241    font-family: "IBM Plex Mono", monospace; font-size: 9px;1242    color: var(--peach-text-muted); flex-shrink: 0;1243  }1244  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1245  .pwgen-pill {1246    padding: 3px 8px; border-radius: 999px;1247    border: 1px solid var(--peach-input-border);1248    background: transparent; color: var(--peach-text-muted);1249    font-family: "IBM Plex Mono", monospace; font-size: 9px;1250    letter-spacing: 0.06em; cursor: pointer;1251    transition: all 130ms ease;1252  }1253  .pwgen-pill.is-on {1254    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1255    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1256    color: var(--peach-accent);1257  }1258  .pwgen-pill:not(.is-on):hover {1259    color: var(--peach-text-dim);1260    border-color: var(--peach-text-muted);1261  }1262  .pwgen-policy-hint {1263    font-size: 10px; color: var(--peach-text-muted);1264    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1265    line-height: 1.3;1266  }1267  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }12681269  /* ── Save offer (after password filled) ───────────────────── */1270  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1271  .save-offer-title {1272    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1273  }1274  .save-offer-row {1275    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1276    border-radius: 7px; background: var(--peach-input-bg);1277    border: 1px solid var(--peach-input-border);1278  }1279  .save-offer-lbl {1280    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1281    font-family: "IBM Plex Mono", monospace;1282  }1283  .save-offer-val {1284    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1285    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1286  }1287  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1288  .save-offer-save {1289    flex: 1; padding: 9px; border-radius: 8px; border: none;1290    background: var(--peach-accent); color: #fff; font-size: 13px;1291    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1292  }1293  .save-offer-save:hover { filter: brightness(1.08); }1294  .save-offer-skip {1295    flex: 1; padding: 9px; border-radius: 8px; border: none;1296    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1297    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1298    font-family: Inter, sans-serif; transition: background 100ms ease;1299  }1300  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1301`;13021303export function showAutofillSelector(1304  anchorEl: HTMLInputElement,1305  entries: SelectorEntry[],1306  onSelect: (id: string) => void,1307  options: SelectorOptions = {}1308): () => void {1309  const host = document.createElement("div");1310  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1311  // when Peach's internal inputs gain focus, immediately blurring them and closing1312  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1313  // as in-bounds (v3.6.131).1314  //1315  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1316  // A plain login page whose card uses transform/filter/backdrop-filter establishes1317  // a containing block for position:fixed, so a host mounted inside it lands offset1318  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1319  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1320  // the popup ~400px off the field and clipped it behind overflow:clip — the user1321  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1322  // everything else mounts at the document root, where fixed == viewport.1323  const modalAncestor = (1324    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1325    (() => {1326      let cur: HTMLElement | null = anchorEl.parentElement;1327      while (cur && cur !== document.body) {1328        if (window.getComputedStyle(cur).position === 'fixed') return cur;1329        cur = cur.parentElement;1330      }1331      return null;1332    })()1333  );1334  host.style.cssText = `position: fixed; z-index: 2147483647;`;1335  host.style.setProperty("--peach-accent", accentHex);1336  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1337  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1338  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1339  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1340  // HOST appear focused to the outside DOM. Modal focus traps that monitor1341  // focusin then see the host (mounted inside the modal) as the focused element1342  // rather than an opaque closed-shadow node, so they don't fire their1343  // "focus escaped" handler and yank focus back. Harmless outside modals.1344  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });13451346  const style = shadow.appendChild(document.createElement("style"));1347  style.textContent = SELECTOR_STYLES;13481349  const rect = anchorEl.getBoundingClientRect();1350  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1351  // applying containing-block compensation once host.parentElement is known.1352  host.style.top = `${rect.bottom + 5}px`;1353  host.style.left = `${rect.left}px`;1354  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1355  // wide single-input fields (e.g. centered email input on signup pages).1356  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1357  // expand the host after the initial measurement.1358  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1359  host.style.width = `${popupWidth}px`;13601361  const container = shadow.appendChild(document.createElement("div"));1362  container.className = "peach-inline-popup";1363  container.setAttribute("data-theme", popupTheme);13641365  const searchableEntries = options.searchableEntries ?? [];1366  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();13671368  let query = "";1369  let focusedIndex = -1;1370  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" = "list";1371  let searchInput: HTMLInputElement | null = null;1372  let identityMode: IdentityFilterMode = "both";1373  // Tracks the silver-platter entry the user pivoted away from, so the1374  // search/list header can offer a one-click way back to it. null when the1375  // popup never showed a single-match platter (e.g. multi-match list view).1376  let silverPlatterOrigin: SelectorEntry | null = null;1377  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1378  // setInterval. Add to this list — don't fan out the dismiss function.1379  const cleanupHooks: Array<() => void> = [];13801381  // Smooth height transitions whenever content changes height.1382  // ResizeObserver fires on natural height changes; we freeze the old height,1383  // then animate to the new one so the surface never jumps.1384  {1385    let prevH = 0;1386    let blocked = false;1387    const heightRo = new ResizeObserver(([entry]) => {1388      if (blocked) return;1389      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1390      if (prevH > 0 && Math.abs(h - prevH) > 1) {1391        blocked = true;1392        container.style.height = `${prevH}px`;1393        requestAnimationFrame(() => requestAnimationFrame(() => {1394          container.style.height = `${h}px`;1395          prevH = h;1396          const onEnd = (e: TransitionEvent) => {1397            if (e.propertyName !== "height") return;1398            container.style.height = "";1399            blocked = false;1400            container.removeEventListener("transitionend", onEnd);1401          };1402          container.addEventListener("transitionend", onEnd);1403        }));1404      } else {1405        prevH = h;1406      }1407    });1408    heightRo.observe(container);1409    cleanupHooks.push(() => heightRo.disconnect());1410  }14111412  // Pre-capture the anchor field value for username prefill1413  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1414  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1415  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";14161417  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1418    const seen = new Set<string>();1419    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1420  }14211422  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1423    const q = value.trim().toLowerCase();1424    const deduped = uniqueEntries(source);1425    if (!q) return deduped.slice(0, 8);1426    return deduped.filter(e =>1427      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1428    ).slice(0, 12);1429  }14301431  function activeEntries(): SelectorEntry[] {1432    // When user is typing a search, filter across all known entries (domain matches + vault)1433    if (query.trim()) {1434      const merged = uniqueEntries([...entries, ...searchableEntries]);1435      return filterEntries(merged, query);1436    }1437    // Default: show domain matches; fall back to vault search when no matches1438    if (entries.length > 0) return entries;1439    return filterEntries(searchableEntries, "").slice(0, 8);1440  }14411442  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1443    const icon = document.createElement("div");1444    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1445    if (isNew) {1446      icon.innerHTML = plusSvgStr();1447    } else {1448      // Use the generic key glyph for all entries in the page-injected selector.1449      // Avoids disclosing vault domains to any third party and avoids needing1450      // to expose the browser favicon API to page context via web_accessible_resources.1451      void url;1452      icon.innerHTML = keySvgStr();1453    }1454    return icon;1455  }14561457  function renderIdentityHelper() {1458    currentMode = "identity-helper";1459    container.innerHTML = "";1460    focusedIndex = -1;1461    searchInput = null;14621463    const fallbackKind: IdentityKind = options.identityKind ?? "username";1464    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1465    const typedQuery = query.trim();1466    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);14671468    function applyIdentity(identity: string) {1469      options.onFillFields?.(identity, "");1470      renderGenerator(identity);1471    }14721473    function applyCustomIdentity(identity: string) {1474      const trimmed = identity.trim();1475      if (!trimmed) return;1476      applyIdentity(trimmed);1477    }14781479    // Header: "NEW ACCOUNT" + domain name1480    const hdr = container.appendChild(document.createElement("div"));1481    hdr.className = "domain-header";1482    const headText = hdr.appendChild(document.createElement("div"));1483    headText.className = "domain-header-text";1484    const eyebrow = headText.appendChild(document.createElement("div"));1485    eyebrow.className = "domain-eyebrow";1486    eyebrow.textContent = "NEW ACCOUNT";1487    const domName = headText.appendChild(document.createElement("div"));1488    domName.className = "domain-name";1489    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14901491    const actions = hdr.appendChild(document.createElement("div"));1492    actions.className = "identity-mode-toggle";1493    for (const mode of ["both", "email", "username"] as const) {1494      const btn = actions.appendChild(document.createElement("button"));1495      btn.type = "button";1496      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1497      btn.textContent = identityFilterLabel(mode);1498      btn.setAttribute("aria-pressed", String(identityMode === mode));1499      btn.addEventListener("click", () => {1500        identityMode = mode;1501        renderIdentityHelper();1502      });1503    }15041505    const searchWrap = container.appendChild(document.createElement("div"));1506    searchWrap.className = "search-wrap identity-search-wrap";1507    const search = searchWrap.appendChild(document.createElement("input"));1508    search.className = "search";1509    search.placeholder = "search identities…";1510    search.value = query;1511    search.addEventListener("input", () => {1512      query = search.value;1513      renderIdentityHelper();1514      searchInput?.focus();1515      searchInput?.setSelectionRange(query.length, query.length);1516    });1517    search.addEventListener("keydown", (e) => {1518      if (e.key === "Escape") {1519        e.preventDefault();1520        dismiss(true);1521        return;1522      }1523      if (e.key !== "Enter") return;1524      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1525      if (exact) {1526        e.preventDefault();1527        applyIdentity(exact.value);1528        return;1529      }1530      if (!typedQuery || identities.length > 0) return;1531      e.preventDefault();1532      applyCustomIdentity(typedQuery);1533    });1534    const searchTools = searchWrap.appendChild(document.createElement("div"));1535    searchTools.className = "identity-mode-toggle";1536    const sortHint = searchTools.appendChild(document.createElement("div"));1537    sortHint.className = "identity-empty";1538    sortHint.style.padding = "0";1539    sortHint.textContent = "sorted by recent use";1540    searchInput = search;1541    const customLabel = identityMode === "both"1542      ? customKind1543      : identityMode;15441545    // Identity rows1546    const list = container.appendChild(document.createElement("div"));1547    list.className = "identity-list";1548    // Bottom fade only when the list overflows its max-height and isn't scrolled1549    // to the end. A short list (1-2 identities) shows no fade, so it never looks1550    // prematurely cut off; a long list gets the affordance, which clears on1551    // reaching the bottom.1552    const updateListFade = () => {1553      const overflowing = list.scrollHeight > list.clientHeight + 1;1554      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1555      const mask = overflowing && !atBottom1556        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1557        : "none";1558      list.style.setProperty("mask-image", mask);1559      list.style.setProperty("-webkit-mask-image", mask);1560    };1561    list.addEventListener("scroll", updateListFade);1562    if (typedQuery && identities.length === 0) {1563      const empty = list.appendChild(document.createElement("div"));1564      empty.className = "identity-empty";1565      empty.textContent = identityMode === "both"1566        ? `No match for “${typedQuery}”.`1567        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1568      const custom = list.appendChild(document.createElement("div"));1569      custom.className = "identity-custom-row";1570      const customTitle = custom.appendChild(document.createElement("div"));1571      customTitle.className = "identity-custom-row-title";1572      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1573      const customSub = custom.appendChild(document.createElement("div"));1574      customSub.className = "identity-custom-row-sub";1575      customSub.textContent = "Press Enter or click to continue.";1576      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1577    }1578    for (const id of identities) {1579      const row = list.appendChild(document.createElement("div"));1580      row.className = "peach-identity-row";1581      row.setAttribute("tabindex", "-1");1582      const val = row.appendChild(document.createElement("div"));1583      val.className = "peach-identity-value";1584      val.textContent = id.value;1585      const meta = row.appendChild(document.createElement("div"));1586      meta.className = "peach-identity-meta";1587      meta.textContent = `used ${id.useCount}×`;1588      row.addEventListener("click", () => {1589        applyIdentity(id.value);1590      });1591    }15921593    updateListFade();15941595    // Divider before "Use a different email…"1596    if (identities.length > 0) {1597      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1598    }15991600    // "Use a different email/username…" expandable row1601    const altRow = container.appendChild(document.createElement("div"));1602    altRow.className = "identity-alt-row";1603    altRow.textContent = `+ Use a different ${customLabel}…`;16041605    const altInputWrap = container.appendChild(document.createElement("div"));1606    altInputWrap.className = "identity-alt-input-wrap";1607    const altInput = altInputWrap.appendChild(document.createElement("input"));1608    altInput.className = "identity-alt-input";1609    altInput.type = "text";1610    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1611    altInput.setAttribute("autocomplete", "off");1612    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1613    altConfirm.className = "identity-alt-confirm";1614    altConfirm.type = "button";1615    altConfirm.textContent = "✓";16161617    function fillCustomIdentity() {1618      const v = altInput.value.trim();1619      if (!v) return;1620      applyCustomIdentity(v);1621    }16221623    altRow.addEventListener("click", () => {1624      altRow.style.display = "none";1625      altInputWrap.classList.add("open");1626      altInput.value = typedQuery || altInput.value;1627      altInput.focus();1628      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1629    });1630    altConfirm.addEventListener("click", fillCustomIdentity);1631    altInput.addEventListener("keydown", (e) => {1632      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1633    });16341635    // Escape hatch: user already has a vault entry for this site but it1636    // wasn't detected (different domain, old entry, etc.). Tapping this1637    // switches to the full searchable list so they can find and fill it;1638    // selecting an entry there will trigger the remember-site toast if1639    // the domain isn't already associated.1640    if ((options.searchableEntries?.length ?? 0) > 0) {1641      const escapeRow = container.appendChild(document.createElement("div"));1642      escapeRow.className = "identity-escape-row";1643      escapeRow.textContent = "I already have an account →";1644      escapeRow.setAttribute("tabindex", "0");1645      escapeRow.addEventListener("click", () => renderList());1646      escapeRow.addEventListener("keydown", (e) => {1647        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1648      });1649    }16501651    requestAnimationFrame(() => {1652      search.focus();1653      search.setSelectionRange(query.length, query.length);1654    });1655  }16561657  function renderGenerator(filledEmail: string) {1658    container.innerHTML = "";1659    const sitePolicy = detectPasswordPolicy();16601661    const wrap = container.appendChild(document.createElement("div"));1662    wrap.className = "gen-view";16631664    // Header: domain + NEW ACCOUNT1665    const hdrRow = wrap.appendChild(document.createElement("div"));1666    hdrRow.className = "domain-header";1667    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1668    eyebrow2.className = "domain-eyebrow";1669    eyebrow2.textContent = "NEW ACCOUNT";1670    const domName2 = hdrRow.appendChild(document.createElement("div"));1671    domName2.className = "domain-name";1672    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");16731674    // Confirmed email row1675    const conf = wrap.appendChild(document.createElement("div"));1676    conf.className = "gen-confirmed";1677    const confCheck = conf.appendChild(document.createElement("span"));1678    confCheck.className = "gen-confirmed-check";1679    confCheck.textContent = "✓";1680    const confVal = conf.appendChild(document.createElement("div"));1681    confVal.className = "gen-confirmed-val";1682    confVal.textContent = filledEmail;16831684    const lbl = wrap.appendChild(document.createElement("div"));1685    lbl.className = "gen-label";1686    lbl.textContent = "Generate a password";16871688    let currentPw = "";1689    const smartGen = createSmartGenerator({1690      policy: sitePolicy,1691      onChange: (pw) => { currentPw = pw; },1692    });1693    wrap.appendChild(smartGen.root);16941695    const fillBtn = wrap.appendChild(document.createElement("button"));1696    fillBtn.className = "gen-fill-btn";1697    fillBtn.type = "button";1698    fillBtn.textContent = "Copy & fill";1699    fillBtn.addEventListener("click", () => {1700      if (!currentPw) return;1701      options.onFillFields?.("", currentPw);1702      renderSaveOffer(filledEmail, currentPw);1703    });1704  }17051706  function renderSaveOffer(filledEmail: string, filledPassword: string) {1707    container.innerHTML = "";1708    const domain = options.domain ?? location.hostname.replace(/^www\./, "");17091710    const wrap = container.appendChild(document.createElement("div"));1711    wrap.className = "save-offer";17121713    const title = wrap.appendChild(document.createElement("div"));1714    title.className = "save-offer-title";1715    title.textContent = "Save this login to Peach?";17161717    function detailRow(label: string, value: string) {1718      const row = wrap.appendChild(document.createElement("div"));1719      row.className = "save-offer-row";1720      const lbl = row.appendChild(document.createElement("div"));1721      lbl.className = "save-offer-lbl";1722      lbl.textContent = label;1723      const val = row.appendChild(document.createElement("div"));1724      val.className = "save-offer-val";1725      val.textContent = value;1726    }17271728    detailRow("site", domain);1729    detailRow("email", filledEmail);1730    detailRow("password", "••••••••••••••••");17311732    const btns = wrap.appendChild(document.createElement("div"));1733    btns.className = "save-offer-btns";17341735    const saveBtn = btns.appendChild(document.createElement("button"));1736    saveBtn.className = "save-offer-save";1737    saveBtn.type = "button";1738    saveBtn.textContent = "Save";1739    saveBtn.addEventListener("click", async () => {1740      saveBtn.disabled = true;1741      saveBtn.textContent = "Saving…";1742      try {1743        const res = await chrome.runtime.sendMessage({1744          type: "ADD_ENTRY",1745          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1746        });1747        if ((res as { ok?: boolean }).ok) {1748          showSuccess(sTitle);1749        } else {1750          saveBtn.disabled = false;1751          saveBtn.textContent = "Save";1752        }1753      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1754    });17551756    const skipBtn = btns.appendChild(document.createElement("button"));1757    skipBtn.className = "save-offer-skip";1758    skipBtn.type = "button";1759    skipBtn.textContent = "Not now";1760    skipBtn.addEventListener("click", () => { dismiss(true); });1761  }17621763  function renderList() {1764    container.innerHTML = "";1765    focusedIndex = -1;1766    searchInput = null;1767    currentMode = "list";17681769    const current = activeEntries();17701771    // Domain header (always show) — eyebrow + domain on the left,1772    // a "+" shortcut to the create form on the right so the user is never1773    // trapped in the search list when they want to make a new entry.1774    const domHdr = document.createElement("div");1775    domHdr.className = "domain-header";1776    const headText = document.createElement("div");1777    headText.className = "domain-header-text";1778    const eyebrow = document.createElement("div");1779    eyebrow.className = "domain-eyebrow";1780    eyebrow.textContent = options.isSignup1781      ? "Sign up as"1782      : entries.length > 0 ? "Saved for this site" : "No saved login";1783    const domName = document.createElement("div");1784    domName.className = "domain-name";1785    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1786    headText.append(eyebrow, domName);1787    domHdr.appendChild(headText);17881789    if (!options.isSignup) {1790      const actions = document.createElement("div");1791      actions.className = "domain-header-actions";17921793      // Back arrow takes the place of the silver-platter's search icon when1794      // the user has pivoted away from a single-match platter — gives them1795      // a one-click way back to the original recommendation.1796      if (silverPlatterOrigin) {1797        const backBtn = document.createElement("button");1798        backBtn.className = "domain-search-btn";1799        backBtn.type = "button";1800        backBtn.setAttribute("aria-label", "Back to suggested entry");1801        backBtn.title = "Back to suggested entry";1802        backBtn.innerHTML = backSvgStr();1803        backBtn.addEventListener("click", (e) => {1804          e.stopPropagation();1805          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);1806        });1807        actions.appendChild(backBtn);1808      }18091810      const addBtn = document.createElement("button");1811      addBtn.className = "domain-add-btn";1812      addBtn.type = "button";1813      addBtn.setAttribute("aria-label", "Create new entry");1814      addBtn.title = "Create new entry";1815      addBtn.textContent = "+";1816      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1817      actions.appendChild(addBtn);18181819      domHdr.appendChild(actions);1820    }18211822    container.appendChild(domHdr);18231824    // Search — always show so user can find entries beyond the domain matches1825    const sw = document.createElement("div"); sw.className = "search-wrap";1826    searchInput = document.createElement("input");1827    searchInput.className = "search";1828    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1829    searchInput.value = query;1830    searchInput.addEventListener("input", () => {1831      query = searchInput?.value ?? "";1832      renderList();1833      searchInput?.focus();1834      searchInput?.setSelectionRange(query.length, query.length);1835    });1836    sw.appendChild(searchInput);1837    container.appendChild(sw);18381839    // Results1840    const results = document.createElement("div");1841    results.className = "results";1842    container.appendChild(results);18431844    if (current.length === 0 && entries.length > 0) {1845      // Show a hint but don't render empty entries1846    }18471848    for (let i = 0; i < current.length; i++) {1849      const e = current[i]!;1850      const entryEl = document.createElement("div");1851      entryEl.className = "entry";1852      entryEl.dataset.id = e.id;1853      entryEl.dataset.index = String(i);1854      entryEl.setAttribute("tabindex", "-1");18551856      entryEl.appendChild(makeEntryIcon(e.url));18571858      const info = document.createElement("div"); info.className = "entry-info";1859      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1860      const subEl = document.createElement("div"); subEl.className = "entry-sub";1861      const domain = e.url ? getDomainFromUrl(e.url) : "";1862      subEl.textContent = domain || e.username || "";1863      info.append(titleEl, subEl);1864      entryEl.appendChild(info);18651866      if (e.hasTotp) {1867        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1868        entryEl.appendChild(badge);1869      }1870      if (e.hasPasskey) {1871        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1872        entryEl.appendChild(badge);1873      }18741875      entryEl.addEventListener("click", () => {1876        if (options.isSignup && options.onFillFields) {1877          // Signup mode: clicking a saved identity fills the username field1878          options.onFillFields(e.username ?? "", "");1879          dismiss();1880        } else {1881          onSelect(e.id);1882          dismiss();1883        }1884      });1885      results.appendChild(entryEl);1886    }18871888    // Divider before "New entry"1889    if (current.length > 0) {1890      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1891    }18921893    // "New entry" row — always present1894    const newEl = document.createElement("div");1895    newEl.className = "entry";1896    newEl.setAttribute("tabindex", "-1");1897    newEl.appendChild(makeEntryIcon(undefined, true));18981899    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1900    const newTitle = document.createElement("div");1901    newTitle.className = "entry-title is-new";1902    newTitle.textContent = `New entry for ${sTitle}`;1903    const newSub = document.createElement("div");1904    newSub.className = "entry-sub";1905    newSub.textContent = sOrigin;1906    newInfo.append(newTitle, newSub);1907    newEl.appendChild(newInfo);1908    newEl.addEventListener("click", showCreateForm);1909    results.appendChild(newEl);19101911    // Focus search if present1912    if (searchInput) {1913      requestAnimationFrame(() => {1914        searchInput?.focus();1915        // Seed query (from type-to-search or domain-search-btn) lands at the1916        // end so the next keystroke extends it, not overwrites.1917        searchInput?.setSelectionRange(query.length, query.length);1918      });1919    }1920  }19211922  function setFocused(idx: number) {1923    const all = container.querySelectorAll<HTMLElement>(".entry");1924    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1925    focusedIndex = idx;1926    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1927  }19281929  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1930    const typed = identities.filter(s => s.type === fieldType);1931    if (!typed.length) return;1932    let collapsed = false;1933    let suppressNextFocus = false;19341935    const list = g.appendChild(document.createElement("div"));1936    list.className = "identity-suggest-list";1937    list.style.display = "none";19381939    // Collapse toggle — sits alone now that filter pills are gone1940    const collapseRow = list.appendChild(document.createElement("div"));1941    collapseRow.className = "identity-filter-row";1942    collapseRow.style.justifyContent = "flex-end";1943    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1944    collapseBtn.type = "button";1945    collapseBtn.className = "identity-collapse-btn";1946    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>`;1947    collapseBtn.addEventListener("mousedown", (e) => {1948      e.preventDefault();1949      collapsed = !collapsed;1950      collapseBtn.classList.toggle("is-collapsed", collapsed);1951      rowsWrapper.classList.toggle("is-collapsed", collapsed);1952    });19531954    const rowsWrapper = list.appendChild(document.createElement("div"));1955    rowsWrapper.className = "identity-rows";1956    const rows = rowsWrapper.appendChild(document.createElement("div"));1957    rows.className = "identity-rows-inner";19581959    // Bottom fade only when the list actually overflows and isn't scrolled to1960    // the end — a static mask-image fades the last row even on a 1-2 item list1961    // that fits entirely, making it look cut off. Driven off live scroll state.1962    const updateRowsFade = () => {1963      const overflowing = rows.scrollHeight > rows.clientHeight + 1;1964      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;1965      const mask = overflowing && !atBottom1966        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"1967        : "none";1968      rows.style.setProperty("mask-image", mask);1969      rows.style.setProperty("-webkit-mask-image", mask);1970    };1971    rows.addEventListener("scroll", updateRowsFade);19721973    // Hides the list and removes the document-level click watcher.1974    function hideList() {1975      list.style.display = "none";1976      document.removeEventListener("mousedown", onDocMousedown, { capture: true });1977    }19781979    // Dismiss list on any mousedown that originates outside the popup's shadow1980    // DOM. This is the ONLY close trigger for the list — blur is intentionally1981    // NOT used, because modal focus traps fire blur without a mousedown (they1982    // call element.focus() programmatically in response to focusin/focusout),1983    // which caused the list to vanish before the user could pick from it.1984    function onDocMousedown(e: MouseEvent) {1985      if (e.composedPath().includes(host)) return;1986      hideList();1987    }19881989    function pick(value: string) {1990      inp.value = value;1991      hideList();1992      suppressNextFocus = true;1993      inp.focus();1994      // If a focus trap intercepts inp.focus() and redirects to anchorEl before1995      // inp ever fires its focus event, suppressNextFocus would strand the user.1996      // Clear after a short window so subsequent clicks still work.1997      setTimeout(() => { suppressNextFocus = false; }, 120);1998    }19992000    function render() {2001      const q = inp.value.toLowerCase();2002      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2003      rows.innerHTML = "";2004      if (!filtered.length) { hideList(); return; }2005      for (const s of filtered) {2006        const row = rows.appendChild(document.createElement("button"));2007        row.type = "button"; row.className = "identity-suggest-row";2008        const val = row.appendChild(document.createElement("span"));2009        val.className = "identity-suggest-val"; val.textContent = s.value;2010        const meta = row.appendChild(document.createElement("span"));2011        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2012        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2013        row.addEventListener("keydown", (e) => {2014          if (e.key === "ArrowDown") {2015            e.preventDefault();2016            (row.nextElementSibling as HTMLElement | null)?.focus();2017          } else if (e.key === "ArrowUp") {2018            e.preventDefault();2019            const prev = row.previousElementSibling as HTMLElement | null;2020            if (prev) prev.focus();2021            else inp.focus();2022          } else if (e.key === "Enter" || e.key === " ") {2023            e.preventDefault();2024            pick(s.value);2025          } else if (e.key === "Escape") {2026            e.preventDefault();2027            hideList();2028            suppressNextFocus = true;2029            inp.focus();2030          }2031        });2032        // Row blur only fires during keyboard navigation (arrow keys / Tab).2033        // Focus traps don't produce row blur events since rows aren't focused2034        // when the trap fires; this handler is therefore trap-safe.2035        row.addEventListener("blur", (e) => {2036          const rt = (e as FocusEvent).relatedTarget as Node | null;2037          if (rt && (rt === inp || list.contains(rt))) return;2038          setTimeout(() => { hideList(); }, 150);2039        });2040      }2041      list.style.display = "";2042      updateRowsFade();2043      // Register the close-on-outside-click watcher each time the list shows.2044      // addEventListener deduplicates identical (fn, options) pairs, so2045      // re-rendering on input events does not stack up listeners.2046      document.addEventListener("mousedown", onDocMousedown, { capture: true });2047    }20482049    inp.addEventListener("focus", () => {2050      if (suppressNextFocus) { suppressNextFocus = false; return; }2051      render();2052    });2053    inp.addEventListener("input", render);2054    inp.addEventListener("keydown", (e) => {2055      if (list.style.display === "none") return;2056      if (e.key === "ArrowDown" && !collapsed) {2057        e.preventDefault();2058        (rows.firstElementChild as HTMLElement | null)?.focus();2059      } else if (e.key === "Escape") {2060        e.preventDefault();2061        hideList();2062      } else if (e.key === "Tab") {2063        // Tab moves focus away intentionally — close the list.2064        hideList();2065      }2066    });2067    // No blur handler on inp. Blur fires for ANY focus movement including2068    // programmatic focus() calls from modal focus traps, which caused the list2069    // to close before the user could interact. The document mousedown listener2070    // (registered in render()) handles intentional click-outside dismissal,2071    // and the keydown handler above covers keyboard Tab/Escape.20722073    // Ensure the watcher is removed if the main popup is dismissed while the2074    // list is visible.2075    cleanupHooks.push(hideList);2076  }20772078  async function showCreateForm() {2079    currentMode = "create";2080    container.innerHTML = "";20812082    // Guard: the service worker may lock the vault between when the selector2083    // opens and when the user clicks "New entry". Show the inline unlock form2084    // instead of silently failing on save.2085    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2086    if (!statusRes?.unlocked) {2087      renderLocked();2088      return;2089    }20902091    // Detect page password policy once for this form — reused on every2092    // regenerate click so the user always gets a compliant password.2093    const sitePolicy = detectPasswordPolicy();20942095    // Fetch identities on-demand — they're passed in signup context but not2096    // in login/search context where the user still clicks "New entry".2097    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];2098    if (!formIdentities.length) {2099      try {2100        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;2101        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;2102      } catch { /* silent fallback */ }2103    }21042105    const wrap = document.createElement("div");2106    wrap.className = "create-form-wrap";21072108    // Header2109    const head = document.createElement("div"); head.className = "create-head";2110    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2111    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>`;2112    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2113    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2114    head.append(backBtn, lbl);21152116    // Body2117    const body = document.createElement("div"); body.className = "create-body";21182119    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2120      const g = document.createElement("div"); g.className = "f-group";2121      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2122      const inp = document.createElement("input"); inp.className = "f-input";2123      g.append(l, inp); return { g, inp };2124    }21252126    // Title2127    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2128    body.appendChild(tg.g);21292130    // URL2131    const ug = fGroup("website");2132    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2133    if (loginSubdomain) {2134      const h = document.createElement("div"); h.className = "url-hint";2135      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2136    }2137    body.appendChild(ug.g);21382139    // Username — pre-fill from anchor if it doesn't look like an email2140    const xg = fGroup("username");2141    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2142    xg.inp.placeholder = "johndoe";2143    xg.inp.setAttribute("autocomplete", "off");2144    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2145    body.appendChild(xg.g);21462147    // Email — pre-fill from anchor if it looks like an email2148    const eg = fGroup("email");2149    (eg.inp as HTMLInputElement).type = "email";2150    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2151    eg.inp.placeholder = "[email protected]";2152    eg.inp.setAttribute("autocomplete", "off");2153    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2154    body.appendChild(eg.g);21552156    // Password — full smart generator with charset pills + length slider +2157    // policy hint. Mirrors the main UI's compact generator so users get the2158    // same controls inline as in the popup.2159    const pg = fGroup("password");2160    pg.inp.remove(); // smartGen provides its own display — no separate input needed2161    let currentPassword = prePassword || "";2162    const smartGen = createSmartGenerator({2163      policy: sitePolicy,2164      initialPassword: prePassword || undefined,2165      onChange: (pw) => { currentPassword = pw; },2166    });2167    pg.g.appendChild(smartGen.root);2168    body.appendChild(pg.g);21692170    // Save2171    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2172    saveBtn.textContent = "Save entry";2173    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2174    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2175    saveBtn.addEventListener("click", async () => {2176      const title = tg.inp.value.trim();2177      const pw = currentPassword.trim();2178      const username = xg.inp.value.trim();2179      const email = eg.inp.value.trim();2180      if (!title) {2181        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2182        showFormError("Entry needs a title");2183        return;2184      }2185      if (!pw) {2186        showFormError("Entry needs a password — tap regen to make one");2187        return;2188      }2189      errEl.style.display = "none";2190      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2191      try {2192        const res = await chrome.runtime.sendMessage({2193          type: "ADD_ENTRY",2194          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2195        });2196        if ((res as { ok?: boolean }).ok) {2197          // Fill the detected form. onFillFields uses whichever identity the2198          // page anchored on — the vault captures both username and email.2199          options.onFillFields?.(username || email, pw);2200          showSuccess(title);2201        } else {2202          const err = (res as { error?: string })?.error;2203          const errMsg = err === "vault_locked"2204            ? "Vault locked — open Peach to save"2205            : err === "STORAGE_QUOTA_EXCEEDED"2206              ? "Out of storage — open Peach → Settings to free space"2207              : err2208                ? `Could not save: ${err}`2209                : "Could not save entry";2210          showFormError(errMsg);2211          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2212        }2213      } catch (e) {2214        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2215        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2216      }2217    });2218    body.appendChild(saveBtn);2219    body.appendChild(errEl);22202221    wrap.append(head, body);2222    container.appendChild(wrap);2223    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2224  }22252226  function showSuccess(title: string) {2227    currentMode = "success";2228    container.innerHTML = "";2229    const wrap = document.createElement("div"); wrap.className = "success-wrap";2230    const ring = document.createElement("div"); ring.className = "success-ring";2231    ring.innerHTML = checkSvgStr();2232    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2233    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2234    wrap.append(ring, t, s);2235    container.appendChild(wrap);2236    setTimeout(() => dismiss(), 1600);2237  }22382239  function flashActionBtn(btn: HTMLButtonElement) {2240    btn.classList.add("flashed");2241    setTimeout(() => btn.classList.remove("flashed"), 700);2242  }22432244  // M3/QUA-005: when both the direct clipboard write and the background COPY2245  // fallback fail, briefly show the user that the copy did not happen.2246  function flashCopyError(btn: HTMLButtonElement) {2247    const original = btn.textContent ?? "";2248    btn.textContent = "Blocked";2249    btn.classList.add("flashed");2250    setTimeout(() => {2251      btn.classList.remove("flashed");2252      if (btn.isConnected) btn.textContent = original;2253    }, 1200);2254  }22552256  function renderSilverPlatter(entry: SelectorEntry) {2257    container.innerHTML = "";2258    searchInput = null;2259    focusedIndex = -1;2260    currentMode = "silver-platter";2261    silverPlatterOrigin = entry;22622263    const domHdr = document.createElement("div");2264    domHdr.className = "domain-header";2265    const headText = document.createElement("div");2266    headText.className = "domain-header-text";2267    const eyebrow = document.createElement("div");2268    eyebrow.className = "domain-eyebrow";2269    eyebrow.textContent = "Saved for this site";2270    const domName = document.createElement("div");2271    domName.className = "domain-name";2272    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2273    headText.append(eyebrow, domName);2274    domHdr.appendChild(headText);2275    if (!options.isSignup) {2276      const actions = document.createElement("div");2277      actions.className = "domain-header-actions";22782279      // Search shortcut — same idea as type-to-search below, but visible so2280      // the user can discover that another entry is reachable from a2281      // single-match platter. Sits to the left of the create button.2282      const searchBtn = document.createElement("button");2283      searchBtn.className = "domain-search-btn";2284      searchBtn.type = "button";2285      searchBtn.setAttribute("aria-label", "Search for a different entry");2286      searchBtn.title = "Search for a different entry";2287      searchBtn.innerHTML = searchSvgStr();2288      searchBtn.addEventListener("click", (e) => {2289        e.stopPropagation();2290        query = "";2291        renderList();2292      });2293      actions.appendChild(searchBtn);22942295      const addBtn = document.createElement("button");2296      addBtn.className = "domain-add-btn";2297      addBtn.type = "button";2298      addBtn.setAttribute("aria-label", "Create new entry");2299      addBtn.title = "Create new entry";2300      addBtn.textContent = "+";2301      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2302      actions.appendChild(addBtn);23032304      domHdr.appendChild(actions);2305    }2306    container.appendChild(domHdr);23072308    const platter = document.createElement("div");2309    platter.className = "silver-platter";23102311    const titleEl = document.createElement("div");2312    titleEl.className = "sp-title";2313    titleEl.textContent = entry.title;2314    platter.appendChild(titleEl);23152316    if (entry.email) {2317      const emailEl = document.createElement("div");2318      emailEl.className = "sp-identity-row";2319      const emailLbl = document.createElement("span");2320      emailLbl.className = "sp-identity-label";2321      emailLbl.textContent = "email";2322      const emailVal = document.createElement("span");2323      emailVal.className = "sp-username";2324      emailVal.textContent = entry.email;2325      emailEl.append(emailLbl, emailVal);2326      platter.appendChild(emailEl);2327    }23282329    if (entry.username) {2330      const userEl = document.createElement("div");2331      userEl.className = "sp-identity-row";2332      const userLbl = document.createElement("span");2333      userLbl.className = "sp-identity-label";2334      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2335      const userVal = document.createElement("span");2336      userVal.className = "sp-username";2337      userVal.textContent = entry.username;2338      userEl.append(userLbl, userVal);2339      platter.appendChild(userEl);2340    }23412342    const fillBtn = document.createElement("button");2343    fillBtn.className = "sp-fill-btn";2344    fillBtn.type = "button";2345    fillBtn.textContent = "Fill credentials";2346    fillBtn.addEventListener("click", () => {2347      if (fillBtn.disabled) return;2348      fillBtn.disabled = true;2349      fillBtn.classList.add("filled");2350      fillBtn.innerHTML = checkSvgStr();2351      // Fire the fill, then exit via the standard exit animation. The fill2352      // itself is async (handled in index.ts) — by 400ms the form is filled2353      // and the popup begins its exit. Total dwell from click to host2354      // removal: 400ms + 130ms (exit animation) = 530ms.2355      onSelect(entry.id);2356      setTimeout(() => dismiss(), 400);2357    });2358    platter.appendChild(fillBtn);23592360    const actionsGroup = document.createElement("div");2361    actionsGroup.className = "sp-actions-group";2362    const actionsLabel = document.createElement("div");2363    actionsLabel.className = "sp-actions-label";2364    actionsLabel.textContent = "Copy";2365    actionsGroup.appendChild(actionsLabel);23662367    const actions = document.createElement("div");2368    actions.className = "sp-actions";2369    actionsGroup.appendChild(actions);23702371    if (entry.email) {2372      const copyEmail = document.createElement("button");2373      copyEmail.className = "sp-action-btn";2374      copyEmail.type = "button";2375      copyEmail.title = "Copy email";2376      copyEmail.textContent = "Email";2377      copyEmail.addEventListener("click", async (e) => {2378        e.stopPropagation();2379        let alreadyWritten = false;2380        try {2381          await navigator.clipboard.writeText(entry.email!);2382          alreadyWritten = true;2383        } catch (err) {2384          console.warn("[Peach] clipboard write denied:", err);2385        }2386        const resp = await chrome.runtime.sendMessage({2387          type: "COPY",2388          payload: { text: entry.email, label: "Email", alreadyWritten },2389        }).catch(() => null) as { ok?: boolean } | null;2390        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2391        else flashCopyError(copyEmail);2392      });2393      actions.appendChild(copyEmail);2394    }23952396    const copyU = document.createElement("button");2397    copyU.className = "sp-action-btn";2398    copyU.type = "button";2399    const usernameIsEmail = entry.username?.includes("@") ?? false;2400    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2401    copyU.textContent = usernameIsEmail ? "Email" : "Username";2402    copyU.disabled = !entry.username;2403    copyU.addEventListener("click", async (e) => {2404      e.stopPropagation();2405      if (!entry.username) return;2406      let alreadyWritten = false;2407      try {2408        await navigator.clipboard.writeText(entry.username);2409        alreadyWritten = true;2410      } catch (err) {2411        console.warn("[Peach] clipboard write denied:", err);2412      }2413      const resp = await chrome.runtime.sendMessage({2414        type: "COPY",2415        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2416      }).catch(() => null) as { ok?: boolean } | null;2417      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2418      else flashCopyError(copyU);2419    });2420    actions.appendChild(copyU);24212422    const copyP = document.createElement("button");2423    copyP.className = "sp-action-btn";2424    copyP.type = "button";2425    copyP.title = "Copy password";2426    copyP.textContent = "Password";2427    copyP.addEventListener("click", async (e) => {2428      e.stopPropagation();2429      const resp = await chrome.runtime.sendMessage({2430        type: "GET_ENTRY_FOR_FILL",2431        payload: { id: entry.id },2432      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2433      if (!resp?.ok || !resp.data?.password) return;2434      let alreadyWritten = false;2435      try {2436        await navigator.clipboard.writeText(resp.data.password);2437        alreadyWritten = true;2438      } catch (err) {2439        console.warn("[Peach] clipboard write denied:", err);2440      }2441      const copyResp = await chrome.runtime.sendMessage({2442        type: "COPY",2443        payload: { text: resp.data.password, label: "Password", alreadyWritten },2444      }).catch(() => null) as { ok?: boolean } | null;2445      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2446      else flashCopyError(copyP);2447    });2448    actions.appendChild(copyP);24492450    let trayEl: HTMLDivElement | null = null;2451    let trayInterval: ReturnType<typeof setInterval> | null = null;24522453    function closeTray() {2454      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2455      trayEl?.remove();2456      trayEl = null;2457    }2458    // Register so dismiss() will close the tray and clear the interval2459    // even if the user dismisses without explicitly closing the tray.2460    cleanupHooks.push(closeTray);24612462    async function openTOTPTray() {2463      // Fetch the current TOTP code from the background. The raw base32 seed2464      // never enters the content script (SEV-3-C): we receive the live 6-digit2465      // code plus the seconds remaining, count down locally, and re-fetch a2466      // fresh code only when the 30s window rolls over.2467      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2468        const r = await chrome.runtime.sendMessage({2469          type: "GET_ENTRY_FOR_FILL",2470          payload: { id: entry.id },2471        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2472        if (!r?.ok || !r.data?.totpCode) return null;2473        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2474      }2475      let current = await fetchCode();2476      if (!current) return;24772478      trayEl = document.createElement("div");2479      trayEl.className = "sp-tray";24802481      const label = document.createElement("span");2482      label.className = "sp-tray-label";2483      label.textContent = "2FA";2484      trayEl.appendChild(label);24852486      const codeEl = document.createElement("div");2487      codeEl.className = "sp-totp-code";2488      trayEl.appendChild(codeEl);24892490      const ringNs = "http://www.w3.org/2000/svg";2491      const ring = document.createElementNS(ringNs, "svg");2492      ring.setAttribute("class", "sp-totp-ring");2493      ring.setAttribute("viewBox", "0 0 24 24");2494      const trackC = document.createElementNS(ringNs, "circle");2495      trackC.setAttribute("class", "ring-track");2496      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2497      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2498      const fillC = document.createElementNS(ringNs, "circle");2499      fillC.setAttribute("class", "ring-fill");2500      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2501      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2502      fillC.setAttribute("stroke-linecap", "round");2503      fillC.setAttribute("stroke-dasharray", "62.83");2504      ring.append(trackC, fillC);2505      trayEl.appendChild(ring);25062507      const copyBtn = document.createElement("button");2508      copyBtn.className = "sp-totp-copy";2509      copyBtn.type = "button";2510      copyBtn.textContent = "Copy";2511      trayEl.appendChild(copyBtn);25122513      function render() {2514        const { code, remaining } = current!;2515        // Group as "847 291" — easier to read than "847291"2516        codeEl.textContent = code.length === 62517          ? `${code.slice(0, 3)} ${code.slice(3)}`2518          : code;2519        // Ring fills counter-clockwise as time elapses: dashoffset goes from2520        // 0 (full ring) to 62.83 (empty) over the 30s window.2521        const fraction = (30 - remaining) / 30;2522        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2523      }2524      render();2525      trayInterval = setInterval(async () => {2526        if (!current) return;2527        current = { code: current.code, remaining: current.remaining - 1 };2528        // Window rolled over — pull a fresh code from the background.2529        if (current.remaining <= 0) {2530          const next = await fetchCode();2531          current = next ?? { code: current.code, remaining: 30 };2532        }2533        render();2534      }, 1000);25352536      copyBtn.addEventListener("click", async (e) => {2537        e.stopPropagation();2538        const code = current?.code;2539        if (!code) return;2540        let alreadyWritten = false;2541        try {2542          await navigator.clipboard.writeText(code);2543          alreadyWritten = true;2544        } catch (err) {2545          console.warn("[Peach] clipboard write denied:", err);2546        }2547        const resp = await chrome.runtime.sendMessage({2548          type: "COPY",2549          payload: { text: code, label: "TOTP", alreadyWritten },2550        }).catch(() => null) as { ok?: boolean } | null;2551        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2552        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2553      });25542555      platter.appendChild(trayEl);2556    }25572558    const editBtn = document.createElement("button");2559    editBtn.className = "sp-action-btn sp-action-edit";2560    editBtn.type = "button";2561    editBtn.title = "Edit entry";2562    editBtn.textContent = "Edit";2563    editBtn.addEventListener("click", (e) => {2564      e.stopPropagation();2565      closeTray();2566      void renderInlineEdit(entry);2567    });2568    actions.appendChild(editBtn);25692570    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2571    // "···" toggle was zero-savings (the toggle button took the same space2572    // the "2FA" label needed) and made the code one extra click away.2573    if (entry.hasTotp) void openTOTPTray();25742575    platter.appendChild(actionsGroup);2576    container.appendChild(platter);2577  }25782579  /**2580   * Inline-popup edit mode. Swaps the silver platter for an editable form2581   * over the same shadow-DOM surface so the user never leaves the page.2582   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2583   * with the new fields. Cancel returns without writing.2584   */2585  async function renderInlineEdit(summary: SelectorEntry) {2586    container.innerHTML = "";2587    const wrap = document.createElement("div");2588    wrap.className = "create-form-wrap";25892590    const head = document.createElement("div");2591    head.className = "create-head";2592    const back = document.createElement("button");2593    back.className = "back-btn";2594    back.type = "button";2595    back.title = "Cancel";2596    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>`;2597    back.addEventListener("click", () => renderSilverPlatter(summary));2598    head.appendChild(back);2599    const headLbl = document.createElement("div");2600    headLbl.className = "create-label";2601    headLbl.textContent = "Edit entry";2602    head.appendChild(headLbl);2603    wrap.appendChild(head);26042605    const body = document.createElement("div");2606    body.className = "create-body";26072608    // Loading shimmer while we fetch the full entry2609    const loading = document.createElement("div");2610    loading.className = "empty-hint";2611    loading.textContent = "loading…";2612    body.appendChild(loading);2613    wrap.appendChild(body);2614    container.appendChild(wrap);26152616    const [res, idRes] = await Promise.all([2617      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2618      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2619      chrome.runtime.sendMessage({2620        type: "GET_ENTRY_FOR_EDIT",2621        payload: { id: summary.id },2622      }).catch(() => null),2623      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2624    ]);2625    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2626    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];26272628    if (!entryRes || !entryRes.ok || !entryRes.data) {2629      loading.textContent = "couldn't load this entry. try again from the popup.";2630      return;2631    }2632    body.innerHTML = "";26332634    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2635      const group = document.createElement("div");2636      group.className = "f-group";2637      const lbl = document.createElement("div");2638      lbl.className = "f-label";2639      lbl.textContent = label;2640      const input = document.createElement("input");2641      input.className = "f-input";2642      input.type = type;2643      input.value = value;2644      input.autocomplete = "off";2645      group.append(lbl, input);2646      body.appendChild(group);2647      return { g: group, inp: input };2648    }26492650    const titleInput = field("title", entryRes.data.title ?? "").inp;2651    const urlInput = field("url", entryRes.data.url ?? "").inp;2652    urlInput.classList.add("url-f");2653    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2654    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2655    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2656    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2657    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");26582659    // Password row with reveal toggle + generator2660    const pwGroup = document.createElement("div");2661    pwGroup.className = "f-group";2662    const pwLbl = document.createElement("div");2663    pwLbl.className = "f-label";2664    pwLbl.textContent = "password";2665    const pwRow = document.createElement("div");2666    pwRow.className = "f-row";2667    const pwInput = document.createElement("input");2668    pwInput.className = "f-input";2669    pwInput.type = "password";2670    pwInput.value = entryRes.data.password ?? "";2671    pwInput.autocomplete = "new-password";2672    const revealBtn = document.createElement("button");2673    revealBtn.className = "gen-btn";2674    revealBtn.type = "button";2675    revealBtn.textContent = "show";2676    revealBtn.addEventListener("click", () => {2677      const reveal = pwInput.type === "password";2678      pwInput.type = reveal ? "text" : "password";2679      revealBtn.textContent = reveal ? "hide" : "show";2680    });2681    pwRow.append(pwInput, revealBtn);2682    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2683    editSmartGen.root.style.display = "none";2684    let editGenVisible = false;2685    const genToggleBtn = document.createElement("button");2686    genToggleBtn.className = "gen-toggle-link";2687    genToggleBtn.type = "button";2688    genToggleBtn.textContent = "⚙ generate";2689    genToggleBtn.addEventListener("click", () => {2690      editGenVisible = !editGenVisible;2691      pwRow.style.display = editGenVisible ? "none" : "";2692      editSmartGen.root.style.display = editGenVisible ? "" : "none";2693      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2694    });2695    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2696    body.appendChild(pwGroup);26972698    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;26992700    // Notes2701    const notesGroup = document.createElement("div");2702    notesGroup.className = "f-group";2703    const notesLbl = document.createElement("div");2704    notesLbl.className = "f-label";2705    notesLbl.textContent = "notes";2706    const notesInput = document.createElement("textarea");2707    notesInput.className = "f-input";2708    notesInput.rows = 3;2709    notesInput.value = entryRes.data.notes ?? "";2710    notesInput.style.fontFamily = "Inter, sans-serif";2711    notesInput.style.resize = "vertical";2712    notesGroup.append(notesLbl, notesInput);2713    body.appendChild(notesGroup);27142715    // Save / Cancel row2716    const actionsRow = document.createElement("div");2717    actionsRow.className = "f-row";2718    const saveBtn = document.createElement("button");2719    saveBtn.className = "save-btn";2720    saveBtn.type = "button";2721    saveBtn.textContent = "Save changes";2722    saveBtn.style.flex = "1";2723    const cancelBtn = document.createElement("button");2724    cancelBtn.className = "gen-btn";2725    cancelBtn.type = "button";2726    cancelBtn.textContent = "cancel";2727    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2728    actionsRow.append(saveBtn, cancelBtn);2729    body.appendChild(actionsRow);27302731    saveBtn.addEventListener("click", async () => {2732      saveBtn.disabled = true;2733      const originalLabel = saveBtn.textContent;2734      saveBtn.textContent = "Saving…";2735      const patch: Record<string, unknown> = {2736        title: titleInput.value.trim(),2737        url: urlInput.value.trim(),2738        username: usernameInput.value.trim(),2739        email: emailInput.value.trim() || undefined,2740        password: pwInput.value,2741        totp: totpInput.value.trim(),2742        notes: notesInput.value,2743      };2744      const updateRes = (await chrome.runtime.sendMessage({2745        type: "UPDATE_ENTRY",2746        payload: { id: summary.id, patch },2747      }).catch(() => null)) as { ok: boolean; error?: string } | null;2748      if (!updateRes?.ok) {2749        saveBtn.disabled = false;2750        saveBtn.textContent = originalLabel;2751        const err = document.createElement("div");2752        err.className = "empty-hint";2753        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2754        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2755        body.appendChild(err);2756        setTimeout(() => err.remove(), 3000);2757        return;2758      }2759      // Refresh the platter with updated summary fields2760      const refreshed: SelectorEntry = {2761        id: summary.id,2762        title: patch.title as string,2763        username: patch.username as string,2764        email: patch.email as string | undefined,2765        url: patch.url as string,2766        hasTotp: Boolean(patch.totp),2767        hasPasskey: summary.hasPasskey,2768      };2769      renderSilverPlatter(refreshed);2770    });27712772    queueMicrotask(() => titleInput.focus());2773  }27742775  function renderLocked() {2776    container.innerHTML = "";27772778    // Domain header (same as list view)2779    const domHdr = document.createElement("div");2780    domHdr.className = "domain-header";2781    const eyebrow = document.createElement("div");2782    eyebrow.className = "domain-eyebrow";2783    eyebrow.textContent = "vault locked";2784    const domName = document.createElement("div");2785    domName.className = "domain-name";2786    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2787    domHdr.append(eyebrow, domName);2788    container.appendChild(domHdr);27892790    const wrap = document.createElement("div");2791    wrap.className = "locked-wrap";27922793    // Icon + label row2794    const head = document.createElement("div"); head.className = "locked-head";2795    const icon = document.createElement("div"); icon.className = "locked-icon";2796    icon.innerHTML = keySvgStr();2797    const title = document.createElement("div"); title.className = "locked-title";2798    title.textContent = "unlock to autofill";2799    head.append(icon, title);28002801    // The master password is NEVER collected in page-hosted DOM. A malicious2802    // page can observe keystrokes on the shared DOM event stream (a capture-2803    // phase listener registered before Peach injects sees every key before any2804    // stopImmediatePropagation), which would leak the vault's root secret2805    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2806    // where keystrokes are isolated from the page. After the user unlocks2807    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2808    // automatically (see content/index.ts), so the flow resumes on its own.2809    const sub = document.createElement("div");2810    sub.className = "locked-sub";2811    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";28122813    const openBtn = document.createElement("button");2814    openBtn.className = "locked-btn";2815    openBtn.type = "button";2816    openBtn.textContent = "Open Peach to unlock";2817    openBtn.addEventListener("click", () => {2818      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2819      openBtn.textContent = "opening Peach…";2820      openBtn.disabled = true;2821      // openPopup() can't always open programmatically (browser/version/gesture2822      // limits); reset so the user can retry or click the toolbar icon.2823      setTimeout(() => {2824        if (openBtn.isConnected) {2825          openBtn.textContent = "Open Peach to unlock";2826          openBtn.disabled = false;2827        }2828      }, 2500);2829    });28302831    wrap.append(head, sub, openBtn);2832    container.appendChild(wrap);2833  }28342835  function handleKeyDown(e: KeyboardEvent) {2836    if (options.locked) {2837      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2838      return;2839    }2840    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper") {2841      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2842      return;2843    }2844    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2845    const count = allEntryEls.length;2846    const activeElement = shadow.activeElement ?? document.activeElement;2847    if (activeElement === searchInput) {2848      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2849      if (count === 0) return;2850      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2851    }2852    if (count === 0) return;2853    switch (e.key) {2854      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2855      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2856      case "Enter": {2857        if (focusedIndex >= 0) {2858          const el = allEntryEls[focusedIndex] as HTMLElement;2859          const id = el.dataset.id;2860          if (id) { onSelect(id); dismiss(); }2861          else if (el.classList.contains("is-new") || !id) {2862            // "New entry" row (last item, no data-id)2863            showCreateForm();2864          }2865        }2866        break;2867      }2868      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2869    }2870  }28712872  document.addEventListener("keydown", handleKeyDown);28732874  // Type-to-search from the silver platter. A printable single-character2875  // keystroke (no modifier) seeds the search query and switches into the2876  // list view, so the user can pivot to a different entry without first2877  // clicking the search icon. Capture phase so the anchor input does not2878  // receive the character before we hijack it.2879  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2880    if (currentMode !== "silver-platter") return;2881    if (e.ctrlKey || e.metaKey || e.altKey) return;2882    if (e.key.length !== 1) return;2883    e.preventDefault();2884    e.stopImmediatePropagation();2885    query = e.key;2886    renderList();2887  };2888  document.addEventListener("keydown", silverPlatterTypeHandler, true);2889  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));28902891  const identityHelperTypeHandler = (e: KeyboardEvent) => {2892    if (currentMode !== "identity-helper") return;2893    if (e.ctrlKey || e.metaKey || e.altKey) return;2894    const active = (shadow.activeElement ?? document.activeElement) as Element | null;2895    if (active === searchInput) return;2896    if (2897      active instanceof HTMLInputElement ||2898      active instanceof HTMLTextAreaElement ||2899      (active instanceof HTMLElement && active.isContentEditable)2900    ) {2901      return;2902    }2903    if (e.key.length !== 1) return;2904    e.preventDefault();2905    e.stopImmediatePropagation();2906    query = e.key;2907    renderIdentityHelper();2908  };2909  document.addEventListener("keydown", identityHelperTypeHandler, true);2910  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));29112912  (modalAncestor ?? document.body).appendChild(host);29132914  // position:fixed normally resolves to the viewport, but an ancestor with2915  // transform / filter / backdrop-filter / perspective / contain / will-change2916  // establishes a containing block, so "fixed" then resolves to that ancestor's2917  // padding box instead. When the host is mounted inside such an ancestor (a2918  // modal) we subtract its border-box origin so the popup still lands at the2919  // field's true viewport position. At the document root there is no such2920  // ancestor and the offset is zero.2921  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {2922    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };2923    return (2924      has("transform") || has("perspective") || has("translate") ||2925      has("rotate") || has("scale") || has("filter") ||2926      has("backdrop-filter") || has("-webkit-backdrop-filter") ||2927      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||2928      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))2929    );2930  }2931  function containingBlockOffset(): { dx: number; dy: number } {2932    let el: HTMLElement | null = host.parentElement;2933    while (el && el !== document.documentElement) {2934      const s = getComputedStyle(el);2935      if (establishesFixedContainingBlock(s)) {2936        const r = el.getBoundingClientRect();2937        return {2938          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),2939          dy: r.top + (parseFloat(s.borderTopWidth) || 0),2940        };2941      }2942      el = el.parentElement;2943    }2944    return { dx: 0, dy: 0 };2945  }29462947  function updatePosition() {2948    const r = anchorEl.getBoundingClientRect();2949    const { dx, dy } = containingBlockOffset();2950    host.style.top = `${r.bottom - dy + 5}px`;2951    host.style.left = `${r.left - dx}px`;2952    host.style.width = `${popupWidth}px`;2953  }2954  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);2955  updatePosition();29562957  if (options.locked) {2958    renderLocked();2959  } else if (options.isSignup && options.savedIdentities) {2960    // State 10: identity helper — signup form detected, show derived2961    // identity list (emails then usernames) instead of vault entry list.2962    renderIdentityHelper();2963  } else if (entries.length === 1 && !options.isSignup) {2964    // Silver platter (State 1): single domain match → focused fill view.2965    // Multi-match goes through renderList instead.2966    renderSilverPlatter(entries[0]!);2967  } else {2968    renderList();2969  }29702971  let exitScheduled = false;2972  function dismiss(userAction = false) {2973    // Idempotent: dismiss() can be called from multiple paths (Escape,2974    // outside click, entry select, fill success, host page nav). The exit2975    // animation must only play once and host.remove() must run exactly once.2976    if (exitScheduled) return;2977    exitScheduled = true;2978    // Detach listeners synchronously so nothing can re-trigger during the2979    // 130ms exit window (a focusin firing here would race against the2980    // dismiss-lock work in Pass 2).2981    stopObserving();2982    document.removeEventListener("click", outsideClick, { capture: true });2983    document.removeEventListener("keydown", handleKeyDown);2984    for (const cleanup of cleanupHooks) {2985      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2986    }2987    if (userAction) options.onDismiss?.();2988    container.classList.add("is-exiting");2989    setTimeout(() => host.remove(), 130);2990  }29912992  function outsideClick(ev: MouseEvent) {2993    const path = ev.composedPath();2994    // Never dismiss when clicking the anchor field itself — that click is2995    // what triggered the selector to open, and the user may click the field2996    // again to re-focus it without intending to close the selector.2997    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2998  }2999  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3000  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);30013002  return dismiss;3003}30043005export function showTOTPSelector(3006  anchorEl: HTMLInputElement,3007  entries: SelectorEntry[],3008  onFill: (id: string) => void,3009  options: { domain?: string; onDismiss?: () => void } = {}3010): () => void {3011  const host = document.createElement("div");3012  host.style.cssText = "position: absolute; z-index: 2147483647;";3013  host.style.setProperty("--peach-accent", accentHex);3014  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3015  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3016  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3017  const shadow = host.attachShadow({ mode: "closed" });30183019  const style = shadow.appendChild(document.createElement("style"));3020  style.textContent = SELECTOR_STYLES;30213022  const rect = anchorEl.getBoundingClientRect();3023  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3024  host.style.left = `${rect.left + window.scrollX}px`;3025  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3026  host.style.width = `${popupWidth}px`;30273028  const container = shadow.appendChild(document.createElement("div"));3029  container.className = "peach-inline-popup";3030  container.setAttribute("data-theme", popupTheme);30313032  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3033  const current = entries.filter((entry) => entry.hasTotp);3034  let focusedIndex = current.length === 1 ? 0 : -1;30353036  function updatePosition() {3037    const r = anchorEl.getBoundingClientRect();3038    host.style.top = `${r.bottom + window.scrollY + 5}px`;3039    host.style.left = `${r.left + window.scrollX}px`;3040    host.style.width = `${popupWidth}px`;3041  }30423043  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);30443045  function choose(entry: SelectorEntry) {3046    onFill(entry.id);3047    dismiss();3048  }30493050  function render() {3051    container.innerHTML = "";30523053    const domHdr = document.createElement("div");3054    domHdr.className = "domain-header";3055    const headText = document.createElement("div");3056    headText.className = "domain-header-text";3057    const eyebrow = document.createElement("div");3058    eyebrow.className = "domain-eyebrow";3059    eyebrow.textContent = "2FA code";3060    const domName = document.createElement("div");3061    domName.className = "domain-name";3062    domName.textContent = domain;3063    headText.append(eyebrow, domName);3064    domHdr.appendChild(headText);3065    container.appendChild(domHdr);30663067    if (current.length === 1) {3068      const entry = current[0]!;3069      const platter = document.createElement("div");3070      platter.className = "silver-platter";30713072      const title = document.createElement("div");3073      title.className = "sp-title";3074      title.textContent = entry.title;3075      platter.appendChild(title);30763077      const sub = document.createElement("div");3078      sub.className = "sp-username";3079      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3080      platter.appendChild(sub);30813082      const fill = document.createElement("button");3083      fill.className = "sp-fill-btn";3084      fill.type = "button";3085      fill.textContent = "Fill 2FA code";3086      fill.addEventListener("click", () => choose(entry));3087      platter.appendChild(fill);30883089      container.appendChild(platter);3090      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3091      return;3092    }30933094    const results = document.createElement("div");3095    results.className = "results";3096    container.appendChild(results);30973098    for (let i = 0; i < current.length; i++) {3099      const entry = current[i]!;3100      const row = document.createElement("div");3101      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3102      row.dataset.index = String(i);3103      row.setAttribute("tabindex", "-1");31043105      const icon = document.createElement("div");3106      icon.className = "entry-icon";3107      icon.innerHTML = keySvgStr();3108      row.appendChild(icon);3109      const info = document.createElement("div");3110      info.className = "entry-info";3111      const title = document.createElement("div");3112      title.className = "entry-title";3113      title.textContent = entry.title;3114      const sub = document.createElement("div");3115      sub.className = "entry-sub";3116      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3117      info.append(title, sub);3118      row.appendChild(info);31193120      const badge = document.createElement("span");3121      badge.className = "totp-badge";3122      badge.textContent = "Fill";3123      row.appendChild(badge);3124      row.addEventListener("click", () => choose(entry));3125      results.appendChild(row);3126    }3127  }31283129  function setFocused(index: number) {3130    focusedIndex = index;3131    container.querySelectorAll(".entry").forEach((el, i) => {3132      el.classList.toggle("focused", i === focusedIndex);3133      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3134    });3135  }31363137  function handleKeyDown(e: KeyboardEvent) {3138    if (e.key === "Escape" || e.key === "Tab") {3139      e.preventDefault();3140      dismiss(true);3141      return;3142    }3143    if (current.length === 0) return;3144    if (e.key === "Enter") {3145      e.preventDefault();3146      choose(current[Math.max(0, focusedIndex)]!);3147      return;3148    }3149    if (current.length === 1) return;3150    if (e.key === "ArrowDown") {3151      e.preventDefault();3152      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3153    } else if (e.key === "ArrowUp") {3154      e.preventDefault();3155      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3156    }3157  }31583159  let exitScheduled = false;3160  function dismiss(userAction = false) {3161    if (exitScheduled) return;3162    exitScheduled = true;3163    stopObserving();3164    document.removeEventListener("click", outsideClick, { capture: true });3165    document.removeEventListener("keydown", handleKeyDown);3166    if (userAction) options.onDismiss?.();3167    container.classList.add("is-exiting");3168    setTimeout(() => host.remove(), 130);3169  }31703171  function outsideClick(ev: MouseEvent) {3172    const path = ev.composedPath();3173    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3174  }31753176  document.addEventListener("keydown", handleKeyDown);3177  document.body.appendChild(host);3178  render();3179  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);31803181  return dismiss;3182}31833184export interface CardSelectorEntry {3185  id: string;3186  title: string;3187  cardholderName?: string;3188  last4?: string;3189  expMonth?: string;3190  expYear?: string;3191  network?: import("../shared/types").CardNetwork;3192}31933194interface CardSelectorOptions {3195  domain?: string;3196  /** Caller-provided fill — receives the full CardEntry payload from the SW. */3197  onFill: (entry: import("../shared/types").VaultEntry) => void;3198  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3199  onDismiss?: () => void;3200}32013202/**3203 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3204 * passkey create or get. Renders as a fixed-position floating popup (no3205 * field anchor needed — passkeys don't require a focused input). Uses the3206 * same theme tokens and entrance animation as all other inline popup states.3207 */3208export function showPasskeyProGate(): void {3209  const domain = location.hostname.replace(/^www\./, "");32103211  const host = document.createElement("div");3212  host.setAttribute("data-peach-passkey-gate", "1");3213  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3214  const shadow = host.attachShadow({ mode: "closed" });32153216  const style = document.createElement("style");3217  style.textContent = `3218    :host { all: initial; }3219    .gate-wrap {3220      position: fixed;3221      top: 50%;3222      left: 50%;3223      transform: translate(-50%, -50%);3224      width: 280px;3225      pointer-events: auto;3226      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3227    }3228    @keyframes g-in {3229      from { opacity:0; transform: translate(-50%,-52%); }3230      to   { opacity:1; transform: translate(-50%,-50%); }3231    }3232    .gate-wrap.is-exiting {3233      animation: g-out 130ms ease-in forwards;3234    }3235    @keyframes g-out {3236      to { opacity:0; transform: translate(-50%,-52%); }3237    }3238    .gate {3239      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3240      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3241      border-radius: 12px;3242      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3243      padding: 16px;3244      font-family: Inter, sans-serif;3245    }3246    .gate-header {3247      display: flex;3248      align-items: center;3249      gap: 7px;3250      margin-bottom: 12px;3251      padding-bottom: 10px;3252      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3253    }3254    .gate-domain {3255      font-size: 12px;3256      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3257      font-family: "IBM Plex Mono", monospace;3258      overflow: hidden;3259      text-overflow: ellipsis;3260      white-space: nowrap;3261    }3262    .gate-title {3263      font-size: 14px;3264      font-weight: 500;3265      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3266      margin-bottom: 6px;3267    }3268    .gate-subtitle {3269      font-size: 12px;3270      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3271      line-height: 1.5;3272      margin-bottom: 14px;3273    }3274    .gate-btn {3275      display: block;3276      width: 100%;3277      padding: 9px 0;3278      border-radius: 8px;3279      border: none;3280      cursor: pointer;3281      font-size: 13px;3282      font-family: Inter, sans-serif;3283      font-weight: 500;3284      transition: opacity 100ms;3285      margin-bottom: 7px;3286      text-align: center;3287    }3288    .gate-btn:last-child { margin-bottom: 0; }3289    .gate-btn--accent {3290      background: ${accentHex};3291      color: #fff;3292    }3293    .gate-btn--accent:hover { opacity: 0.88; }3294    .gate-btn--ghost {3295      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3296      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3297    }3298    .gate-btn--ghost:hover { opacity: 0.75; }3299    .backdrop {3300      position: fixed;3301      inset: 0;3302      pointer-events: auto;3303    }3304  `;3305  shadow.appendChild(style);33063307  const backdrop = document.createElement("div");3308  backdrop.className = "backdrop";3309  shadow.appendChild(backdrop);33103311  const wrap = document.createElement("div");3312  wrap.className = "gate-wrap";3313  shadow.appendChild(wrap);33143315  const gate = document.createElement("div");3316  gate.className = "gate";3317  wrap.appendChild(gate);33183319  // Header: peach icon + domain3320  const header = document.createElement("div");3321  header.className = "gate-header";3322  const icon = document.createElement("span");3323  icon.innerHTML = peachIconSvg();3324  const domainEl = document.createElement("span");3325  domainEl.className = "gate-domain";3326  domainEl.textContent = domain;3327  header.append(icon, domainEl);3328  gate.appendChild(header);33293330  const title = document.createElement("div");3331  title.className = "gate-title";3332  title.textContent = "Passkeys are part of Peach Pro.";3333  gate.appendChild(title);33343335  const subtitle = document.createElement("div");3336  subtitle.className = "gate-subtitle";3337  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3338  gate.appendChild(subtitle);33393340  const upgradeBtn = document.createElement("button");3341  upgradeBtn.className = "gate-btn gate-btn--accent";3342  upgradeBtn.type = "button";3343  upgradeBtn.textContent = "Upgrade to Pro";3344  gate.appendChild(upgradeBtn);33453346  const laterBtn = document.createElement("button");3347  laterBtn.className = "gate-btn gate-btn--ghost";3348  laterBtn.type = "button";3349  laterBtn.textContent = "Not right now";3350  gate.appendChild(laterBtn);33513352  function dismiss() {3353    wrap.classList.add("is-exiting");3354    setTimeout(() => host.remove(), 130);3355  }33563357  upgradeBtn.addEventListener("click", () => {3358    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3359    dismiss();3360  });3361  laterBtn.addEventListener("click", dismiss);3362  backdrop.addEventListener("click", dismiss);33633364  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3365    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3366  });33673368  document.body.appendChild(host);3369}33703371/**3372 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3373 * detector sees the page invoke navigator.credentials.create(); content/index.ts3374 * checks vault + decline state then calls this. "Save passkey to Peach"3375 * initiates the popup-context credential flow; "Not now" records a 30-day3376 * decline for the domain so we don't re-show on every page reload.3377 */3378export function showPasskeyRegistrationOffer(args: {3379  rpId: string;3380  rpName?: string;3381  userName?: string;3382  userDisplayName?: string;3383}): void {3384  const domain = location.hostname.replace(/^www\./, "");3385  const displayName = args.rpName || domain;33863387  const host = document.createElement("div");3388  host.setAttribute("data-peach-passkey-offer", "1");3389  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3390  const shadow = host.attachShadow({ mode: "closed" });33913392  const style = document.createElement("style");3393  style.textContent = `3394    :host { all: initial; }3395    .offer-wrap {3396      position: fixed;3397      top: 16px;3398      right: 16px;3399      width: 320px;3400      pointer-events: auto;3401      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3402    }3403    @keyframes o-in {3404      from { opacity: 0; transform: translateY(-6px); }3405      to   { opacity: 1; transform: translateY(0); }3406    }3407    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3408    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3409    .offer {3410      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3411      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3412      border-radius: 12px;3413      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3414      padding: 14px 14px 12px;3415      font-family: Inter, sans-serif;3416      position: relative;3417    }3418    .offer-close {3419      position: absolute;3420      top: 8px;3421      right: 8px;3422      width: 18px;3423      height: 18px;3424      border: none;3425      background: transparent;3426      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3427      cursor: pointer;3428      font-size: 14px;3429      line-height: 1;3430      padding: 0;3431    }3432    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3433    .offer-header {3434      display: flex;3435      align-items: center;3436      gap: 7px;3437      margin-bottom: 8px;3438      padding-bottom: 8px;3439      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3440    }3441    .offer-domain {3442      font-size: 12px;3443      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3444      font-family: "IBM Plex Mono", monospace;3445      overflow: hidden;3446      text-overflow: ellipsis;3447      white-space: nowrap;3448    }3449    .offer-title {3450      font-size: 13px;3451      font-weight: 500;3452      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3453      margin-bottom: 4px;3454    }3455    .offer-subtitle {3456      font-size: 11px;3457      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3458      line-height: 1.45;3459      margin-bottom: 12px;3460    }3461    .offer-btn {3462      display: block;3463      width: 100%;3464      padding: 8px 0;3465      border-radius: 7px;3466      border: none;3467      cursor: pointer;3468      font-size: 12px;3469      font-family: Inter, sans-serif;3470      font-weight: 500;3471      transition: opacity 100ms;3472      margin-bottom: 6px;3473      text-align: center;3474    }3475    .offer-btn:last-child { margin-bottom: 0; }3476    .offer-btn--accent { background: ${accentHex}; color: #fff; }3477    .offer-btn--accent:hover { opacity: 0.88; }3478    .offer-btn--ghost {3479      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3480      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3481    }3482    .offer-btn--ghost:hover { opacity: 0.75; }3483  `;3484  shadow.appendChild(style);34853486  const wrap = document.createElement("div");3487  wrap.className = "offer-wrap";3488  shadow.appendChild(wrap);34893490  const offer = document.createElement("div");3491  offer.className = "offer";3492  wrap.appendChild(offer);34933494  const closeBtn = document.createElement("button");3495  closeBtn.className = "offer-close";3496  closeBtn.type = "button";3497  closeBtn.setAttribute("aria-label", "Dismiss");3498  closeBtn.textContent = "✕";3499  offer.appendChild(closeBtn);35003501  const header = document.createElement("div");3502  header.className = "offer-header";3503  const icon = document.createElement("span");3504  icon.innerHTML = peachIconSvg();3505  const domainEl = document.createElement("span");3506  domainEl.className = "offer-domain";3507  domainEl.textContent = domain;3508  header.append(icon, domainEl);3509  offer.appendChild(header);35103511  const title = document.createElement("div");3512  title.className = "offer-title";3513  title.textContent = "This site supports passkeys.";3514  offer.appendChild(title);35153516  const subtitle = document.createElement("div");3517  subtitle.className = "offer-subtitle";3518  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3519  offer.appendChild(subtitle);35203521  const saveBtn = document.createElement("button");3522  saveBtn.className = "offer-btn offer-btn--accent";3523  saveBtn.type = "button";3524  saveBtn.textContent = "Save passkey to Peach";3525  offer.appendChild(saveBtn);35263527  const laterBtn = document.createElement("button");3528  laterBtn.className = "offer-btn offer-btn--ghost";3529  laterBtn.type = "button";3530  laterBtn.textContent = "Not now";3531  offer.appendChild(laterBtn);35323533  function dismiss(decline: boolean) {3534    if (decline) {3535      chrome.runtime.sendMessage({3536        type: "PASSKEY_OFFER_DECLINE",3537        payload: { domain },3538      }).catch(() => {});3539    }3540    wrap.classList.add("is-exiting");3541    setTimeout(() => host.remove(), 130);3542  }35433544  saveBtn.addEventListener("click", () => {3545    chrome.runtime.sendMessage({3546      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3547      payload: {3548        rpId: args.rpId,3549        rpName: args.rpName ?? displayName,3550        userName: args.userName ?? "user",3551        userDisplayName: args.userDisplayName,3552      },3553    }).catch(() => {});3554    dismiss(false);3555  });3556  laterBtn.addEventListener("click", () => dismiss(true));3557  closeBtn.addEventListener("click", () => dismiss(true));35583559  document.body.appendChild(host);3560}35613562/**3563 * State 11 — passkey available indicator. Shown when the user lands on a3564 * domain for which they already have a stored passkey. Tells them where to3565 * find it (the entry already shows in the vault list); the "Sign in with3566 * passkey" button opens the popup so they can use the platform authenticator3567 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3568 * the actual sign-in transparently, so this banner is informational only.3569 */3570export function showPasskeyAvailable(args: {3571  rpId: string;3572  userName: string;3573  fromBrowser?: "chrome" | "firefox";3574  currentBrowser?: "chrome" | "firefox" | "unknown";3575}): void {3576  const domain = location.hostname.replace(/^www\./, "");3577  const crossBrowser =3578    args.fromBrowser &&3579    args.currentBrowser &&3580    args.currentBrowser !== "unknown" &&3581    args.fromBrowser !== args.currentBrowser;35823583  const host = document.createElement("div");3584  host.setAttribute("data-peach-passkey-available", "1");3585  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3586  const shadow = host.attachShadow({ mode: "closed" });35873588  const style = document.createElement("style");3589  style.textContent = `3590    :host { all: initial; }3591    .avail-wrap {3592      position: fixed;3593      top: 16px;3594      right: 16px;3595      width: 320px;3596      pointer-events: auto;3597      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3598    }3599    @keyframes a-in {3600      from { opacity: 0; transform: translateY(-6px); }3601      to   { opacity: 1; transform: translateY(0); }3602    }3603    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3604    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3605    .avail {3606      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3607      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3608      border-radius: 12px;3609      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3610      padding: 14px 14px 12px;3611      font-family: Inter, sans-serif;3612      position: relative;3613    }3614    .avail-close {3615      position: absolute;3616      top: 8px;3617      right: 8px;3618      width: 18px;3619      height: 18px;3620      border: none;3621      background: transparent;3622      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3623      cursor: pointer;3624      font-size: 14px;3625      line-height: 1;3626      padding: 0;3627    }3628    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3629    .avail-header {3630      display: flex;3631      align-items: center;3632      gap: 7px;3633      margin-bottom: 8px;3634      padding-bottom: 8px;3635      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3636    }3637    .avail-domain {3638      font-size: 12px;3639      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3640      font-family: "IBM Plex Mono", monospace;3641    }3642    .avail-label {3643      font-size: 9px;3644      letter-spacing: 0.16em;3645      text-transform: uppercase;3646      color: ${accentHex};3647      margin-bottom: 4px;3648    }3649    .avail-user {3650      font-size: 13px;3651      font-weight: 500;3652      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3653      margin-bottom: 12px;3654      overflow: hidden;3655      text-overflow: ellipsis;3656      white-space: nowrap;3657    }3658    .avail-cross {3659      font-size: 11px;3660      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3661      line-height: 1.45;3662      margin-bottom: 12px;3663      padding: 8px;3664      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3665      border-radius: 6px;3666    }3667    .avail-btn {3668      display: block;3669      width: 100%;3670      padding: 8px 0;3671      border-radius: 7px;3672      border: none;3673      cursor: pointer;3674      font-size: 12px;3675      font-family: Inter, sans-serif;3676      font-weight: 500;3677      transition: opacity 100ms;3678      margin-bottom: 6px;3679      text-align: center;3680    }3681    .avail-btn:last-child { margin-bottom: 0; }3682    .avail-btn--accent { background: ${accentHex}; color: #fff; }3683    .avail-btn--accent:hover { opacity: 0.88; }3684    .avail-btn--ghost {3685      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3686      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3687    }3688    .avail-btn--ghost:hover { opacity: 0.75; }3689  `;3690  shadow.appendChild(style);36913692  const wrap = document.createElement("div");3693  wrap.className = "avail-wrap";3694  shadow.appendChild(wrap);36953696  const avail = document.createElement("div");3697  avail.className = "avail";3698  wrap.appendChild(avail);36993700  const closeBtn = document.createElement("button");3701  closeBtn.className = "avail-close";3702  closeBtn.type = "button";3703  closeBtn.setAttribute("aria-label", "Dismiss");3704  closeBtn.textContent = "✕";3705  avail.appendChild(closeBtn);37063707  const header = document.createElement("div");3708  header.className = "avail-header";3709  const icon = document.createElement("span");3710  icon.innerHTML = peachIconSvg();3711  const domainEl = document.createElement("span");3712  domainEl.className = "avail-domain";3713  domainEl.textContent = domain;3714  header.append(icon, domainEl);3715  avail.appendChild(header);37163717  const label = document.createElement("div");3718  label.className = "avail-label";3719  label.textContent = "PASSKEY";3720  avail.appendChild(label);37213722  const user = document.createElement("div");3723  user.className = "avail-user";3724  user.textContent = args.userName;3725  avail.appendChild(user);37263727  if (crossBrowser) {3728    const cross = document.createElement("div");3729    cross.className = "avail-cross";3730    cross.textContent =3731      args.fromBrowser === "chrome"3732        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3733        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3734    avail.appendChild(cross);3735  }37363737  const signInBtn = document.createElement("button");3738  signInBtn.className = "avail-btn avail-btn--accent";3739  signInBtn.type = "button";3740  signInBtn.textContent = "Sign in with passkey";3741  avail.appendChild(signInBtn);37423743  const passwordBtn = document.createElement("button");3744  passwordBtn.className = "avail-btn avail-btn--ghost";3745  passwordBtn.type = "button";3746  passwordBtn.textContent = "Use password instead";3747  avail.appendChild(passwordBtn);37483749  function dismiss() {3750    wrap.classList.add("is-exiting");3751    setTimeout(() => host.remove(), 130);3752  }37533754  signInBtn.addEventListener("click", () => {3755    // On Chrome: the user clicking the page's own Sign-in button is what3756    //   triggers webAuthenticationProxy → existing background flow handles it.3757    //   Our button just dismisses since the page itself drives auth.3758    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3759    //   and surface the entry for manual reference (popup view).3760    dismiss();3761    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3762  });3763  passwordBtn.addEventListener("click", dismiss);3764  closeBtn.addEventListener("click", dismiss);37653766  document.body.appendChild(host);3767}37683769/**3770 * State 7 — card silver platter. Single-card focused fill view rendered3771 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3772 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3773 * so card and login flows render identically. Multi-card list view is a3774 * follow-up; today this picks the first card.3775 */3776export function showCardSelector(3777  anchorEl: HTMLInputElement,3778  cards: CardSelectorEntry[],3779  options: CardSelectorOptions3780): () => void {3781  if (cards.length === 0) return () => {};3782  const card = cards[0]!;37833784  const host = document.createElement("div");3785  host.style.cssText = "position: absolute; z-index: 2147483647;";3786  host.style.setProperty("--peach-accent", accentHex);3787  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3788  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3789  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3790  const shadow = host.attachShadow({ mode: "closed" });37913792  const style = shadow.appendChild(document.createElement("style"));3793  style.textContent = SELECTOR_STYLES;37943795  const rect = anchorEl.getBoundingClientRect();3796  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3797  host.style.left = `${rect.left + window.scrollX}px`;3798  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;37993800  const container = shadow.appendChild(document.createElement("div"));3801  container.className = "peach-inline-popup";3802  container.setAttribute("data-theme", popupTheme);38033804  // Domain header — eyebrow communicates the card context, not the site3805  const domHdr = document.createElement("div");3806  domHdr.className = "domain-header";3807  const eyebrow = document.createElement("div");3808  eyebrow.className = "domain-eyebrow";3809  eyebrow.textContent = "Pay with Peach";3810  const domName = document.createElement("div");3811  domName.className = "domain-name";3812  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3813  domHdr.append(eyebrow, domName);3814  container.appendChild(domHdr);38153816  const platter = document.createElement("div");3817  platter.className = "card-platter";38183819  if (card.network && card.network !== "unknown") {3820    const net = document.createElement("div");3821    net.className = "cp-network";3822    net.textContent = card.network;3823    platter.appendChild(net);3824  }38253826  const nick = document.createElement("div");3827  nick.className = "cp-nickname";3828  nick.textContent = card.title;3829  platter.appendChild(nick);38303831  if (card.last4) {3832    const l4 = document.createElement("div");3833    l4.className = "cp-last4";3834    l4.textContent = `•••• ${card.last4}`;3835    platter.appendChild(l4);3836  }38373838  const meta = document.createElement("div");3839  meta.className = "cp-meta";3840  if (card.cardholderName) {3841    const name = document.createElement("span");3842    name.textContent = card.cardholderName;3843    meta.appendChild(name);3844  }3845  if (card.expMonth && card.expYear) {3846    if (card.cardholderName) {3847      const sep = document.createElement("span");3848      sep.className = "cp-meta-sep";3849      sep.textContent = "·";3850      meta.appendChild(sep);3851    }3852    const exp = document.createElement("span");3853    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3854    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3855    meta.appendChild(exp);3856  }3857  if (meta.childElementCount > 0) platter.appendChild(meta);38583859  const fillWrap = document.createElement("div");3860  fillWrap.className = "cp-fill-wrap";3861  const fillBtn = document.createElement("button");3862  fillBtn.className = "sp-fill-btn";3863  fillBtn.type = "button";3864  fillBtn.textContent = "Fill card details";3865  fillBtn.addEventListener("click", async () => {3866    if (fillBtn.disabled) return;3867    fillBtn.disabled = true;3868    fillBtn.classList.add("filled");3869    fillBtn.innerHTML = checkSvgStr();3870    const resp = await chrome.runtime.sendMessage({3871      type: "GET_ENTRY_FOR_FILL",3872      payload: { id: card.id },3873    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3874    if (resp?.ok && resp.data) options.onFill(resp.data);3875    setTimeout(() => dismiss(), 400);3876  });3877  fillWrap.appendChild(fillBtn);3878  platter.appendChild(fillWrap);38793880  // Secondary actions — copy number, copy CVC, dismiss3881  const actions = document.createElement("div");3882  actions.className = "sp-actions";38833884  function flashBtn(b: HTMLButtonElement) {3885    b.classList.add("flashed");3886    setTimeout(() => b.classList.remove("flashed"), 700);3887  }38883889  // M3/QUA-005: clipboard + background COPY both failed — show user.3890  function flashCopyError(b: HTMLButtonElement) {3891    const original = b.textContent ?? "";3892    b.textContent = "Blocked";3893    b.classList.add("flashed");3894    setTimeout(() => {3895      b.classList.remove("flashed");3896      if (b.isConnected) b.textContent = original;3897    }, 1200);3898  }38993900  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3901    const resp = await chrome.runtime.sendMessage({3902      type: "GET_ENTRY_FOR_FILL",3903      payload: { id: card.id },3904    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3905    return resp?.ok && resp.data ? resp.data : null;3906  }39073908  const copyNum = document.createElement("button");3909  copyNum.className = "sp-action-btn";3910  copyNum.type = "button";3911  copyNum.title = "Copy card number";3912  copyNum.textContent = "Copy number";3913  copyNum.addEventListener("click", async (e) => {3914    e.stopPropagation();3915    const full = await fetchFullCard();3916    if (!full?.cardNumber) return;3917    let alreadyWritten = false;3918    try {3919      await navigator.clipboard.writeText(full.cardNumber);3920      alreadyWritten = true;3921    } catch (err) {3922      console.warn("[Peach] clipboard write denied:", err);3923    }3924    const resp = await chrome.runtime.sendMessage({3925      type: "COPY",3926      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3927    }).catch(() => null) as { ok?: boolean } | null;3928    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3929    else flashCopyError(copyNum);3930  });3931  actions.appendChild(copyNum);39323933  const copyCvc = document.createElement("button");3934  copyCvc.className = "sp-action-btn";3935  copyCvc.type = "button";3936  copyCvc.title = "Copy CVC";3937  copyCvc.textContent = "Copy CVC";3938  copyCvc.addEventListener("click", async (e) => {3939    e.stopPropagation();3940    const full = await fetchFullCard();3941    if (!full?.cvc) return;3942    let alreadyWritten = false;3943    try {3944      await navigator.clipboard.writeText(full.cvc);3945      alreadyWritten = true;3946    } catch (err) {3947      console.warn("[Peach] clipboard write denied:", err);3948    }3949    const resp = await chrome.runtime.sendMessage({3950      type: "COPY",3951      payload: { text: full.cvc, label: "CVC", alreadyWritten },3952    }).catch(() => null) as { ok?: boolean } | null;3953    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3954    else flashCopyError(copyCvc);3955  });3956  actions.appendChild(copyCvc);39573958  const closeBtn = document.createElement("button");3959  closeBtn.className = "sp-action-btn";3960  closeBtn.type = "button";3961  closeBtn.title = "Dismiss";3962  closeBtn.textContent = "✕";3963  closeBtn.addEventListener("click", (e) => {3964    e.stopPropagation();3965    dismiss(true);3966  });3967  actions.appendChild(closeBtn);39683969  platter.appendChild(actions);3970  container.appendChild(platter);39713972  document.body.appendChild(host);3973  function updatePosition() {3974    const r = anchorEl.getBoundingClientRect();3975    host.style.top = `${r.bottom + window.scrollY + 5}px`;3976    host.style.left = `${r.left + window.scrollX}px`;3977  }3978  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);39793980  function onKeyDown(e: KeyboardEvent) {3981    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3982  }3983  document.addEventListener("keydown", onKeyDown);39843985  let exitScheduled = false;3986  function dismiss(userAction = false) {3987    if (exitScheduled) return;3988    exitScheduled = true;3989    stopObserving();3990    document.removeEventListener("click", outsideClick, { capture: true });3991    document.removeEventListener("keydown", onKeyDown);3992    if (userAction) options.onDismiss?.();3993    container.classList.add("is-exiting");3994    setTimeout(() => host.remove(), 130);3995  }39963997  function outsideClick(ev: MouseEvent) {3998    const path = ev.composedPath();3999    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4000  }4001  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);40024003  return dismiss;4004}