inject.ts

174.9 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type PasswordHistoryItem, 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";2223// Coarse "time since" label for the inline password-history list. Mirrors the24// main popup's helper — "roughly when", not a precise duration.25function timeSince(when: number): string {26  const secs = Math.max(0, Math.floor((Date.now() - when) / 1000));27  if (secs < 60) return "just now";28  const mins = Math.floor(secs / 60);29  if (mins < 60) return `${mins}m ago`;30  const hours = Math.floor(mins / 60);31  if (hours < 24) return `${hours}h ago`;32  const days = Math.floor(hours / 24);33  if (days < 30) return `${days}d ago`;34  const months = Math.floor(days / 30);35  if (months < 12) return `${months}mo ago`;36  return `${Math.floor(months / 12)}y ago`;37}3839let accentHex = "#E8956D";40let popupTheme: "dark" | "light" = "dark";41chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {42  const data = resp?.data;43  const name = data?.accentColor ?? "peach";44  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";45  popupTheme = data?.theme === "light" ? "light" : "dark";46});4748// 8-digit hex alpha helpers for the accent-derived shadow tokens.49// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing50// two hex digits as the alpha channel.51function withAlpha(hex: string, alpha: string): string {52  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS53  // always exposes 6-digit hex, so this is a guard against future changes54  // shipping shorthand colors that would silently break the var injection.55  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;56}5758export interface SelectorEntry {59  id: string;60  title: string;61  username?: string;62  email?: string;63  url?: string;64  hasTotp?: boolean;65  /** True when the entry also has a passkey credential attached. */66  hasPasskey?: boolean;67}6869interface SelectorOptions {70  domain?: string;71  searchableEntries?: SelectorEntry[];72  /** True when shown on a signup form — changes header label and entry-click behaviour */73  isSignup?: boolean;74  /**75   * Identity kind the current signup field is expecting. Used to avoid76   * assuming email when the user is actually filling a username.77   */78  identityKind?: IdentityKind;79  /**80   * Derived identity list (emails then usernames) for signup mode (State 10).81   * When present, renderIdentityHelper() is used instead of renderList().82   */83  savedIdentities?: SavedIdentity[];84  /**85   * Called after the user picks a saved identity (signup mode only) or86   * after successfully saving a new entry on a signup form.87   * Lets the caller fill the visible username + password fields.88   */89  onFillFields?: (username: string, password: string, email?: string) => void;90  /**91   * True when the form has both a distinct username field AND a distinct email92   * field (e.g. Name / Username / Email / Password signup forms). Enables the93   * two-step identity wizard: first pick the field type the user clicked on,94   * then pick the other, then generate a password.95   */96  hasEmailField?: boolean;97  /**98   * When true, show an inline unlock form instead of the entries list.99   * Used when the vault is locked so the user can unlock without opening100   * the popup.101   */102  locked?: boolean;103  /**104   * Called after a successful inline unlock — the caller should re-query105   * entries and re-open the selector with real data.106   */107  onUnlocked?: () => void;108  /**109   * Called when the user explicitly dismisses the selector (Escape, Tab, or110   * click outside) — NOT when an entry is selected or on auto-close.111   * Used by the caller to suppress spurious reopens on the same field.112   */113  onDismiss?: () => void;114}115116function getDomainFromUrl(url: string): string {117  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }118}119120function keySvgStr(): string {121  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="rgba(240,232,216,0.35)" stroke-width="0.95" stroke-linecap="round"><rect x="2" y="5.5" width="8" height="6" rx="1.5"/><path d="M4 5.5V4.25A2 2 0 0 1 6 2.25A2 2 0 0 1 8 4.25V5.5"/></svg>`;122}123124function plusSvgStr(): string {125  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>`;126}127128function searchSvgStr(): string {129  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><circle cx="5.25" cy="5.25" r="3.5"/><path d="M7.9 7.9l2.35 2.35"/></svg>`;130}131132function backSvgStr(): string {133  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 2.5L3.5 6l4 3.5"/></svg>`;134}135136function peachIconSvg(): string {137  // Peach body stays brand-peach regardless of `accentHex` — a sage or138  // sky accent must not turn the autofill icon green or blue. Accent139  // color still tints surrounding glow/hover halos below.140  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 240 240" fill="none" aria-hidden="true"><path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/><path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z" fill="#FFB082"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z" fill="#E5805C"/><ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/></svg>`;141}142143function checkSvgStr(): string {144  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="#5E7A42" stroke-width="1.5" stroke-linecap="round"><path d="M4 10.5L8 14.5L16 6.5"/></svg>`;145}146147function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {148  const { hostname, origin } = location;149  const parts = hostname.split(".");150  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",151    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",152    "oidc", "federation", "saml", "cas", "ldap"];153  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());154  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;155  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);156  return { origin, title, loginSubdomain };157}158159/**160 * Shows a bottom-of-page toast after filling credentials when the entry has161 * never matched the current site — offering to add the current origin to the162 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.163 */164export function showRememberSiteToast(165  pageDomain: string,166  entryId: string,167): void {168  const host = document.createElement("div");169  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";170  host.style.setProperty("--peach-accent", accentHex);171  const shadow = host.attachShadow({ mode: "closed" });172173  const style = document.createElement("style");174  style.textContent = `175    .bar {176      display:flex;align-items:center;gap:10px;padding:10px 14px;177      background:#131109;border:1px solid rgba(240,232,216,0.09);178      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);179      font-family:Inter,sans-serif;white-space:nowrap;180      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;181    }182    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }183    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }184    .yes {185      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;186      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;187    }188    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }189    .no {190      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;191      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;192    }193  `;194  shadow.appendChild(style);195196  const bar = document.createElement("div"); bar.className = "bar";197  const txt = document.createElement("span"); txt.className = "txt";198  txt.textContent = `Remember ${pageDomain} for this entry?`;199  const yesBtn = document.createElement("button"); yesBtn.className = "yes";200  yesBtn.textContent = "Remember";201  yesBtn.addEventListener("click", async () => {202    await chrome.runtime.sendMessage({203      type: "ADD_ADDITIONAL_URL",204      payload: { id: entryId, url: location.origin },205    });206    host.remove();207  });208  const noBtn = document.createElement("button"); noBtn.className = "no";209  noBtn.textContent = "Not now";210  noBtn.addEventListener("click", () => host.remove());211  bar.append(txt, yesBtn, noBtn);212  shadow.appendChild(bar);213  document.body.appendChild(host);214  setTimeout(() => host.remove(), 9000);215}216217interface SmartGenerator {218  root: HTMLElement;219  getPassword: () => string;220  /** Copy the current password to the clipboard with the standard pulse UX. */221  copy: () => Promise<void>;222}223224interface SmartGeneratorOptions {225  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */226  policy: PasswordPolicy;227  /**228   * Seed value: used as the displayed password without regenerating, e.g. the229   * password the user already typed into the page. The generator still230   * regenerates the moment any control changes.231   */232  initialPassword?: string;233  /** Fires every time the password regenerates (initial + on changes). */234  onChange?: (pw: string) => void;235}236237/**238 * Build the inline-popup smart-password generator. Mirrors the main popup's239 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset240 * pills + a policy hint that names the constraints Peach detected on the241 * page. Writing this in pure DOM rather than reusing the Solid component242 * keeps the content-script bundle small.243 */244function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {245  const policy = opts.policy ?? {};246247  // Start at site max (strongest password the site accepts), fall back to 64248  let length = policy.maxLength ?? 64;249  if (policy.minLength) length = Math.max(length, policy.minLength);250  if (length < 8) length = 8;251  if (length > 128) length = 128;252253  let upper = true;254  let lower = true;255  let numbers = true;256  let symbols = !policy.forbidsSymbols;257  if (policy.requiresSymbols) symbols = true;258  const forbiddenChars = policy.forbiddenChars ?? "";259260  let password = "";261262  const root = document.createElement("div");263  root.className = "pwgen-block";264265  const displayRow = root.appendChild(document.createElement("div"));266  displayRow.className = "pwgen-display-row";267  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;268  output.type = "text";269  output.className = "pwgen-output";270  output.setAttribute("autocomplete", "off");271  output.setAttribute("spellcheck", "false");272  output.setAttribute("autocorrect", "off");273  output.setAttribute("autocapitalize", "off");274275  const regenBtn = displayRow.appendChild(document.createElement("button"));276  regenBtn.className = "pwgen-icon-btn";277  regenBtn.type = "button";278  regenBtn.setAttribute("aria-label", "Regenerate password");279  regenBtn.title = "Regenerate";280  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>`;281282  const copyBtn = displayRow.appendChild(document.createElement("button"));283  copyBtn.className = "pwgen-icon-btn";284  copyBtn.type = "button";285  copyBtn.setAttribute("aria-label", "Copy password");286  copyBtn.title = "Copy";287  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>`;288289  const controls = root.appendChild(document.createElement("div"));290  controls.className = "pwgen-controls-row";291  const slider = controls.appendChild(document.createElement("input"));292  slider.type = "range";293  slider.className = "pwgen-slider";294  slider.min = "8";295  slider.max = "128";296  slider.value = String(length);297  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));298  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));299  const lenNum = controls.appendChild(document.createElement("span"));300  lenNum.className = "pwgen-len-num pwgen-len-num--edit";301  lenNum.textContent = String(length);302  lenNum.addEventListener("click", () => {303    const li = document.createElement("input");304    li.type = "text"; li.inputMode = "numeric";305    li.className = "pwgen-len-input"; li.value = String(length);306    lenNum.replaceWith(li);307    requestAnimationFrame(() => li.select());308    function commitLenEdit() {309      const n = parseInt(li.value, 10);310      if (!isNaN(n)) {311        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));312        slider.value = String(length);313        regenerate();314      }315      lenNum.textContent = String(length);316      li.replaceWith(lenNum);317    }318    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });319    li.addEventListener("blur", commitLenEdit);320  });321322  const pills = root.appendChild(document.createElement("div"));323  pills.className = "pwgen-pills";324325  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {326    const b = document.createElement("button");327    b.type = "button";328    b.className = `pwgen-pill ${on ? "is-on" : ""}`;329    b.textContent = label;330    b.addEventListener("click", () => {331      const next = !b.classList.contains("is-on");332      b.classList.toggle("is-on", next);333      onToggle(next);334    });335    return b;336  }337  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));338  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));339  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));340  pills.appendChild(makePill("!@#", symbols, (next) => {341    // The site forbids symbols — UI lets the user override but still warn.342    symbols = next;343    regenerate();344  }));345346  // Policy hint — surfaces what Peach read off the site so the user knows the347  // generator is already tuned to it. Only shows when something interesting348  // was detected.349  const hintParts: string[] = [];350  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);351  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);352  if (policy.requiresSymbols) hintParts.push("requires symbols");353  if (policy.forbidsSymbols) hintParts.push("no symbols");354  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);355  if (hintParts.length > 0) {356    const hint = root.appendChild(document.createElement("div"));357    hint.className = "pwgen-policy-hint";358    const accent = document.createElement("span");359    accent.className = "pwgen-hint-accent";360    accent.textContent = "site rules · ";361    const text = document.createTextNode(hintParts.join(" · "));362    hint.appendChild(accent);363    hint.appendChild(text);364  }365366  function regenerate() {367    // Falls back gracefully when the user toggles every charset off — the368    // shared generator forces lowercase in that case rather than throwing.369    password = generatePassword({370      length,371      includeUppercase: upper,372      includeLowercase: lower,373      includeNumbers: numbers,374      includeSymbols: symbols,375      forbiddenChars,376    });377    output.value = password;378    opts.onChange?.(password);379  }380381  output.addEventListener("input", () => {382    password = output.value;383    length = password.length;384    slider.value = String(Math.max(8, Math.min(128, length)));385    lenNum.textContent = String(length);386    opts.onChange?.(password);387  });388389  slider.addEventListener("input", () => {390    length = parseInt(slider.value, 10);391    lenNum.textContent = String(length);392    regenerate();393  });394  regenBtn.addEventListener("click", regenerate);395396  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;397  async function copy(): Promise<void> {398    try {399      await navigator.clipboard.writeText(password);400      copyBtn.classList.add("is-copied");401      if (copyResetTimer) clearTimeout(copyResetTimer);402      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);403    } catch {404      // Clipboard API may be denied — silently no-op; user still has regen UI.405    }406  }407  copyBtn.addEventListener("click", () => { void copy(); });408409  if (opts.initialPassword) {410    password = opts.initialPassword;411    output.value = password;412    opts.onChange?.(password);413  } else {414    regenerate();415  }416417  return {418    root,419    getPassword: () => password,420    copy,421  };422}423424export function observeAnchorPosition(425  anchorEl: HTMLElement,426  onUpdate: () => void427): () => void {428  let rafId = 0;429  let burstUntil = 0;430431  const runUpdate = () => {432    rafId = 0;433    onUpdate();434    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);435  };436  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };437  const scheduleBurst = (ms = 220) => {438    burstUntil = Math.max(burstUntil, performance.now() + ms);439    scheduleUpdate();440  };441442  const resizeObserver = new ResizeObserver(() => scheduleBurst());443  resizeObserver.observe(anchorEl);444  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);445446  const mutationObserver = new MutationObserver(() => scheduleBurst());447  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });448  if (anchorEl.parentElement) {449    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });450  }451452  const onScroll = () => scheduleUpdate();453  window.addEventListener("scroll", onScroll, true);454  window.addEventListener("resize", onScroll);455  window.visualViewport?.addEventListener("resize", onScroll);456  window.visualViewport?.addEventListener("scroll", onScroll);457  anchorEl.addEventListener("focus", () => scheduleBurst());458  anchorEl.addEventListener("input", () => scheduleBurst());459460  scheduleBurst(260);461462  return () => {463    if (rafId) cancelAnimationFrame(rafId);464    resizeObserver.disconnect();465    mutationObserver.disconnect();466    window.removeEventListener("scroll", onScroll, true);467    window.removeEventListener("resize", onScroll);468    window.visualViewport?.removeEventListener("resize", onScroll);469    window.visualViewport?.removeEventListener("scroll", onScroll);470  };471}472473export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {474  const button = document.createElement("button");475  button.type = "button";476  button.setAttribute("aria-label", "Peach autofill");477  button.title = "Fill with Peach";478  button.innerHTML = peachIconSvg();479  // position: fixed is load-bearing — not absolute. Absolute positioning480  // inherits the nearest positioned ancestor's box, which on sites with481  // overflow:hidden or sticky parents clips or offsets the icon. Fixed482  // anchors to the viewport and escapes all parent layout.483  button.style.cssText = `484    position: fixed; z-index: 2147483646;485    width: 26px; height: 26px; cursor: pointer;486    pointer-events: auto; border: none; padding: 3px;487    display: inline-flex; align-items: center; justify-content: center;488    background: transparent; border-radius: 999px;489    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;490    opacity: 0;491  `;492  button.addEventListener("mouseenter", () => {493    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;494    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;495    button.style.transform = "scale(1.08)";496  });497  button.addEventListener("mouseleave", () => {498    button.style.background = "transparent";499    button.style.boxShadow = "none";500    button.style.transform = "none";501  });502  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });503  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });504505  document.body.appendChild(button);506507  function updatePosition() {508    const rect = field.getBoundingClientRect();509    if (rect.width === 0 || rect.height === 0) {510      button.style.opacity = "0"; button.style.pointerEvents = "none";511      return;512    }513    const sz = 26;514    const inset = Math.max(5, Math.min(10, rect.height * 0.22));515    const top = rect.top + rect.height / 2 - sz / 2;516    // Clamp left so the icon stays fully inside the field's right edge, never517    // spilling onto an adjacent sibling button.518    const minLeft = rect.left + 4;519    const left = Math.max(minLeft, rect.right - sz - inset);520    // Hide if the field is too narrow to fit the icon cleanly (< 40px)521    if (rect.width < 40) {522      button.style.opacity = "0"; button.style.pointerEvents = "none";523      return;524    }525    button.style.top = `${top}px`;526    button.style.left = `${left}px`;527    button.style.opacity = "1"; button.style.pointerEvents = "auto";528  }529  updatePosition();530  requestAnimationFrame(() => { button.style.opacity = "1"; });531  const stopObserving = observeAnchorPosition(field, updatePosition);532  return () => { stopObserving(); button.remove(); };533}534535// All theme-dependent values resolve through tokens scoped to536// .peach-inline-popup[data-theme="dark|light"]. Accent variables537// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)538// are identical in both themes — only surface tokens differ. See539// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the540// theme switch — only literal brand-peach in peachIconSvg may stay raw.541const SELECTOR_STYLES = `542  :host { all: initial; }543  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }544545  .peach-inline-popup[data-theme="dark"] {546    --peach-bg:           #1a1410;547    --peach-bg-card:      #221c16;548    --peach-text:         #f5f0ea;549    --peach-text-dim:     #8a7a6a;550    --peach-text-muted:   #4a3a2a;551    --peach-border:       rgba(255,255,255,0.07);552    --peach-input-bg:     rgba(255,255,255,0.05);553    --peach-input-border: rgba(255,255,255,0.08);554  }555  .peach-inline-popup[data-theme="light"] {556    --peach-bg:           #fdf8f4;557    --peach-bg-card:      #f5ede4;558    --peach-text:         #1c1310;559    --peach-text-dim:     #6b5a4a;560    --peach-text-muted:   #a89080;561    --peach-border:       rgba(0,0,0,0.08);562    --peach-input-bg:     rgba(0,0,0,0.04);563    --peach-input-border: rgba(0,0,0,0.10);564  }565566  .peach-inline-popup {567    background: var(--peach-bg);568    border: 1px solid var(--peach-border-accent, var(--peach-border));569    border-radius: 14px;570    overflow: hidden;571    box-shadow:572      0 8px 40px var(--peach-glow, transparent),573      0 2px 12px rgba(0,0,0,0.5);574    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;575    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;576    transition: height 220ms cubic-bezier(0.16,1,0.3,1);577  }578  /* Light theme: shadow against a light page is too strong otherwise — drop both579     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */580  .peach-inline-popup[data-theme="light"] {581    box-shadow:582      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),583      0 2px 12px rgba(0,0,0,0.12);584  }585  .peach-inline-popup.is-exiting {586    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;587    pointer-events: none;588  }589590  @keyframes peach-enter {591    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }592    65%  { opacity: 1; filter: blur(0); }593    100% { opacity: 1; transform: translateY(0) scale(1); }594  }595  @keyframes peach-exit {596    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }597    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }598  }599  @keyframes peach-slide-in {600    from { opacity: 0; transform: translateX(12px); }601    to   { opacity: 1; transform: translateX(0); }602  }603  @keyframes peach-slide-back {604    from { opacity: 0; transform: translateX(-12px); }605    to   { opacity: 1; transform: translateX(0); }606  }607  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }608  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }609610  /* Domain header */611  .domain-header {612    padding: 9px 13px 7px;613    border-bottom: 1px solid var(--peach-border);614    display: flex; align-items: center; justify-content: space-between;615    gap: 8px;616  }617  .domain-header-text {618    display: flex; flex-direction: column; gap: 2px;619    min-width: 0; flex: 1;620  }621  .domain-eyebrow {622    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;623    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;624  }625  .domain-name {626    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);627    font-family: "IBM Plex Mono", monospace;628    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;629  }630  .domain-header-actions {631    display: inline-flex; align-items: center; gap: 5px;632    flex-shrink: 0;633  }634  .domain-add-btn,635  .domain-search-btn {636    flex-shrink: 0;637    width: 22px; height: 22px;638    display: inline-flex; align-items: center; justify-content: center;639    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);640    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);641    border-radius: 6px;642    color: var(--peach-accent);643    cursor: pointer; padding: 0;644    transition: background 120ms, border-color 120ms, transform 80ms;645    font-family: "IBM Plex Mono", monospace;646    font-size: 14px; line-height: 1;647  }648  .domain-add-btn:hover,649  .domain-search-btn:hover {650    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);651    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);652    transform: scale(1.06);653  }654  .domain-add-btn:active,655  .domain-search-btn:active { transform: scale(0.96); }656657  /* Search */658  .search-wrap {659    padding: 9px 12px 7px;660    border-bottom: 1px solid var(--peach-border);661  }662  .search {663    width: 100%; background: var(--peach-input-bg);664    border: 1px solid var(--peach-input-border);665    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;666    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;667    transition: border-color 120ms, box-shadow 120ms;668  }669  .search:focus {670    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);671    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);672  }673  .search::placeholder { color: var(--peach-text-muted); }674675  /* Results */676  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }677  .results::-webkit-scrollbar { display: none; }678679  /* Entry rows */680  .entry {681    display: flex; align-items: center; padding: 8px 12px;682    cursor: pointer; border-bottom: 1px solid var(--peach-border);683    transition: background 70ms; position: relative; outline: none;684  }685  .entry:last-child { border-bottom: none; }686  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }687  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }688  .entry.focused::before {689    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;690    width: 2px; border-radius: 2px;691    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);692  }693694  .entry-icon {695    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;696    background: var(--peach-input-bg); border: 1px solid var(--peach-border);697    display: flex; align-items: center; justify-content: center;698    overflow: hidden; margin-right: 10px;699  }700  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }701  .entry-icon.is-new {702    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);703    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);704    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);705  }706707  .entry-info { flex: 1; min-width: 0; }708  .entry-title {709    font-size: 12.5px; color: var(--peach-text);710    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;711    line-height: 1.3;712  }713  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }714  .entry-sub {715    font-size: 10px; color: var(--peach-text-dim);716    font-family: "IBM Plex Mono", monospace;717    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;718    margin-top: 1px;719  }720721  .totp-badge {722    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;723    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);724    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);725    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;726  }727  .passkey-badge {728    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;729    border-radius: 4px;730    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);731    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);732    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);733    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;734  }735736  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }737738  .empty-hint {739    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);740    font-family: "IBM Plex Mono", monospace;741  }742743  /* Create form */744  .create-form-wrap {745    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;746  }747  .create-head {748    display: flex; align-items: center; gap: 8px;749    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);750  }751  .back-btn {752    background: transparent; border: none; cursor: pointer;753    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;754    display: flex; align-items: center; line-height: 0;755    transition: color 100ms, background 100ms;756  }757  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }758  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }759  /* minmax(0, 1fr) caps the grid track at the popup width — without it,760     long monospace content (e.g. a 60-char generated password) would761     auto-size the track wider than the popup and overflow the right edge. */762  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }763  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }764  .f-label {765    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;766    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;767  }768  .f-input {769    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);770    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;771    font-size: 11px; font-family: "IBM Plex Mono", monospace;772    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;773  }774  .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); }775  .f-input::placeholder { color: var(--peach-text-muted); }776  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }777  .f-row { display: flex; gap: 6px; }778  .f-row .f-input { flex: 1; min-width: 0; }779  .gen-btn {780    padding: 0 10px; border-radius: 7px; border: none;781    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);782    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);783    font-size: 10px; font-family: "IBM Plex Mono", monospace;784    cursor: pointer; white-space: nowrap; flex-shrink: 0;785    display: flex; align-items: center; gap: 4px;786    transition: background 100ms;787  }788  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }789  .gen-toggle-link {790    background: none; border: none; padding: 2px 0;791    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);792    font-size: 10px; font-family: "IBM Plex Mono", monospace;793    cursor: pointer; text-align: left; transition: color 100ms;794  }795  .gen-toggle-link:hover { color: var(--peach-accent); }796  .pw-history {797    display: grid; gap: 4px; margin-top: 4px;798    max-height: 150px; overflow-y: auto; scrollbar-width: thin;799  }800  .pw-history-row {801    display: flex; align-items: center; justify-content: space-between; gap: 6px;802    padding: 5px 7px; border-radius: 7px;803    background: color-mix(in srgb, var(--peach-accent) 6%, transparent);804    border: 1px solid color-mix(in srgb, var(--peach-accent) 10%, transparent);805  }806  .pw-history-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }807  .pw-history-pw {808    font-family: "IBM Plex Mono", monospace; font-size: 11px;809    color: var(--peach-t1, #eee); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;810  }811  .pw-history-age {812    font-family: "IBM Plex Mono", monospace; font-size: 9px;813    color: color-mix(in srgb, var(--peach-accent) 55%, transparent); letter-spacing: 0.03em;814  }815  .pw-history-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }816  .pw-history-btn {817    background: none; border: none; padding: 2px 5px; border-radius: 5px;818    color: color-mix(in srgb, var(--peach-accent) 65%, transparent);819    font-size: 9px; font-family: "IBM Plex Mono", monospace; cursor: pointer;820    transition: color 100ms, background 100ms;821  }822  .pw-history-btn:hover {823    color: var(--peach-accent);824    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);825  }826  .pw-history-empty {827    font-family: "IBM Plex Mono", monospace; font-size: 10px; line-height: 1.45;828    color: color-mix(in srgb, var(--peach-accent) 55%, transparent);829    padding: 6px 8px; border-radius: 7px;830    background: color-mix(in srgb, var(--peach-accent) 5%, transparent);831    border: 1px solid color-mix(in srgb, var(--peach-accent) 9%, transparent);832  }833  .save-btn {834    width: 100%; padding: 8px; border-radius: 8px; border: none;835    background: var(--peach-accent); color: #fff; font-size: 12px;836    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;837    transition: background 120ms, box-shadow 120ms, transform 80ms;838    letter-spacing: 0.01em;839  }840  .save-btn:hover {841    background: color-mix(in srgb, var(--peach-accent) 82%, #000);842    box-shadow: 0 4px 20px var(--peach-glow, transparent);843  }844  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }845  .url-hint {846    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);847    font-family: "IBM Plex Mono", monospace; font-style: italic;848  }849850  /* Success */851  .success-wrap {852    display: flex; flex-direction: column; align-items: center;853    padding: 24px 16px 20px; gap: 8px;854    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;855  }856  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }857  .success-ring {858    width: 40px; height: 40px; border-radius: 50%;859    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);860    display: flex; align-items: center; justify-content: center;861  }862  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }863  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }864865  /* Silver platter (State 1 — single match) */866  .silver-platter {867    padding: 14px 14px 12px;868    display: flex; flex-direction: column; gap: 6px;869  }870  .sp-title {871    font-size: 14px; font-weight: 500; color: var(--peach-text);872    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;873    line-height: 1.25;874  }875  .sp-identity-row {876    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;877  }878  .sp-identity-label {879    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;880    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;881  }882  .sp-username {883    font-size: 12px; color: var(--peach-text-dim);884    font-family: "IBM Plex Mono", monospace;885    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;886    margin-bottom: 0;887  }888  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }889  .sp-fill-btn {890    width: 100%; padding: 11px; border-radius: 9px; border: none;891    background: var(--peach-accent); color: #fff;892    font-size: 13px; font-weight: 500; cursor: pointer;893    font-family: Inter, sans-serif; letter-spacing: 0.01em;894    display: flex; align-items: center; justify-content: center; min-height: 38px;895    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;896  }897  .sp-fill-btn:hover {898    filter: brightness(1.1);899    box-shadow: 0 4px 20px var(--peach-glow, transparent);900    transform: translateY(-1px);901  }902  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }903  .sp-fill-btn.filled {904    background: #16a34a; transform: none; filter: none;905    box-shadow: 0 4px 16px rgba(22,163,74,0.35);906    cursor: default;907  }908  .sp-fill-btn:disabled { cursor: default; }909  .sp-actions-group {910    margin-top: 6px;911    display: flex; flex-direction: column; gap: 4px;912  }913  .sp-actions-label {914    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;915    color: var(--peach-text-muted);916    font-family: "IBM Plex Mono", monospace;917    text-align: center;918  }919  .sp-actions {920    display: flex; gap: 4px; justify-content: space-between; align-items: center;921  }922  .sp-action-btn {923    flex: 1; height: 28px; border: none; border-radius: 6px;924    background: transparent; color: var(--peach-text-dim);925    font-size: 12px; cursor: pointer;926    transition: background 120ms ease, color 120ms ease;927    font-family: Inter, sans-serif; letter-spacing: 0.04em;928    display: inline-flex; align-items: center; justify-content: center; gap: 4px;929    white-space: nowrap; overflow: hidden;930  }931  .sp-action-btn:hover:not(:disabled) {932    background: color-mix(in srgb, var(--peach-text) 5%, transparent);933    color: var(--peach-text);934  }935  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }936  .sp-action-btn.flashed {937    color: var(--peach-accent);938    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);939  }940941  /* TOTP tray — shown below the silver-platter secondary actions */942  .sp-tray {943    margin-top: 8px;944    padding: 10px 12px;945    border-radius: 9px;946    background: var(--peach-input-bg);947    border: 1px solid var(--peach-input-border);948    display: flex; align-items: center; gap: 12px;949    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;950  }951  .sp-tray-label {952    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;953    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;954    flex-shrink: 0;955  }956  .sp-totp-code {957    font-size: 18px; font-weight: 500;958    color: var(--peach-text);959    font-family: "IBM Plex Mono", monospace;960    letter-spacing: 0.12em;961    flex: 1;962    text-align: center;963  }964  .sp-totp-ring {965    width: 22px; height: 22px; flex-shrink: 0;966  }967  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }968  .sp-totp-ring .ring-fill {969    stroke: var(--peach-accent);970    transition: stroke-dashoffset 1s linear;971    transform: rotate(-90deg);972    transform-origin: center;973  }974  .sp-totp-copy {975    background: transparent; border: none; cursor: pointer;976    padding: 4px 8px; border-radius: 5px;977    color: var(--peach-text-dim); font-size: 11px;978    font-family: Inter, sans-serif;979    transition: background 120ms, color 120ms;980  }981  .sp-totp-copy:hover {982    background: color-mix(in srgb, var(--peach-text) 5%, transparent);983    color: var(--peach-text);984  }985986  /* Card silver platter (State 7) — reuses .sp-* primary action classes */987  .card-platter {988    padding: 12px 14px 10px;989    display: flex; flex-direction: column; gap: 4px;990  }991  .cp-network {992    font-size: 10px; font-weight: 600;993    color: var(--peach-accent);994    letter-spacing: 0.08em; text-transform: uppercase;995    font-family: Inter, sans-serif;996  }997  .cp-nickname {998    font-size: 14px; font-weight: 500; color: var(--peach-text);999    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1000    line-height: 1.2;1001  }1002  .cp-last4 {1003    font-size: 12px; color: var(--peach-text-dim);1004    font-family: "IBM Plex Mono", monospace;1005    letter-spacing: 0.04em;1006    margin-top: 2px;1007  }1008  .cp-meta {1009    font-size: 11px; color: var(--peach-text-dim);1010    font-family: "IBM Plex Mono", monospace;1011    margin-top: 2px;1012    display: flex; gap: 10px; align-items: center;1013  }1014  .cp-meta-sep { opacity: 0.5; }1015  .cp-fill-wrap { margin-top: 10px; }10161017  /* Locked state */1018  .locked-wrap {1019    display: flex; flex-direction: column; align-items: stretch;1020    padding: 14px 13px 13px; gap: 9px;1021  }1022  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }1023  .locked-icon {1024    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;1025    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1026    display: flex; align-items: center; justify-content: center;1027  }1028  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }1029  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }1030  .locked-input {1031    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1032    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;1033    font-size: 11px; font-family: "IBM Plex Mono", monospace;1034    outline: none; transition: border-color 120ms, box-shadow 120ms;1035  }1036  .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); }1037  .locked-input::placeholder { color: var(--peach-text-muted); }1038  .locked-btn {1039    width: 100%; padding: 8px; border-radius: 8px; border: none;1040    background: var(--peach-accent); color: #fff; font-size: 12px;1041    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;1042    transition: background 120ms;1043    letter-spacing: 0.01em;1044    box-shadow: 0 2px 16px var(--peach-glow, transparent);1045    animation: peach-pulse-glow 2.4s ease-in-out infinite;1046  }1047  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }1048  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }1049  .locked-error {1050    font-size: 10px; color: rgba(220,80,60,0.85);1051    font-family: "IBM Plex Mono", monospace;1052  }10531054  @keyframes peach-pulse-glow {1055    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }1056    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),1057                            0 0 48px var(--peach-glow, transparent); }1058  }10591060  /* ── State 10: identity helper ─────────────────────────────── */1061  .identity-list {1062    max-height: 192px; overflow-y: auto; padding: 4px 0;1063    scrollbar-width: none;1064  }1065  .identity-list::-webkit-scrollbar { display: none; }1066  .peach-identity-row {1067    display: flex; align-items: center; gap: 10px;1068    padding: 9px 12px; cursor: pointer; border-radius: 8px;1069    transition: background 100ms ease;1070  }1071  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1072  .peach-identity-value {1073    font-family: "IBM Plex Mono", monospace; font-size: 13px;1074    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1075  }1076  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1077  .identity-search-wrap {1078    display: flex; flex-direction: column; gap: 6px;1079  }1080  .identity-mode-toggle {1081    display: inline-flex; gap: 4px; flex-wrap: wrap;1082  }1083  .identity-mode-btn {1084    border: 1px solid var(--peach-input-border);1085    background: var(--peach-input-bg);1086    color: var(--peach-text-dim);1087    border-radius: 999px;1088    padding: 4px 9px;1089    cursor: pointer;1090    font-family: "IBM Plex Mono", monospace;1091    font-size: 9px;1092    letter-spacing: 0.03em;1093    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1094  }1095  .identity-mode-btn:hover {1096    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1097    color: var(--peach-text);1098  }1099  .identity-mode-btn.is-active {1100    color: var(--peach-accent);1101    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1102    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1103  }1104  .identity-mode-btn:active { transform: translateY(1px); }1105  .identity-custom-row {1106    display: flex; flex-direction: column; gap: 2px;1107    padding: 9px 12px; cursor: pointer; border-radius: 8px;1108    transition: background 100ms ease;1109  }1110  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1111  .identity-custom-row-title {1112    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1113  }1114  .identity-custom-row-sub {1115    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1116  }1117  .identity-empty {1118    padding: 10px 12px 2px; color: var(--peach-text-dim);1119    font-size: 10px; font-family: "IBM Plex Mono", monospace;1120  }1121  .identity-alt-row {1122    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1123    border-radius: 8px; transition: background 100ms ease;1124    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1125  }1126  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1127  .identity-escape-row {1128    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1129    border-radius: 8px; transition: background 100ms ease; outline: none;1130    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1131    margin-top: 2px;1132  }1133  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1134  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1135  .identity-alt-input-wrap.open { display: flex; }1136  .identity-alt-input {1137    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1138    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1139    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1140    outline: none; transition: border-color 120ms;1141  }1142  .identity-alt-input:focus {1143    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1144    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1145  }1146  .identity-alt-confirm {1147    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1148    background: var(--peach-accent); color: #fff; font-size: 12px;1149    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1150  }1151  /* ── Generator view (after identity picked) ────────────────── */1152  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1153  .gen-confirmed {1154    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1155    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1156    border-radius: 8px;1157  }1158  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1159  .gen-confirmed-val {1160    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1161    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1162  }1163  .gen-label {1164    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1165    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1166  }1167  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1168  .gen-pw-val {1169    flex: 1; padding: 8px 10px; border-radius: 7px;1170    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1171    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1172    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1173  }1174  .gen-regen-btn {1175    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1176    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1177    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1178    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1179  }1180  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1181  .gen-fill-btn {1182    padding: 10px; border-radius: 8px; border: none;1183    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1184    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1185    transition: filter 120ms ease, transform 80ms ease;1186  }1187  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1188  .gen-fill-btn:active { transform: translateY(0); }11891190  /* ── Smart password generator (parity with main UI compact mode) ─── */1191  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1192  .pwgen-display-row {1193    display: flex; align-items: center; gap: 6px;1194    padding: 8px 10px; border-radius: 7px;1195    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1196  }1197  .pwgen-output {1198    flex: 1; min-width: 0; width: 0;1199    font-family: "IBM Plex Mono", monospace; font-size: 12px;1200    color: var(--peach-text);1201    background: transparent; border: none; outline: none; padding: 0;1202  }1203  .pwgen-icon-btn {1204    flex-shrink: 0;1205    width: 26px; height: 26px;1206    display: inline-flex; align-items: center; justify-content: center;1207    background: transparent; border: 1px solid var(--peach-input-border);1208    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1209    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1210  }1211  .pwgen-icon-btn:hover {1212    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1213    color: var(--peach-accent);1214    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1215  }1216  .pwgen-icon-btn.is-copied {1217    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1218    color: var(--peach-accent);1219    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1220  }1221  .pwgen-controls-row {1222    display: flex; align-items: center; gap: 8px;1223    flex-wrap: wrap;1224  }1225  .pwgen-slider {1226    flex: 1; min-width: 110px;1227    accent-color: var(--peach-accent);1228    cursor: pointer; height: 2px; background: transparent;1229  }1230  .pwgen-len-num {1231    font-family: "IBM Plex Mono", monospace; font-size: 11px;1232    color: var(--peach-accent); min-width: 22px; text-align: right;1233  }1234  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1235  .pwgen-len-input {1236    font-family: "IBM Plex Mono", monospace; font-size: 11px;1237    color: var(--peach-accent); width: 28px; text-align: right;1238    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1239    outline: none; padding: 0; min-width: 22px;1240  }1241  @keyframes identity-suggest-in {1242    from { opacity: 0; transform: translateY(-4px); }1243    to   { opacity: 1; transform: none; }1244  }1245  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1246    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1247  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1248  .identity-collapse-btn {1249    margin-left: auto; background: transparent; border: none; cursor: pointer;1250    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1251    line-height: 0; border-radius: 3px;1252    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1253  }1254  .identity-collapse-btn:hover { color: var(--peach-text); }1255  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1256  .identity-rows { display: grid; grid-template-rows: 1fr;1257    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1258  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1259  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1260    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1261  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1262  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1263  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1264  .identity-filter-pill {1265    padding: 2px 7px; border-radius: 999px;1266    border: 1px solid var(--peach-input-border);1267    background: transparent; color: var(--peach-text-muted);1268    font-family: "IBM Plex Mono", monospace; font-size: 9px;1269    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1270  }1271  .identity-filter-pill.is-on {1272    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1273    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1274    color: var(--peach-accent);1275  }1276  .identity-suggest-row {1277    display: flex; align-items: center; gap: 5px;1278    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1279    background: transparent; cursor: pointer; text-align: left;1280    transition: background 80ms;1281  }1282  .identity-suggest-row:hover,1283  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1284  .identity-suggest-val {1285    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1286    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1287  }1288  .identity-suggest-type {1289    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1290    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1291  }1292  .identity-suggest-type--email {1293    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1294    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1295  }1296  .identity-suggest-type--username {1297    color: var(--peach-text-muted);1298    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1299  }1300  .identity-suggest-meta {1301    font-family: "IBM Plex Mono", monospace; font-size: 9px;1302    color: var(--peach-text-muted); flex-shrink: 0;1303  }1304  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1305  .pwgen-pill {1306    padding: 3px 8px; border-radius: 999px;1307    border: 1px solid var(--peach-input-border);1308    background: transparent; color: var(--peach-text-muted);1309    font-family: "IBM Plex Mono", monospace; font-size: 9px;1310    letter-spacing: 0.06em; cursor: pointer;1311    transition: all 130ms ease;1312  }1313  .pwgen-pill.is-on {1314    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1315    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1316    color: var(--peach-accent);1317  }1318  .pwgen-pill:not(.is-on):hover {1319    color: var(--peach-text-dim);1320    border-color: var(--peach-text-muted);1321  }1322  .pwgen-policy-hint {1323    font-size: 10px; color: var(--peach-text-muted);1324    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1325    line-height: 1.3;1326  }1327  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }13281329  /* ── Save offer (after password filled) ───────────────────── */1330  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1331  .save-offer-title {1332    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1333  }1334  .save-offer-row {1335    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1336    border-radius: 7px; background: var(--peach-input-bg);1337    border: 1px solid var(--peach-input-border);1338  }1339  .save-offer-lbl {1340    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1341    font-family: "IBM Plex Mono", monospace;1342  }1343  .save-offer-val {1344    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1345    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1346  }1347  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1348  .save-offer-save {1349    flex: 1; padding: 9px; border-radius: 8px; border: none;1350    background: var(--peach-accent); color: #fff; font-size: 13px;1351    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1352  }1353  .save-offer-save:hover { filter: brightness(1.08); }1354  .save-offer-skip {1355    flex: 1; padding: 9px; border-radius: 8px; border: none;1356    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1357    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1358    font-family: Inter, sans-serif; transition: background 100ms ease;1359  }1360  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1361`;13621363export function showAutofillSelector(1364  anchorEl: HTMLInputElement,1365  entries: SelectorEntry[],1366  onSelect: (id: string) => void,1367  options: SelectorOptions = {}1368): () => void {1369  const host = document.createElement("div");1370  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1371  // when Peach's internal inputs gain focus, immediately blurring them and closing1372  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1373  // as in-bounds (v3.6.131).1374  //1375  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1376  // A plain login page whose card uses transform/filter/backdrop-filter establishes1377  // a containing block for position:fixed, so a host mounted inside it lands offset1378  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1379  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1380  // the popup ~400px off the field and clipped it behind overflow:clip — the user1381  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1382  // everything else mounts at the document root, where fixed == viewport.1383  const modalAncestor = (1384    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1385    (() => {1386      let cur: HTMLElement | null = anchorEl.parentElement;1387      while (cur && cur !== document.body) {1388        if (window.getComputedStyle(cur).position === 'fixed') return cur;1389        cur = cur.parentElement;1390      }1391      return null;1392    })()1393  );1394  host.style.cssText = `position: fixed; z-index: 2147483647;`;1395  host.style.setProperty("--peach-accent", accentHex);1396  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1397  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1398  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1399  // Hint the compositor that top/left animate during scroll repositioning so the1400  // popup stays on the GPU layer and doesn't flicker as observeAnchorPosition1401  // re-asserts its coordinates.1402  host.style.willChange = "top, left";1403  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1404  // HOST appear focused to the outside DOM. Modal focus traps that monitor1405  // focusin then see the host (mounted inside the modal) as the focused element1406  // rather than an opaque closed-shadow node, so they don't fire their1407  // "focus escaped" handler and yank focus back. Harmless outside modals.1408  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });14091410  const style = shadow.appendChild(document.createElement("style"));1411  style.textContent = SELECTOR_STYLES;14121413  const rect = anchorEl.getBoundingClientRect();1414  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1415  // applying containing-block compensation once host.parentElement is known.1416  host.style.top = `${rect.bottom + 5}px`;1417  host.style.left = `${rect.left}px`;1418  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1419  // wide single-input fields (e.g. centered email input on signup pages).1420  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1421  // expand the host after the initial measurement.1422  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1423  host.style.width = `${popupWidth}px`;14241425  const container = shadow.appendChild(document.createElement("div"));1426  container.className = "peach-inline-popup";1427  container.setAttribute("data-theme", popupTheme);14281429  const searchableEntries = options.searchableEntries ?? [];1430  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();14311432  let query = "";1433  let focusedIndex = -1;1434  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" | "edit" = "list";1435  let searchInput: HTMLInputElement | null = null;1436  let identityMode: IdentityFilterMode = "both";1437  // Tracks the silver-platter entry the user pivoted away from, so the1438  // search/list header can offer a one-click way back to it. null when the1439  // popup never showed a single-match platter (e.g. multi-match list view).1440  let silverPlatterOrigin: SelectorEntry | null = null;1441  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1442  // setInterval. Add to this list — don't fan out the dismiss function.1443  const cleanupHooks: Array<() => void> = [];14441445  // Smooth height transitions whenever content changes height.1446  // ResizeObserver fires on natural height changes; we freeze the old height,1447  // then animate to the new one so the surface never jumps.1448  {1449    let prevH = 0;1450    let blocked = false;1451    const heightRo = new ResizeObserver(([entry]) => {1452      if (blocked) return;1453      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1454      if (prevH > 0 && Math.abs(h - prevH) > 1) {1455        blocked = true;1456        container.style.height = `${prevH}px`;1457        requestAnimationFrame(() => requestAnimationFrame(() => {1458          container.style.height = `${h}px`;1459          prevH = h;1460          const onEnd = (e: TransitionEvent) => {1461            if (e.propertyName !== "height") return;1462            container.style.height = "";1463            blocked = false;1464            container.removeEventListener("transitionend", onEnd);1465          };1466          container.addEventListener("transitionend", onEnd);1467        }));1468      } else {1469        prevH = h;1470      }1471    });1472    heightRo.observe(container);1473    cleanupHooks.push(() => heightRo.disconnect());1474  }14751476  // Pre-capture the anchor field value for username prefill1477  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1478  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1479  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";14801481  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1482    const seen = new Set<string>();1483    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1484  }14851486  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1487    const q = value.trim().toLowerCase();1488    const deduped = uniqueEntries(source);1489    if (!q) return deduped.slice(0, 8);1490    return deduped.filter(e =>1491      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1492    ).slice(0, 12);1493  }14941495  function activeEntries(): SelectorEntry[] {1496    // When user is typing a search, filter across all known entries (domain matches + vault)1497    if (query.trim()) {1498      const merged = uniqueEntries([...entries, ...searchableEntries]);1499      return filterEntries(merged, query);1500    }1501    // Default: show domain matches; fall back to vault search when no matches1502    if (entries.length > 0) return entries;1503    return filterEntries(searchableEntries, "").slice(0, 8);1504  }15051506  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1507    const icon = document.createElement("div");1508    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1509    if (isNew) {1510      icon.innerHTML = plusSvgStr();1511    } else {1512      // Use the generic key glyph for all entries in the page-injected selector.1513      // Avoids disclosing vault domains to any third party and avoids needing1514      // to expose the browser favicon API to page context via web_accessible_resources.1515      void url;1516      icon.innerHTML = keySvgStr();1517    }1518    return icon;1519  }15201521  function renderIdentityHelper() {1522    currentMode = "identity-helper";1523    container.innerHTML = "";1524    focusedIndex = -1;1525    searchInput = null;15261527    const fallbackKind: IdentityKind = options.identityKind ?? "username";1528    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1529    const typedQuery = query.trim();1530    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);15311532    function applyIdentity(identity: string) {1533      if (options.hasEmailField) {1534        if (options.identityKind === "email") {1535          options.onFillFields?.("", "", identity);       // fill email field now1536          renderSecondaryIdentityStep("username", identity);1537        } else {1538          options.onFillFields?.(identity, "", "");       // fill username field now1539          renderSecondaryIdentityStep("email", identity);1540        }1541      } else {1542        options.onFillFields?.(identity, "");1543        renderGenerator(identity);1544      }1545    }15461547    function applyCustomIdentity(identity: string) {1548      const trimmed = identity.trim();1549      if (!trimmed) return;1550      applyIdentity(trimmed);1551    }15521553    // Header: "NEW ACCOUNT" + domain name1554    const hdr = container.appendChild(document.createElement("div"));1555    hdr.className = "domain-header";1556    const headText = hdr.appendChild(document.createElement("div"));1557    headText.className = "domain-header-text";1558    const eyebrow = headText.appendChild(document.createElement("div"));1559    eyebrow.className = "domain-eyebrow";1560    eyebrow.textContent = "NEW ACCOUNT";1561    const domName = headText.appendChild(document.createElement("div"));1562    domName.className = "domain-name";1563    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");15641565    const actions = hdr.appendChild(document.createElement("div"));1566    actions.className = "identity-mode-toggle";1567    for (const mode of ["both", "email", "username"] as const) {1568      const btn = actions.appendChild(document.createElement("button"));1569      btn.type = "button";1570      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1571      btn.textContent = identityFilterLabel(mode);1572      btn.setAttribute("aria-pressed", String(identityMode === mode));1573      btn.addEventListener("click", () => {1574        identityMode = mode;1575        renderIdentityHelper();1576      });1577    }15781579    const searchWrap = container.appendChild(document.createElement("div"));1580    searchWrap.className = "search-wrap identity-search-wrap";1581    const search = searchWrap.appendChild(document.createElement("input"));1582    search.className = "search";1583    search.placeholder = "search identities…";1584    search.value = query;1585    search.addEventListener("input", () => {1586      query = search.value;1587      renderIdentityHelper();1588      searchInput?.focus();1589      searchInput?.setSelectionRange(query.length, query.length);1590    });1591    search.addEventListener("keydown", (e) => {1592      if (e.key === "Escape") {1593        e.preventDefault();1594        dismiss(true);1595        return;1596      }1597      if (e.key !== "Enter") return;1598      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1599      if (exact) {1600        e.preventDefault();1601        applyIdentity(exact.value);1602        return;1603      }1604      if (!typedQuery || identities.length > 0) return;1605      e.preventDefault();1606      applyCustomIdentity(typedQuery);1607    });1608    const searchTools = searchWrap.appendChild(document.createElement("div"));1609    searchTools.className = "identity-mode-toggle";1610    const sortHint = searchTools.appendChild(document.createElement("div"));1611    sortHint.className = "identity-empty";1612    sortHint.style.padding = "0";1613    sortHint.textContent = "sorted by recent use";1614    searchInput = search;1615    const customLabel = identityMode === "both"1616      ? customKind1617      : identityMode;16181619    // Identity rows1620    const list = container.appendChild(document.createElement("div"));1621    list.className = "identity-list";1622    // Bottom fade only when the list overflows its max-height and isn't scrolled1623    // to the end. A short list (1-2 identities) shows no fade, so it never looks1624    // prematurely cut off; a long list gets the affordance, which clears on1625    // reaching the bottom.1626    const updateListFade = () => {1627      const overflowing = list.scrollHeight > list.clientHeight + 1;1628      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1629      const mask = overflowing && !atBottom1630        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1631        : "none";1632      list.style.setProperty("mask-image", mask);1633      list.style.setProperty("-webkit-mask-image", mask);1634    };1635    list.addEventListener("scroll", updateListFade);1636    if (typedQuery && identities.length === 0) {1637      const empty = list.appendChild(document.createElement("div"));1638      empty.className = "identity-empty";1639      empty.textContent = identityMode === "both"1640        ? `No match for “${typedQuery}”.`1641        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1642      const custom = list.appendChild(document.createElement("div"));1643      custom.className = "identity-custom-row";1644      const customTitle = custom.appendChild(document.createElement("div"));1645      customTitle.className = "identity-custom-row-title";1646      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1647      const customSub = custom.appendChild(document.createElement("div"));1648      customSub.className = "identity-custom-row-sub";1649      customSub.textContent = "Press Enter or click to continue.";1650      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1651    }1652    for (const id of identities) {1653      const row = list.appendChild(document.createElement("div"));1654      row.className = "peach-identity-row";1655      row.setAttribute("tabindex", "-1");1656      const val = row.appendChild(document.createElement("div"));1657      val.className = "peach-identity-value";1658      val.textContent = id.value;1659      const meta = row.appendChild(document.createElement("div"));1660      meta.className = "peach-identity-meta";1661      meta.textContent = `used ${id.useCount}×`;1662      row.addEventListener("click", () => {1663        applyIdentity(id.value);1664      });1665    }16661667    updateListFade();16681669    // Divider before "Use a different email…"1670    if (identities.length > 0) {1671      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1672    }16731674    // "Use a different email/username…" expandable row1675    const altRow = container.appendChild(document.createElement("div"));1676    altRow.className = "identity-alt-row";1677    altRow.textContent = `+ Use a different ${customLabel}…`;16781679    const altInputWrap = container.appendChild(document.createElement("div"));1680    altInputWrap.className = "identity-alt-input-wrap";1681    const altInput = altInputWrap.appendChild(document.createElement("input"));1682    altInput.className = "identity-alt-input";1683    altInput.type = "text";1684    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1685    altInput.setAttribute("autocomplete", "off");1686    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1687    altConfirm.className = "identity-alt-confirm";1688    altConfirm.type = "button";1689    altConfirm.textContent = "✓";16901691    function fillCustomIdentity() {1692      const v = altInput.value.trim();1693      if (!v) return;1694      applyCustomIdentity(v);1695    }16961697    altRow.addEventListener("click", () => {1698      altRow.style.display = "none";1699      altInputWrap.classList.add("open");1700      altInput.value = typedQuery || altInput.value;1701      altInput.focus();1702      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1703    });1704    altConfirm.addEventListener("click", fillCustomIdentity);1705    altInput.addEventListener("keydown", (e) => {1706      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1707    });17081709    // Escape hatch: user already has a vault entry for this site but it1710    // wasn't detected (different domain, old entry, etc.). Tapping this1711    // switches to the full searchable list so they can find and fill it;1712    // selecting an entry there will trigger the remember-site toast if1713    // the domain isn't already associated.1714    if ((options.searchableEntries?.length ?? 0) > 0) {1715      const escapeRow = container.appendChild(document.createElement("div"));1716      escapeRow.className = "identity-escape-row";1717      escapeRow.textContent = "I already have an account →";1718      escapeRow.setAttribute("tabindex", "0");1719      escapeRow.addEventListener("click", () => renderList());1720      escapeRow.addEventListener("keydown", (e) => {1721        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1722      });1723    }17241725    requestAnimationFrame(() => {1726      search.focus();1727      search.setSelectionRange(query.length, query.length);1728    });1729  }17301731  /**1732   * Step 2 of the contextual signup wizard.1733   * `stepKind` is the identity type to collect in this step ("email" or "username").1734   * `firstValue` is what was picked in step 1 (the other type).1735   */1736  function renderSecondaryIdentityStep(stepKind: "email" | "username", firstValue: string) {1737    currentMode = "identity-helper";1738    container.innerHTML = "";17391740    const wrap = container.appendChild(document.createElement("div"));1741    wrap.className = "gen-view";17421743    // Header1744    const hdrRow = wrap.appendChild(document.createElement("div"));1745    hdrRow.className = "domain-header";1746    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1747    eyebrow2.className = "domain-eyebrow";1748    eyebrow2.textContent = "NEW ACCOUNT";1749    const domName2 = hdrRow.appendChild(document.createElement("div"));1750    domName2.className = "domain-name";1751    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");17521753    // Confirmed first step1754    const conf = wrap.appendChild(document.createElement("div"));1755    conf.className = "gen-confirmed";1756    const confCheck = conf.appendChild(document.createElement("span"));1757    confCheck.className = "gen-confirmed-check";1758    confCheck.textContent = "✓";1759    const confVal = conf.appendChild(document.createElement("div"));1760    confVal.className = "gen-confirmed-val";1761    confVal.textContent = firstValue;17621763    const stepLbl = wrap.appendChild(document.createElement("div"));1764    stepLbl.className = "gen-label";1765    stepLbl.textContent = stepKind === "email" ? "Now choose your email" : "Now choose your username";17661767    // Filter saved identities to the correct type for this step1768    const identities = (options.savedIdentities ?? [])1769      .filter(s => s.type === stepKind)1770      .sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0))1771      .slice(0, 6);17721773    const list = wrap.appendChild(document.createElement("div"));1774    list.className = "identity-list";1775    for (const id of identities) {1776      const row = list.appendChild(document.createElement("div"));1777      row.className = "peach-identity-row";1778      row.setAttribute("tabindex", "-1");1779      const val = row.appendChild(document.createElement("div"));1780      val.className = "peach-identity-value";1781      val.textContent = id.value;1782      const meta = row.appendChild(document.createElement("div"));1783      meta.className = "peach-identity-meta";1784      meta.textContent = `used ${id.useCount}×`;1785      row.addEventListener("click", () => applySecondIdentity(id.value));1786    }17871788    // Text input for a value not in the list1789    const altInputWrap = wrap.appendChild(document.createElement("div"));1790    altInputWrap.className = "identity-alt-input-wrap open";1791    const altInput = altInputWrap.appendChild(document.createElement("input"));1792    altInput.className = "identity-alt-input";1793    altInput.type = stepKind === "email" ? "email" : "text";1794    altInput.placeholder = stepKind === "email" ? "[email protected]" : "your username";1795    altInput.setAttribute("autocomplete", "off");1796    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1797    altConfirm.className = "identity-alt-confirm";1798    altConfirm.type = "button";1799    altConfirm.textContent = "→";18001801    function applySecondIdentity(value: string) {1802      const trimmed = value.trim();1803      if (!trimmed) return;1804      // Determine final email + username order before passing to the generator1805      const [email, username] = stepKind === "email"1806        ? [trimmed, firstValue]1807        : [firstValue, trimmed];1808      if (stepKind === "email") {1809        options.onFillFields?.("", "", trimmed); // fill email field1810      } else {1811        options.onFillFields?.(trimmed, "", ""); // fill username field1812      }1813      renderGenerator(email, username);1814    }18151816    altConfirm.addEventListener("click", () => applySecondIdentity(altInput.value));1817    altInput.addEventListener("keydown", (e) => {1818      if (e.key === "Enter") { e.preventDefault(); applySecondIdentity(altInput.value); }1819    });18201821    // Skip: proceed without this field1822    const skipRow = wrap.appendChild(document.createElement("div"));1823    skipRow.className = "identity-escape-row";1824    skipRow.textContent = `Skip ${stepKind} →`;1825    skipRow.setAttribute("tabindex", "0");1826    skipRow.addEventListener("click", () => {1827      const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1828      renderGenerator(email, username);1829    });1830    skipRow.addEventListener("keydown", (e) => {1831      if (e.key === "Enter" || e.key === " ") {1832        e.preventDefault();1833        const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1834        renderGenerator(email, username);1835      }1836    });18371838    requestAnimationFrame(() => { altInput.focus(); });1839  }18401841  function renderGenerator(filledEmail: string, filledUsername?: string) {1842    container.innerHTML = "";1843    const sitePolicy = detectPasswordPolicy();18441845    const wrap = container.appendChild(document.createElement("div"));1846    wrap.className = "gen-view";18471848    // Header: domain + NEW ACCOUNT1849    const hdrRow = wrap.appendChild(document.createElement("div"));1850    hdrRow.className = "domain-header";1851    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1852    eyebrow2.className = "domain-eyebrow";1853    eyebrow2.textContent = "NEW ACCOUNT";1854    const domName2 = hdrRow.appendChild(document.createElement("div"));1855    domName2.className = "domain-name";1856    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");18571858    // Confirmed identity rows — show both username and email when both were collected1859    function confirmedRow(value: string) {1860      const conf = wrap.appendChild(document.createElement("div"));1861      conf.className = "gen-confirmed";1862      const confCheck = conf.appendChild(document.createElement("span"));1863      confCheck.className = "gen-confirmed-check";1864      confCheck.textContent = "✓";1865      const confVal = conf.appendChild(document.createElement("div"));1866      confVal.className = "gen-confirmed-val";1867      confVal.textContent = value;1868    }1869    if (filledEmail) confirmedRow(filledEmail);1870    if (filledUsername && filledUsername !== filledEmail) confirmedRow(filledUsername);18711872    const lbl = wrap.appendChild(document.createElement("div"));1873    lbl.className = "gen-label";1874    lbl.textContent = "Generate a password";18751876    let currentPw = "";1877    const smartGen = createSmartGenerator({1878      policy: sitePolicy,1879      onChange: (pw) => { currentPw = pw; },1880    });1881    wrap.appendChild(smartGen.root);18821883    const fillBtn = wrap.appendChild(document.createElement("button"));1884    fillBtn.className = "gen-fill-btn";1885    fillBtn.type = "button";1886    fillBtn.textContent = "Copy & fill";1887    fillBtn.addEventListener("click", async () => {1888      if (!currentPw) return;1889      fillBtn.disabled = true;1890      fillBtn.textContent = "Saving…";1891      // Fill the page fields first — password lands immediately.1892      options.onFillFields?.("", currentPw, "");1893      // Auto-save to vault. Fall back to the save-offer form only if the save fails1894      // (vault locked, quota exceeded, etc.) so the user sees the error and can retry.1895      const saveUsername = filledUsername || filledEmail;1896      const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;1897      try {1898        const res = await chrome.runtime.sendMessage({1899          type: "ADD_ENTRY",1900          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: currentPw, type: "login" },1901        });1902        if ((res as { ok?: boolean }).ok) {1903          showSuccess(sTitle);1904        } else {1905          renderSaveOffer(filledEmail, currentPw, filledUsername);1906        }1907      } catch {1908        renderSaveOffer(filledEmail, currentPw, filledUsername);1909      }1910    });1911  }19121913  function renderSaveOffer(filledEmail: string, filledPassword: string, filledUsername?: string) {1914    container.innerHTML = "";1915    const domain = options.domain ?? location.hostname.replace(/^www\./, "");19161917    const wrap = container.appendChild(document.createElement("div"));1918    wrap.className = "save-offer";19191920    const title = wrap.appendChild(document.createElement("div"));1921    title.className = "save-offer-title";1922    title.textContent = "Save this login to Peach?";19231924    function detailRow(label: string, value: string) {1925      const row = wrap.appendChild(document.createElement("div"));1926      row.className = "save-offer-row";1927      const lbl = row.appendChild(document.createElement("div"));1928      lbl.className = "save-offer-lbl";1929      lbl.textContent = label;1930      const val = row.appendChild(document.createElement("div"));1931      val.className = "save-offer-val";1932      val.textContent = value;1933    }19341935    detailRow("site", domain);1936    // When both username and email were collected, show both; otherwise show the identity as "email"1937    if (filledUsername) {1938      detailRow("username", filledUsername);1939      if (filledEmail) detailRow("email", filledEmail);1940    } else {1941      if (filledEmail) detailRow("email", filledEmail);1942    }1943    detailRow("password", "••••••••••••••••");19441945    const btns = wrap.appendChild(document.createElement("div"));1946    btns.className = "save-offer-btns";19471948    const saveBtn = btns.appendChild(document.createElement("button"));1949    saveBtn.className = "save-offer-save";1950    saveBtn.type = "button";1951    saveBtn.textContent = "Save";1952    saveBtn.addEventListener("click", async () => {1953      saveBtn.disabled = true;1954      saveBtn.textContent = "Saving…";1955      try {1956        // When both username and email were set, save them in the correct fields.1957        // Otherwise fall back to storing the identity as the username (current behaviour).1958        const saveUsername = filledUsername || filledEmail;1959        const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;1960        const res = await chrome.runtime.sendMessage({1961          type: "ADD_ENTRY",1962          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: filledPassword, type: "login" },1963        });1964        if ((res as { ok?: boolean }).ok) {1965          showSuccess(sTitle);1966        } else {1967          saveBtn.disabled = false;1968          saveBtn.textContent = "Save";1969        }1970      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1971    });19721973    const skipBtn = btns.appendChild(document.createElement("button"));1974    skipBtn.className = "save-offer-skip";1975    skipBtn.type = "button";1976    skipBtn.textContent = "Not now";1977    skipBtn.addEventListener("click", () => { dismiss(true); });1978  }19791980  function renderList() {1981    container.innerHTML = "";1982    focusedIndex = -1;1983    searchInput = null;1984    currentMode = "list";19851986    const current = activeEntries();19871988    // Domain header (always show) — eyebrow + domain on the left,1989    // a "+" shortcut to the create form on the right so the user is never1990    // trapped in the search list when they want to make a new entry.1991    const domHdr = document.createElement("div");1992    domHdr.className = "domain-header";1993    const headText = document.createElement("div");1994    headText.className = "domain-header-text";1995    const eyebrow = document.createElement("div");1996    eyebrow.className = "domain-eyebrow";1997    eyebrow.textContent = options.isSignup1998      ? "Sign up as"1999      : entries.length > 0 ? "Saved for this site" : "No saved login";2000    const domName = document.createElement("div");2001    domName.className = "domain-name";2002    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2003    headText.append(eyebrow, domName);2004    domHdr.appendChild(headText);20052006    if (!options.isSignup) {2007      const actions = document.createElement("div");2008      actions.className = "domain-header-actions";20092010      // Back arrow takes the place of the silver-platter's search icon when2011      // the user has pivoted away from a single-match platter — gives them2012      // a one-click way back to the original recommendation.2013      if (silverPlatterOrigin) {2014        const backBtn = document.createElement("button");2015        backBtn.className = "domain-search-btn";2016        backBtn.type = "button";2017        backBtn.setAttribute("aria-label", "Back to suggested entry");2018        backBtn.title = "Back to suggested entry";2019        backBtn.innerHTML = backSvgStr();2020        backBtn.addEventListener("click", (e) => {2021          e.stopPropagation();2022          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);2023        });2024        actions.appendChild(backBtn);2025      }20262027      const addBtn = document.createElement("button");2028      addBtn.className = "domain-add-btn";2029      addBtn.type = "button";2030      addBtn.setAttribute("aria-label", "Create new entry");2031      addBtn.title = "Create new entry";2032      addBtn.textContent = "+";2033      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2034      actions.appendChild(addBtn);20352036      domHdr.appendChild(actions);2037    }20382039    container.appendChild(domHdr);20402041    // Search — always show so user can find entries beyond the domain matches2042    const sw = document.createElement("div"); sw.className = "search-wrap";2043    searchInput = document.createElement("input");2044    searchInput.className = "search";2045    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";2046    searchInput.value = query;2047    searchInput.addEventListener("input", () => {2048      query = searchInput?.value ?? "";2049      renderList();2050      searchInput?.focus();2051      searchInput?.setSelectionRange(query.length, query.length);2052    });2053    sw.appendChild(searchInput);2054    container.appendChild(sw);20552056    // Results2057    const results = document.createElement("div");2058    results.className = "results";2059    container.appendChild(results);20602061    if (current.length === 0 && entries.length > 0) {2062      // Show a hint but don't render empty entries2063    }20642065    for (let i = 0; i < current.length; i++) {2066      const e = current[i]!;2067      const entryEl = document.createElement("div");2068      entryEl.className = "entry";2069      entryEl.dataset.id = e.id;2070      entryEl.dataset.index = String(i);2071      entryEl.setAttribute("tabindex", "-1");20722073      entryEl.appendChild(makeEntryIcon(e.url));20742075      const info = document.createElement("div"); info.className = "entry-info";2076      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;2077      const subEl = document.createElement("div"); subEl.className = "entry-sub";2078      const domain = e.url ? getDomainFromUrl(e.url) : "";2079      subEl.textContent = domain || e.username || "";2080      info.append(titleEl, subEl);2081      entryEl.appendChild(info);20822083      if (e.hasTotp) {2084        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";2085        entryEl.appendChild(badge);2086      }2087      if (e.hasPasskey) {2088        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";2089        entryEl.appendChild(badge);2090      }20912092      entryEl.addEventListener("click", () => {2093        if (options.isSignup && options.onFillFields) {2094          // Fill username, email, and leave password for the user to confirm2095          options.onFillFields(e.username ?? "", "", e.email);2096          dismiss();2097        } else {2098          onSelect(e.id);2099          dismiss();2100        }2101      });2102      results.appendChild(entryEl);2103    }21042105    // Divider before "New entry"2106    if (current.length > 0) {2107      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));2108    }21092110    // "New entry" row — always present2111    const newEl = document.createElement("div");2112    newEl.className = "entry";2113    newEl.setAttribute("tabindex", "-1");2114    newEl.appendChild(makeEntryIcon(undefined, true));21152116    const newInfo = document.createElement("div"); newInfo.className = "entry-info";2117    const newTitle = document.createElement("div");2118    newTitle.className = "entry-title is-new";2119    newTitle.textContent = `New entry for ${sTitle}`;2120    const newSub = document.createElement("div");2121    newSub.className = "entry-sub";2122    newSub.textContent = sOrigin;2123    newInfo.append(newTitle, newSub);2124    newEl.appendChild(newInfo);2125    newEl.addEventListener("click", showCreateForm);2126    results.appendChild(newEl);21272128    // Focus search if present2129    if (searchInput) {2130      requestAnimationFrame(() => {2131        searchInput?.focus();2132        // Seed query (from type-to-search or domain-search-btn) lands at the2133        // end so the next keystroke extends it, not overwrites.2134        searchInput?.setSelectionRange(query.length, query.length);2135      });2136    }2137  }21382139  function setFocused(idx: number) {2140    const all = container.querySelectorAll<HTMLElement>(".entry");2141    all.forEach((el, i) => el.classList.toggle("focused", i === idx));2142    focusedIndex = idx;2143    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });2144  }21452146  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {2147    const typed = identities.filter(s => s.type === fieldType);2148    if (!typed.length) return;2149    let collapsed = false;2150    let suppressNextFocus = false;21512152    const list = g.appendChild(document.createElement("div"));2153    list.className = "identity-suggest-list";2154    list.style.display = "none";21552156    // Collapse toggle — sits alone now that filter pills are gone2157    const collapseRow = list.appendChild(document.createElement("div"));2158    collapseRow.className = "identity-filter-row";2159    collapseRow.style.justifyContent = "flex-end";2160    const collapseBtn = collapseRow.appendChild(document.createElement("button"));2161    collapseBtn.type = "button";2162    collapseBtn.className = "identity-collapse-btn";2163    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>`;2164    collapseBtn.addEventListener("mousedown", (e) => {2165      e.preventDefault();2166      collapsed = !collapsed;2167      collapseBtn.classList.toggle("is-collapsed", collapsed);2168      rowsWrapper.classList.toggle("is-collapsed", collapsed);2169    });21702171    const rowsWrapper = list.appendChild(document.createElement("div"));2172    rowsWrapper.className = "identity-rows";2173    const rows = rowsWrapper.appendChild(document.createElement("div"));2174    rows.className = "identity-rows-inner";21752176    // Bottom fade only when the list actually overflows and isn't scrolled to2177    // the end — a static mask-image fades the last row even on a 1-2 item list2178    // that fits entirely, making it look cut off. Driven off live scroll state.2179    const updateRowsFade = () => {2180      const overflowing = rows.scrollHeight > rows.clientHeight + 1;2181      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;2182      const mask = overflowing && !atBottom2183        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"2184        : "none";2185      rows.style.setProperty("mask-image", mask);2186      rows.style.setProperty("-webkit-mask-image", mask);2187    };2188    rows.addEventListener("scroll", updateRowsFade);21892190    // Hides the list and removes the document-level click watcher.2191    function hideList() {2192      list.style.display = "none";2193      document.removeEventListener("mousedown", onDocMousedown, { capture: true });2194    }21952196    // Dismiss list on any mousedown that originates outside the popup's shadow2197    // DOM. This is the ONLY close trigger for the list — blur is intentionally2198    // NOT used, because modal focus traps fire blur without a mousedown (they2199    // call element.focus() programmatically in response to focusin/focusout),2200    // which caused the list to vanish before the user could pick from it.2201    function onDocMousedown(e: MouseEvent) {2202      if (e.composedPath().includes(host)) return;2203      hideList();2204    }22052206    function pick(value: string) {2207      inp.value = value;2208      hideList();2209      suppressNextFocus = true;2210      inp.focus();2211      // If a focus trap intercepts inp.focus() and redirects to anchorEl before2212      // inp ever fires its focus event, suppressNextFocus would strand the user.2213      // Clear after a short window so subsequent clicks still work.2214      setTimeout(() => { suppressNextFocus = false; }, 120);2215    }22162217    function render() {2218      const q = inp.value.toLowerCase();2219      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2220      rows.innerHTML = "";2221      if (!filtered.length) { hideList(); return; }2222      for (const s of filtered) {2223        const row = rows.appendChild(document.createElement("button"));2224        row.type = "button"; row.className = "identity-suggest-row";2225        const val = row.appendChild(document.createElement("span"));2226        val.className = "identity-suggest-val"; val.textContent = s.value;2227        const meta = row.appendChild(document.createElement("span"));2228        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2229        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2230        row.addEventListener("keydown", (e) => {2231          if (e.key === "ArrowDown") {2232            e.preventDefault();2233            (row.nextElementSibling as HTMLElement | null)?.focus();2234          } else if (e.key === "ArrowUp") {2235            e.preventDefault();2236            const prev = row.previousElementSibling as HTMLElement | null;2237            if (prev) prev.focus();2238            else inp.focus();2239          } else if (e.key === "Enter" || e.key === " ") {2240            e.preventDefault();2241            pick(s.value);2242          } else if (e.key === "Escape") {2243            e.preventDefault();2244            hideList();2245            suppressNextFocus = true;2246            inp.focus();2247          }2248        });2249        // Row blur only fires during keyboard navigation (arrow keys / Tab).2250        // Focus traps don't produce row blur events since rows aren't focused2251        // when the trap fires; this handler is therefore trap-safe.2252        row.addEventListener("blur", (e) => {2253          const rt = (e as FocusEvent).relatedTarget as Node | null;2254          if (rt && (rt === inp || list.contains(rt))) return;2255          setTimeout(() => { hideList(); }, 150);2256        });2257      }2258      list.style.display = "";2259      updateRowsFade();2260      // Register the close-on-outside-click watcher each time the list shows.2261      // addEventListener deduplicates identical (fn, options) pairs, so2262      // re-rendering on input events does not stack up listeners.2263      document.addEventListener("mousedown", onDocMousedown, { capture: true });2264    }22652266    inp.addEventListener("focus", () => {2267      if (suppressNextFocus) { suppressNextFocus = false; return; }2268      render();2269    });2270    inp.addEventListener("input", render);2271    inp.addEventListener("keydown", (e) => {2272      if (list.style.display === "none") return;2273      if (e.key === "ArrowDown" && !collapsed) {2274        e.preventDefault();2275        (rows.firstElementChild as HTMLElement | null)?.focus();2276      } else if (e.key === "Escape") {2277        e.preventDefault();2278        hideList();2279      } else if (e.key === "Tab") {2280        // Tab moves focus away intentionally — close the list.2281        hideList();2282      }2283    });2284    // No blur handler on inp. Blur fires for ANY focus movement including2285    // programmatic focus() calls from modal focus traps, which caused the list2286    // to close before the user could interact. The document mousedown listener2287    // (registered in render()) handles intentional click-outside dismissal,2288    // and the keydown handler above covers keyboard Tab/Escape.22892290    // Ensure the watcher is removed if the main popup is dismissed while the2291    // list is visible.2292    cleanupHooks.push(hideList);2293  }22942295  async function showCreateForm() {2296    currentMode = "create";2297    container.innerHTML = "";22982299    // Guard: the service worker may lock the vault between when the selector2300    // opens and when the user clicks "New entry". Show the inline unlock form2301    // instead of silently failing on save.2302    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2303    if (!statusRes?.unlocked) {2304      renderLocked();2305      return;2306    }23072308    // Detect page password policy once for this form — reused on every2309    // regenerate click so the user always gets a compliant password.2310    const sitePolicy = detectPasswordPolicy();23112312    // Fetch identities on-demand — they're passed in signup context but not2313    // in login/search context where the user still clicks "New entry".2314    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];2315    if (!formIdentities.length) {2316      try {2317        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;2318        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;2319      } catch { /* silent fallback */ }2320    }23212322    const wrap = document.createElement("div");2323    wrap.className = "create-form-wrap";23242325    // Header2326    const head = document.createElement("div"); head.className = "create-head";2327    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2328    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>`;2329    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2330    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2331    head.append(backBtn, lbl);23322333    // Body2334    const body = document.createElement("div"); body.className = "create-body";23352336    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2337      const g = document.createElement("div"); g.className = "f-group";2338      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2339      const inp = document.createElement("input"); inp.className = "f-input";2340      g.append(l, inp); return { g, inp };2341    }23422343    // Title2344    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2345    body.appendChild(tg.g);23462347    // URL2348    const ug = fGroup("website");2349    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2350    if (loginSubdomain) {2351      const h = document.createElement("div"); h.className = "url-hint";2352      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2353    }2354    body.appendChild(ug.g);23552356    // Username — pre-fill from anchor if it doesn't look like an email2357    const xg = fGroup("username");2358    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2359    xg.inp.placeholder = "johndoe";2360    xg.inp.setAttribute("autocomplete", "off");2361    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2362    body.appendChild(xg.g);23632364    // Email — pre-fill from anchor if it looks like an email2365    const eg = fGroup("email");2366    (eg.inp as HTMLInputElement).type = "email";2367    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2368    eg.inp.placeholder = "[email protected]";2369    eg.inp.setAttribute("autocomplete", "off");2370    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2371    body.appendChild(eg.g);23722373    // Password — full smart generator with charset pills + length slider +2374    // policy hint. Mirrors the main UI's compact generator so users get the2375    // same controls inline as in the popup.2376    const pg = fGroup("password");2377    pg.inp.remove(); // smartGen provides its own display — no separate input needed2378    let currentPassword = prePassword || "";2379    const smartGen = createSmartGenerator({2380      policy: sitePolicy,2381      initialPassword: prePassword || undefined,2382      onChange: (pw) => { currentPassword = pw; },2383    });2384    pg.g.appendChild(smartGen.root);2385    body.appendChild(pg.g);23862387    // Save2388    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2389    saveBtn.textContent = "Save entry";2390    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2391    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2392    saveBtn.addEventListener("click", async () => {2393      const title = tg.inp.value.trim();2394      const pw = currentPassword.trim();2395      const username = xg.inp.value.trim();2396      const email = eg.inp.value.trim();2397      if (!title) {2398        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2399        showFormError("Entry needs a title");2400        return;2401      }2402      if (!pw) {2403        showFormError("Entry needs a password — tap regen to make one");2404        return;2405      }2406      errEl.style.display = "none";2407      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2408      try {2409        const res = await chrome.runtime.sendMessage({2410          type: "ADD_ENTRY",2411          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2412        });2413        if ((res as { ok?: boolean }).ok) {2414          // Fill the detected form. onFillFields uses whichever identity the2415          // page anchored on — the vault captures both username and email.2416          options.onFillFields?.(username || email, pw);2417          showSuccess(title);2418        } else {2419          const err = (res as { error?: string })?.error;2420          const errMsg = err === "vault_locked"2421            ? "Vault locked — open Peach to save"2422            : err === "STORAGE_QUOTA_EXCEEDED"2423              ? "Out of storage — open Peach → Settings to free space"2424              : err2425                ? `Could not save: ${err}`2426                : "Could not save entry";2427          showFormError(errMsg);2428          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2429        }2430      } catch (e) {2431        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2432        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2433      }2434    });2435    body.appendChild(saveBtn);2436    body.appendChild(errEl);24372438    wrap.append(head, body);2439    container.appendChild(wrap);2440    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2441  }24422443  function showSuccess(title: string) {2444    currentMode = "success";2445    container.innerHTML = "";2446    const wrap = document.createElement("div"); wrap.className = "success-wrap";2447    const ring = document.createElement("div"); ring.className = "success-ring";2448    ring.innerHTML = checkSvgStr();2449    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2450    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2451    wrap.append(ring, t, s);2452    container.appendChild(wrap);2453    setTimeout(() => dismiss(), 1600);2454  }24552456  function flashActionBtn(btn: HTMLButtonElement) {2457    btn.classList.add("flashed");2458    setTimeout(() => btn.classList.remove("flashed"), 700);2459  }24602461  // M3/QUA-005: when both the direct clipboard write and the background COPY2462  // fallback fail, briefly show the user that the copy did not happen.2463  function flashCopyError(btn: HTMLButtonElement) {2464    const original = btn.textContent ?? "";2465    btn.textContent = "Blocked";2466    btn.classList.add("flashed");2467    setTimeout(() => {2468      btn.classList.remove("flashed");2469      if (btn.isConnected) btn.textContent = original;2470    }, 1200);2471  }24722473  function renderSilverPlatter(entry: SelectorEntry) {2474    container.innerHTML = "";2475    searchInput = null;2476    focusedIndex = -1;2477    currentMode = "silver-platter";2478    silverPlatterOrigin = entry;24792480    const domHdr = document.createElement("div");2481    domHdr.className = "domain-header";2482    const headText = document.createElement("div");2483    headText.className = "domain-header-text";2484    const eyebrow = document.createElement("div");2485    eyebrow.className = "domain-eyebrow";2486    eyebrow.textContent = "Saved for this site";2487    const domName = document.createElement("div");2488    domName.className = "domain-name";2489    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2490    headText.append(eyebrow, domName);2491    domHdr.appendChild(headText);2492    if (!options.isSignup) {2493      const actions = document.createElement("div");2494      actions.className = "domain-header-actions";24952496      // Search shortcut — same idea as type-to-search below, but visible so2497      // the user can discover that another entry is reachable from a2498      // single-match platter. Sits to the left of the create button.2499      const searchBtn = document.createElement("button");2500      searchBtn.className = "domain-search-btn";2501      searchBtn.type = "button";2502      searchBtn.setAttribute("aria-label", "Search for a different entry");2503      searchBtn.title = "Search for a different entry";2504      searchBtn.innerHTML = searchSvgStr();2505      searchBtn.addEventListener("click", (e) => {2506        e.stopPropagation();2507        query = "";2508        renderList();2509      });2510      actions.appendChild(searchBtn);25112512      const addBtn = document.createElement("button");2513      addBtn.className = "domain-add-btn";2514      addBtn.type = "button";2515      addBtn.setAttribute("aria-label", "Create new entry");2516      addBtn.title = "Create new entry";2517      addBtn.textContent = "+";2518      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2519      actions.appendChild(addBtn);25202521      domHdr.appendChild(actions);2522    }2523    container.appendChild(domHdr);25242525    const platter = document.createElement("div");2526    platter.className = "silver-platter";25272528    const titleEl = document.createElement("div");2529    titleEl.className = "sp-title";2530    titleEl.textContent = entry.title;2531    platter.appendChild(titleEl);25322533    if (entry.email) {2534      const emailEl = document.createElement("div");2535      emailEl.className = "sp-identity-row";2536      const emailLbl = document.createElement("span");2537      emailLbl.className = "sp-identity-label";2538      emailLbl.textContent = "email";2539      const emailVal = document.createElement("span");2540      emailVal.className = "sp-username";2541      emailVal.textContent = entry.email;2542      emailEl.append(emailLbl, emailVal);2543      platter.appendChild(emailEl);2544    }25452546    if (entry.username) {2547      const userEl = document.createElement("div");2548      userEl.className = "sp-identity-row";2549      const userLbl = document.createElement("span");2550      userLbl.className = "sp-identity-label";2551      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2552      const userVal = document.createElement("span");2553      userVal.className = "sp-username";2554      userVal.textContent = entry.username;2555      userEl.append(userLbl, userVal);2556      platter.appendChild(userEl);2557    }25582559    const fillBtn = document.createElement("button");2560    fillBtn.className = "sp-fill-btn";2561    fillBtn.type = "button";2562    fillBtn.textContent = "Fill credentials";2563    fillBtn.addEventListener("click", () => {2564      if (fillBtn.disabled) return;2565      fillBtn.disabled = true;2566      fillBtn.classList.add("filled");2567      fillBtn.innerHTML = checkSvgStr();2568      // Fire the fill, then exit via the standard exit animation. The fill2569      // itself is async (handled in index.ts) — by 400ms the form is filled2570      // and the popup begins its exit. Total dwell from click to host2571      // removal: 400ms + 130ms (exit animation) = 530ms.2572      onSelect(entry.id);2573      setTimeout(() => dismiss(), 400);2574    });2575    platter.appendChild(fillBtn);25762577    const actionsGroup = document.createElement("div");2578    actionsGroup.className = "sp-actions-group";2579    const actionsLabel = document.createElement("div");2580    actionsLabel.className = "sp-actions-label";2581    actionsLabel.textContent = "Copy";2582    actionsGroup.appendChild(actionsLabel);25832584    const actions = document.createElement("div");2585    actions.className = "sp-actions";2586    actionsGroup.appendChild(actions);25872588    if (entry.email) {2589      const copyEmail = document.createElement("button");2590      copyEmail.className = "sp-action-btn";2591      copyEmail.type = "button";2592      copyEmail.title = "Copy email";2593      copyEmail.textContent = "Email";2594      copyEmail.addEventListener("click", async (e) => {2595        e.stopPropagation();2596        let alreadyWritten = false;2597        try {2598          await navigator.clipboard.writeText(entry.email!);2599          alreadyWritten = true;2600        } catch (err) {2601          console.warn("[Peach] clipboard write denied:", err);2602        }2603        const resp = await chrome.runtime.sendMessage({2604          type: "COPY",2605          payload: { text: entry.email, label: "Email", alreadyWritten },2606        }).catch(() => null) as { ok?: boolean } | null;2607        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2608        else flashCopyError(copyEmail);2609      });2610      actions.appendChild(copyEmail);2611    }26122613    const copyU = document.createElement("button");2614    copyU.className = "sp-action-btn";2615    copyU.type = "button";2616    const usernameIsEmail = entry.username?.includes("@") ?? false;2617    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2618    copyU.textContent = usernameIsEmail ? "Email" : "Username";2619    copyU.disabled = !entry.username;2620    copyU.addEventListener("click", async (e) => {2621      e.stopPropagation();2622      if (!entry.username) return;2623      let alreadyWritten = false;2624      try {2625        await navigator.clipboard.writeText(entry.username);2626        alreadyWritten = true;2627      } catch (err) {2628        console.warn("[Peach] clipboard write denied:", err);2629      }2630      const resp = await chrome.runtime.sendMessage({2631        type: "COPY",2632        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2633      }).catch(() => null) as { ok?: boolean } | null;2634      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2635      else flashCopyError(copyU);2636    });2637    actions.appendChild(copyU);26382639    const copyP = document.createElement("button");2640    copyP.className = "sp-action-btn";2641    copyP.type = "button";2642    copyP.title = "Copy password";2643    copyP.textContent = "Password";2644    copyP.addEventListener("click", async (e) => {2645      e.stopPropagation();2646      const resp = await chrome.runtime.sendMessage({2647        type: "GET_ENTRY_FOR_FILL",2648        payload: { id: entry.id },2649      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2650      if (!resp?.ok || !resp.data?.password) return;2651      let alreadyWritten = false;2652      try {2653        await navigator.clipboard.writeText(resp.data.password);2654        alreadyWritten = true;2655      } catch (err) {2656        console.warn("[Peach] clipboard write denied:", err);2657      }2658      const copyResp = await chrome.runtime.sendMessage({2659        type: "COPY",2660        payload: { text: resp.data.password, label: "Password", alreadyWritten },2661      }).catch(() => null) as { ok?: boolean } | null;2662      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2663      else flashCopyError(copyP);2664    });2665    actions.appendChild(copyP);26662667    let trayEl: HTMLDivElement | null = null;2668    let trayInterval: ReturnType<typeof setInterval> | null = null;26692670    function closeTray() {2671      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2672      trayEl?.remove();2673      trayEl = null;2674    }2675    // Register so dismiss() will close the tray and clear the interval2676    // even if the user dismisses without explicitly closing the tray.2677    cleanupHooks.push(closeTray);26782679    async function openTOTPTray() {2680      // Fetch the current TOTP code from the background. The raw base32 seed2681      // never enters the content script (SEV-3-C): we receive the live 6-digit2682      // code plus the seconds remaining, count down locally, and re-fetch a2683      // fresh code only when the 30s window rolls over.2684      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2685        const r = await chrome.runtime.sendMessage({2686          type: "GET_ENTRY_FOR_FILL",2687          payload: { id: entry.id },2688        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2689        if (!r?.ok || !r.data?.totpCode) return null;2690        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2691      }2692      let current = await fetchCode();2693      if (!current) return;26942695      trayEl = document.createElement("div");2696      trayEl.className = "sp-tray";26972698      const label = document.createElement("span");2699      label.className = "sp-tray-label";2700      label.textContent = "2FA";2701      trayEl.appendChild(label);27022703      const codeEl = document.createElement("div");2704      codeEl.className = "sp-totp-code";2705      trayEl.appendChild(codeEl);27062707      const ringNs = "http://www.w3.org/2000/svg";2708      const ring = document.createElementNS(ringNs, "svg");2709      ring.setAttribute("class", "sp-totp-ring");2710      ring.setAttribute("viewBox", "0 0 24 24");2711      const trackC = document.createElementNS(ringNs, "circle");2712      trackC.setAttribute("class", "ring-track");2713      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2714      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2715      const fillC = document.createElementNS(ringNs, "circle");2716      fillC.setAttribute("class", "ring-fill");2717      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2718      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2719      fillC.setAttribute("stroke-linecap", "round");2720      fillC.setAttribute("stroke-dasharray", "62.83");2721      ring.append(trackC, fillC);2722      trayEl.appendChild(ring);27232724      const copyBtn = document.createElement("button");2725      copyBtn.className = "sp-totp-copy";2726      copyBtn.type = "button";2727      copyBtn.textContent = "Copy";2728      trayEl.appendChild(copyBtn);27292730      function render() {2731        const { code, remaining } = current!;2732        // Group as "847 291" — easier to read than "847291"2733        codeEl.textContent = code.length === 62734          ? `${code.slice(0, 3)} ${code.slice(3)}`2735          : code;2736        // Ring fills counter-clockwise as time elapses: dashoffset goes from2737        // 0 (full ring) to 62.83 (empty) over the 30s window.2738        const fraction = (30 - remaining) / 30;2739        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2740      }2741      render();2742      trayInterval = setInterval(async () => {2743        if (!current) return;2744        current = { code: current.code, remaining: current.remaining - 1 };2745        // Window rolled over — pull a fresh code from the background.2746        if (current.remaining <= 0) {2747          const next = await fetchCode();2748          current = next ?? { code: current.code, remaining: 30 };2749        }2750        render();2751      }, 1000);27522753      copyBtn.addEventListener("click", async (e) => {2754        e.stopPropagation();2755        const code = current?.code;2756        if (!code) return;2757        let alreadyWritten = false;2758        try {2759          await navigator.clipboard.writeText(code);2760          alreadyWritten = true;2761        } catch (err) {2762          console.warn("[Peach] clipboard write denied:", err);2763        }2764        const resp = await chrome.runtime.sendMessage({2765          type: "COPY",2766          payload: { text: code, label: "TOTP", alreadyWritten },2767        }).catch(() => null) as { ok?: boolean } | null;2768        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2769        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2770      });27712772      platter.appendChild(trayEl);2773    }27742775    const editBtn = document.createElement("button");2776    editBtn.className = "sp-action-btn sp-action-edit";2777    editBtn.type = "button";2778    editBtn.title = "Edit entry";2779    editBtn.textContent = "Edit";2780    editBtn.addEventListener("click", (e) => {2781      e.stopPropagation();2782      closeTray();2783      void renderInlineEdit(entry);2784    });2785    actions.appendChild(editBtn);27862787    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2788    // "···" toggle was zero-savings (the toggle button took the same space2789    // the "2FA" label needed) and made the code one extra click away.2790    if (entry.hasTotp) void openTOTPTray();27912792    platter.appendChild(actionsGroup);2793    container.appendChild(platter);2794  }27952796  /**2797   * Inline-popup edit mode. Swaps the silver platter for an editable form2798   * over the same shadow-DOM surface so the user never leaves the page.2799   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2800   * with the new fields. Cancel returns without writing.2801   */2802  async function renderInlineEdit(summary: SelectorEntry) {2803    currentMode = "edit";2804    container.innerHTML = "";2805    const wrap = document.createElement("div");2806    wrap.className = "create-form-wrap";28072808    const head = document.createElement("div");2809    head.className = "create-head";2810    const back = document.createElement("button");2811    back.className = "back-btn";2812    back.type = "button";2813    back.title = "Cancel";2814    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>`;2815    back.addEventListener("click", () => renderSilverPlatter(summary));2816    head.appendChild(back);2817    const headLbl = document.createElement("div");2818    headLbl.className = "create-label";2819    headLbl.textContent = "Edit entry";2820    head.appendChild(headLbl);2821    wrap.appendChild(head);28222823    const body = document.createElement("div");2824    body.className = "create-body";28252826    // Loading shimmer while we fetch the full entry2827    const loading = document.createElement("div");2828    loading.className = "empty-hint";2829    loading.textContent = "loading…";2830    body.appendChild(loading);2831    wrap.appendChild(body);2832    container.appendChild(wrap);28332834    const [res, idRes] = await Promise.all([2835      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2836      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2837      chrome.runtime.sendMessage({2838        type: "GET_ENTRY_FOR_EDIT",2839        payload: { id: summary.id },2840      }).catch(() => null),2841      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2842    ]);2843    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string; passwordHistory?: PasswordHistoryItem[] } } | null;2844    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];28452846    if (!entryRes || !entryRes.ok || !entryRes.data) {2847      loading.textContent = "couldn't load this entry. try again from the popup.";2848      return;2849    }2850    body.innerHTML = "";28512852    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2853      const group = document.createElement("div");2854      group.className = "f-group";2855      const lbl = document.createElement("div");2856      lbl.className = "f-label";2857      lbl.textContent = label;2858      const input = document.createElement("input");2859      input.className = "f-input";2860      input.type = type;2861      input.value = value;2862      input.autocomplete = "off";2863      group.append(lbl, input);2864      body.appendChild(group);2865      return { g: group, inp: input };2866    }28672868    const titleInput = field("title", entryRes.data.title ?? "").inp;2869    const urlInput = field("url", entryRes.data.url ?? "").inp;2870    urlInput.classList.add("url-f");2871    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2872    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2873    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2874    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2875    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");28762877    // Password row with reveal toggle + generator2878    const pwGroup = document.createElement("div");2879    pwGroup.className = "f-group";2880    const pwLbl = document.createElement("div");2881    pwLbl.className = "f-label";2882    pwLbl.textContent = "password";2883    const pwRow = document.createElement("div");2884    pwRow.className = "f-row";2885    const pwInput = document.createElement("input");2886    pwInput.className = "f-input";2887    pwInput.type = "password";2888    pwInput.value = entryRes.data.password ?? "";2889    pwInput.autocomplete = "new-password";2890    const revealBtn = document.createElement("button");2891    revealBtn.className = "gen-btn";2892    revealBtn.type = "button";2893    revealBtn.textContent = "show";2894    revealBtn.addEventListener("click", () => {2895      const reveal = pwInput.type === "password";2896      pwInput.type = reveal ? "text" : "password";2897      revealBtn.textContent = reveal ? "hide" : "show";2898    });2899    pwRow.append(pwInput, revealBtn);2900    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2901    editSmartGen.root.style.display = "none";2902    let editGenVisible = false;2903    const genToggleBtn = document.createElement("button");2904    genToggleBtn.className = "gen-toggle-link";2905    genToggleBtn.type = "button";2906    genToggleBtn.textContent = "⚙ generate";2907    genToggleBtn.addEventListener("click", () => {2908      editGenVisible = !editGenVisible;2909      pwRow.style.display = editGenVisible ? "none" : "";2910      editSmartGen.root.style.display = editGenVisible ? "" : "none";2911      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2912    });2913    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);29142915    // Past-password history: reveal, copy, or restore a previously-used value.2916    // Rows are masked by default; "use" loads the old value into the editor so2917    // the standard save flow records the swap (no separate write path). The2918    // toggle is always present (matching the main popup) so the affordance is2919    // discoverable — even before any history exists it explains how it fills.2920    const history = entryRes.data.passwordHistory ?? [];2921    {2922      const histList = document.createElement("div");2923      histList.className = "pw-history";2924      histList.style.display = "none";2925      let histVisible = false;29262927      const restLabel = history.length ? `↺ history (${history.length})` : "↺ history";2928      const histToggle = document.createElement("button");2929      histToggle.className = "gen-toggle-link";2930      histToggle.type = "button";2931      histToggle.textContent = restLabel;2932      histToggle.addEventListener("click", () => {2933        histVisible = !histVisible;2934        histList.style.display = histVisible ? "" : "none";2935        histToggle.textContent = histVisible ? "↺ hide history" : restLabel;2936      });29372938      if (history.length === 0) {2939        const empty = document.createElement("div");2940        empty.className = "pw-history-empty";2941        empty.textContent = "No earlier passwords yet. When you change this password, the old one is saved here so you can copy or restore it.";2942        histList.appendChild(empty);2943      }29442945      for (const item of history) {2946        const row = document.createElement("div");2947        row.className = "pw-history-row";2948        const main = document.createElement("div");2949        main.className = "pw-history-main";2950        const pwText = document.createElement("div");2951        pwText.className = "pw-history-pw";2952        let revealed = false;2953        const mask = "••••••••••••";2954        pwText.textContent = mask;2955        const age = document.createElement("div");2956        age.className = "pw-history-age";2957        age.textContent = timeSince(item.changedAt);2958        main.append(pwText, age);29592960        const acts = document.createElement("div");2961        acts.className = "pw-history-actions";2962        const revealBtn2 = document.createElement("button");2963        revealBtn2.className = "pw-history-btn";2964        revealBtn2.type = "button";2965        revealBtn2.textContent = "show";2966        revealBtn2.addEventListener("click", () => {2967          revealed = !revealed;2968          pwText.textContent = revealed ? item.password : mask;2969          revealBtn2.textContent = revealed ? "hide" : "show";2970        });2971        const copyBtn2 = document.createElement("button");2972        copyBtn2.className = "pw-history-btn";2973        copyBtn2.type = "button";2974        copyBtn2.textContent = "copy";2975        copyBtn2.addEventListener("click", async () => {2976          let alreadyWritten = false;2977          try {2978            await navigator.clipboard.writeText(item.password);2979            alreadyWritten = true;2980          } catch (err) {2981            console.warn("[Peach] clipboard write denied:", err);2982          }2983          await chrome.runtime.sendMessage({2984            type: "COPY",2985            payload: { text: item.password, label: "Password", alreadyWritten },2986          }).catch(() => null);2987          copyBtn2.textContent = "copied";2988          setTimeout(() => { if (copyBtn2.isConnected) copyBtn2.textContent = "copy"; }, 1200);2989        });2990        const useBtn = document.createElement("button");2991        useBtn.className = "pw-history-btn";2992        useBtn.type = "button";2993        useBtn.textContent = "use";2994        useBtn.title = "Use this password again";2995        useBtn.addEventListener("click", () => {2996          pwInput.value = item.password;2997          pwInput.type = "text";2998          revealBtn.textContent = "hide";2999          if (editGenVisible) {3000            editGenVisible = false;3001            pwRow.style.display = "";3002            editSmartGen.root.style.display = "none";3003            genToggleBtn.textContent = "⚙ generate";3004          }3005          histVisible = false;3006          histList.style.display = "none";3007          histToggle.textContent = `↺ history (${history.length})`;3008        });3009        acts.append(revealBtn2, copyBtn2, useBtn);3010        row.append(main, acts);3011        histList.appendChild(row);3012      }30133014      pwGroup.append(histToggle, histList);3015    }30163017    body.appendChild(pwGroup);30183019    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;30203021    // Notes3022    const notesGroup = document.createElement("div");3023    notesGroup.className = "f-group";3024    const notesLbl = document.createElement("div");3025    notesLbl.className = "f-label";3026    notesLbl.textContent = "notes";3027    const notesInput = document.createElement("textarea");3028    notesInput.className = "f-input";3029    notesInput.rows = 3;3030    notesInput.value = entryRes.data.notes ?? "";3031    notesInput.style.fontFamily = "Inter, sans-serif";3032    notesInput.style.resize = "vertical";3033    notesGroup.append(notesLbl, notesInput);3034    body.appendChild(notesGroup);30353036    // Save / Cancel row3037    const actionsRow = document.createElement("div");3038    actionsRow.className = "f-row";3039    const saveBtn = document.createElement("button");3040    saveBtn.className = "save-btn";3041    saveBtn.type = "button";3042    saveBtn.textContent = "Save changes";3043    saveBtn.style.flex = "1";3044    const cancelBtn = document.createElement("button");3045    cancelBtn.className = "gen-btn";3046    cancelBtn.type = "button";3047    cancelBtn.textContent = "cancel";3048    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));3049    actionsRow.append(saveBtn, cancelBtn);3050    body.appendChild(actionsRow);30513052    saveBtn.addEventListener("click", async () => {3053      saveBtn.disabled = true;3054      const originalLabel = saveBtn.textContent;3055      saveBtn.textContent = "Saving…";3056      const patch: Record<string, unknown> = {3057        title: titleInput.value.trim(),3058        url: urlInput.value.trim(),3059        username: usernameInput.value.trim(),3060        email: emailInput.value.trim() || undefined,3061        password: pwInput.value,3062        totp: totpInput.value.trim(),3063        notes: notesInput.value,3064      };3065      const updateRes = (await chrome.runtime.sendMessage({3066        type: "UPDATE_ENTRY",3067        payload: { id: summary.id, patch },3068      }).catch(() => null)) as { ok: boolean; error?: string } | null;3069      if (!updateRes?.ok) {3070        saveBtn.disabled = false;3071        saveBtn.textContent = originalLabel;3072        const err = document.createElement("div");3073        err.className = "empty-hint";3074        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";3075        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";3076        body.appendChild(err);3077        setTimeout(() => err.remove(), 3000);3078        return;3079      }3080      // Refresh the platter with updated summary fields3081      const refreshed: SelectorEntry = {3082        id: summary.id,3083        title: patch.title as string,3084        username: patch.username as string,3085        email: patch.email as string | undefined,3086        url: patch.url as string,3087        hasTotp: Boolean(patch.totp),3088        hasPasskey: summary.hasPasskey,3089      };3090      renderSilverPlatter(refreshed);3091    });30923093    queueMicrotask(() => titleInput.focus());3094  }30953096  function renderLocked() {3097    container.innerHTML = "";30983099    // Domain header (same as list view)3100    const domHdr = document.createElement("div");3101    domHdr.className = "domain-header";3102    const eyebrow = document.createElement("div");3103    eyebrow.className = "domain-eyebrow";3104    eyebrow.textContent = "vault locked";3105    const domName = document.createElement("div");3106    domName.className = "domain-name";3107    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3108    domHdr.append(eyebrow, domName);3109    container.appendChild(domHdr);31103111    const wrap = document.createElement("div");3112    wrap.className = "locked-wrap";31133114    // Icon + label row3115    const head = document.createElement("div"); head.className = "locked-head";3116    const icon = document.createElement("div"); icon.className = "locked-icon";3117    icon.innerHTML = keySvgStr();3118    const title = document.createElement("div"); title.className = "locked-title";3119    title.textContent = "unlock to autofill";3120    head.append(icon, title);31213122    // The master password is NEVER collected in page-hosted DOM. A malicious3123    // page can observe keystrokes on the shared DOM event stream (a capture-3124    // phase listener registered before Peach injects sees every key before any3125    // stopImmediatePropagation), which would leak the vault's root secret3126    // (audit HIGH). Instead, route unlocking to the trusted extension popup,3127    // where keystrokes are isolated from the page. After the user unlocks3128    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill3129    // automatically (see content/index.ts), so the flow resumes on its own.3130    const sub = document.createElement("div");3131    sub.className = "locked-sub";3132    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";31333134    const openBtn = document.createElement("button");3135    openBtn.className = "locked-btn";3136    openBtn.type = "button";3137    openBtn.textContent = "Open Peach to unlock";3138    openBtn.addEventListener("click", () => {3139      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});3140      openBtn.textContent = "opening Peach…";3141      openBtn.disabled = true;3142      // openPopup() can't always open programmatically (browser/version/gesture3143      // limits); reset so the user can retry or click the toolbar icon.3144      setTimeout(() => {3145        if (openBtn.isConnected) {3146          openBtn.textContent = "Open Peach to unlock";3147          openBtn.disabled = false;3148        }3149      }, 2500);3150    });31513152    wrap.append(head, sub, openBtn);3153    container.appendChild(wrap);3154  }31553156  function handleKeyDown(e: KeyboardEvent) {3157    if (options.locked) {3158      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3159      return;3160    }3161    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {3162      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3163      return;3164    }3165    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");3166    const count = allEntryEls.length;3167    const activeElement = shadow.activeElement ?? document.activeElement;3168    if (activeElement === searchInput) {3169      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }3170      if (count === 0) return;3171      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;3172    }3173    if (count === 0) return;3174    switch (e.key) {3175      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3176      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3177      case "Enter": {3178        if (focusedIndex >= 0) {3179          const el = allEntryEls[focusedIndex] as HTMLElement;3180          const id = el.dataset.id;3181          if (id) { onSelect(id); dismiss(); }3182          else if (el.classList.contains("is-new") || !id) {3183            // "New entry" row (last item, no data-id)3184            showCreateForm();3185          }3186        }3187        break;3188      }3189      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3190    }3191  }31923193  document.addEventListener("keydown", handleKeyDown);31943195  // Type-to-search from the silver platter. A printable single-character3196  // keystroke (no modifier) seeds the search query and switches into the3197  // list view, so the user can pivot to a different entry without first3198  // clicking the search icon. Capture phase so the anchor input does not3199  // receive the character before we hijack it.3200  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3201    if (currentMode !== "silver-platter") return;3202    if (e.ctrlKey || e.metaKey || e.altKey) return;3203    if (e.key.length !== 1) return;3204    e.preventDefault();3205    e.stopImmediatePropagation();3206    query = e.key;3207    renderList();3208  };3209  document.addEventListener("keydown", silverPlatterTypeHandler, true);3210  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));32113212  const identityHelperTypeHandler = (e: KeyboardEvent) => {3213    if (currentMode !== "identity-helper") return;3214    if (e.ctrlKey || e.metaKey || e.altKey) return;3215    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3216    if (active === searchInput) return;3217    if (3218      active instanceof HTMLInputElement ||3219      active instanceof HTMLTextAreaElement ||3220      (active instanceof HTMLElement && active.isContentEditable)3221    ) {3222      return;3223    }3224    if (e.key.length !== 1) return;3225    e.preventDefault();3226    e.stopImmediatePropagation();3227    query = e.key;3228    renderIdentityHelper();3229  };3230  document.addEventListener("keydown", identityHelperTypeHandler, true);3231  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));32323233  (modalAncestor ?? document.body).appendChild(host);32343235  // position:fixed normally resolves to the viewport, but an ancestor with3236  // transform / filter / backdrop-filter / perspective / contain / will-change3237  // establishes a containing block, so "fixed" then resolves to that ancestor's3238  // padding box instead. When the host is mounted inside such an ancestor (a3239  // modal) we subtract its border-box origin so the popup still lands at the3240  // field's true viewport position. At the document root there is no such3241  // ancestor and the offset is zero.3242  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3243    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3244    return (3245      has("transform") || has("perspective") || has("translate") ||3246      has("rotate") || has("scale") || has("filter") ||3247      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3248      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3249      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3250    );3251  }3252  function containingBlockOffset(): { dx: number; dy: number } {3253    let el: HTMLElement | null = host.parentElement;3254    while (el && el !== document.documentElement) {3255      const s = getComputedStyle(el);3256      if (establishesFixedContainingBlock(s)) {3257        const r = el.getBoundingClientRect();3258        return {3259          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3260          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3261        };3262      }3263      el = el.parentElement;3264    }3265    return { dx: 0, dy: 0 };3266  }32673268  function updatePosition() {3269    const r = anchorEl.getBoundingClientRect();3270    const { dx, dy } = containingBlockOffset();3271    host.style.top = `${r.bottom - dy + 5}px`;3272    host.style.left = `${r.left - dx}px`;3273    host.style.width = `${popupWidth}px`;3274  }3275  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3276  updatePosition();32773278  // observeAnchorPosition listens on window scroll, but a modal with its own3279  // internal scroll container doesn't move the window — track the modal's scroll3280  // too so the popup follows the field inside it.3281  if (modalAncestor) {3282    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3283    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3284  }32853286  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3287  // swap) removes the field without firing blur/click, so none of the normal3288  // dismiss triggers fire and the popup would otherwise linger over nothing.3289  const removalObserver = new MutationObserver(() => {3290    if (!document.contains(anchorEl)) dismiss();3291  });3292  removalObserver.observe(document.body, { childList: true, subtree: true });3293  cleanupHooks.push(() => removalObserver.disconnect());32943295  if (options.locked) {3296    renderLocked();3297  } else if (options.isSignup && options.savedIdentities) {3298    // State 10: identity helper — signup form detected, show derived3299    // identity list (emails then usernames) instead of vault entry list.3300    renderIdentityHelper();3301  } else if (entries.length === 1 && !options.isSignup) {3302    // Silver platter (State 1): single domain match → focused fill view.3303    // Multi-match goes through renderList instead.3304    renderSilverPlatter(entries[0]!);3305  } else {3306    renderList();3307  }33083309  let exitScheduled = false;3310  function dismiss(userAction = false) {3311    // Idempotent: dismiss() can be called from multiple paths (Escape,3312    // outside click, entry select, fill success, host page nav). The exit3313    // animation must only play once and host.remove() must run exactly once.3314    if (exitScheduled) return;3315    exitScheduled = true;3316    // Detach listeners synchronously so nothing can re-trigger during the3317    // 130ms exit window (a focusin firing here would race against the3318    // dismiss-lock work in Pass 2).3319    stopObserving();3320    document.removeEventListener("click", outsideClick, { capture: true });3321    document.removeEventListener("keydown", handleKeyDown);3322    for (const cleanup of cleanupHooks) {3323      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3324    }3325    if (userAction) options.onDismiss?.();3326    container.classList.add("is-exiting");3327    setTimeout(() => host.remove(), 130);3328  }33293330  function outsideClick(ev: MouseEvent) {3331    const path = ev.composedPath();3332    // Never dismiss when clicking the anchor field itself — that click is3333    // what triggered the selector to open, and the user may click the field3334    // again to re-focus it without intending to close the selector.3335    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3336  }3337  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3338  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33393340  return dismiss;3341}33423343export function showTOTPSelector(3344  anchorEl: HTMLInputElement,3345  entries: SelectorEntry[],3346  onFill: (id: string) => void,3347  options: { domain?: string; onDismiss?: () => void } = {}3348): () => void {3349  const host = document.createElement("div");3350  host.style.cssText = "position: absolute; z-index: 2147483647;";3351  host.style.setProperty("--peach-accent", accentHex);3352  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3353  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3354  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3355  const shadow = host.attachShadow({ mode: "closed" });33563357  const style = shadow.appendChild(document.createElement("style"));3358  style.textContent = SELECTOR_STYLES;33593360  const rect = anchorEl.getBoundingClientRect();3361  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3362  host.style.left = `${rect.left + window.scrollX}px`;3363  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3364  host.style.width = `${popupWidth}px`;33653366  const container = shadow.appendChild(document.createElement("div"));3367  container.className = "peach-inline-popup";3368  container.setAttribute("data-theme", popupTheme);33693370  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3371  const current = entries.filter((entry) => entry.hasTotp);3372  let focusedIndex = current.length === 1 ? 0 : -1;33733374  function updatePosition() {3375    const r = anchorEl.getBoundingClientRect();3376    host.style.top = `${r.bottom + window.scrollY + 5}px`;3377    host.style.left = `${r.left + window.scrollX}px`;3378    host.style.width = `${popupWidth}px`;3379  }33803381  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);33823383  function choose(entry: SelectorEntry) {3384    onFill(entry.id);3385    dismiss();3386  }33873388  function render() {3389    container.innerHTML = "";33903391    const domHdr = document.createElement("div");3392    domHdr.className = "domain-header";3393    const headText = document.createElement("div");3394    headText.className = "domain-header-text";3395    const eyebrow = document.createElement("div");3396    eyebrow.className = "domain-eyebrow";3397    eyebrow.textContent = "2FA code";3398    const domName = document.createElement("div");3399    domName.className = "domain-name";3400    domName.textContent = domain;3401    headText.append(eyebrow, domName);3402    domHdr.appendChild(headText);3403    container.appendChild(domHdr);34043405    if (current.length === 1) {3406      const entry = current[0]!;3407      const platter = document.createElement("div");3408      platter.className = "silver-platter";34093410      const title = document.createElement("div");3411      title.className = "sp-title";3412      title.textContent = entry.title;3413      platter.appendChild(title);34143415      const sub = document.createElement("div");3416      sub.className = "sp-username";3417      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3418      platter.appendChild(sub);34193420      const fill = document.createElement("button");3421      fill.className = "sp-fill-btn";3422      fill.type = "button";3423      fill.textContent = "Fill 2FA code";3424      fill.addEventListener("click", () => choose(entry));3425      platter.appendChild(fill);34263427      container.appendChild(platter);3428      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3429      return;3430    }34313432    const results = document.createElement("div");3433    results.className = "results";3434    container.appendChild(results);34353436    for (let i = 0; i < current.length; i++) {3437      const entry = current[i]!;3438      const row = document.createElement("div");3439      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3440      row.dataset.index = String(i);3441      row.setAttribute("tabindex", "-1");34423443      const icon = document.createElement("div");3444      icon.className = "entry-icon";3445      icon.innerHTML = keySvgStr();3446      row.appendChild(icon);3447      const info = document.createElement("div");3448      info.className = "entry-info";3449      const title = document.createElement("div");3450      title.className = "entry-title";3451      title.textContent = entry.title;3452      const sub = document.createElement("div");3453      sub.className = "entry-sub";3454      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3455      info.append(title, sub);3456      row.appendChild(info);34573458      const badge = document.createElement("span");3459      badge.className = "totp-badge";3460      badge.textContent = "Fill";3461      row.appendChild(badge);3462      row.addEventListener("click", () => choose(entry));3463      results.appendChild(row);3464    }3465  }34663467  function setFocused(index: number) {3468    focusedIndex = index;3469    container.querySelectorAll(".entry").forEach((el, i) => {3470      el.classList.toggle("focused", i === focusedIndex);3471      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3472    });3473  }34743475  function handleKeyDown(e: KeyboardEvent) {3476    if (e.key === "Escape" || e.key === "Tab") {3477      e.preventDefault();3478      dismiss(true);3479      return;3480    }3481    if (current.length === 0) return;3482    if (e.key === "Enter") {3483      e.preventDefault();3484      choose(current[Math.max(0, focusedIndex)]!);3485      return;3486    }3487    if (current.length === 1) return;3488    if (e.key === "ArrowDown") {3489      e.preventDefault();3490      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3491    } else if (e.key === "ArrowUp") {3492      e.preventDefault();3493      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3494    }3495  }34963497  let exitScheduled = false;3498  function dismiss(userAction = false) {3499    if (exitScheduled) return;3500    exitScheduled = true;3501    stopObserving();3502    document.removeEventListener("click", outsideClick, { capture: true });3503    document.removeEventListener("keydown", handleKeyDown);3504    if (userAction) options.onDismiss?.();3505    container.classList.add("is-exiting");3506    setTimeout(() => host.remove(), 130);3507  }35083509  function outsideClick(ev: MouseEvent) {3510    const path = ev.composedPath();3511    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3512  }35133514  document.addEventListener("keydown", handleKeyDown);3515  document.body.appendChild(host);3516  render();3517  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);35183519  return dismiss;3520}35213522export interface CardSelectorEntry {3523  id: string;3524  title: string;3525  cardholderName?: string;3526  last4?: string;3527  expMonth?: string;3528  expYear?: string;3529  network?: import("../shared/types").CardNetwork;3530}35313532interface CardSelectorOptions {3533  domain?: string;3534  /** Caller-provided fill — receives the full CardEntry payload from the SW. */3535  onFill: (entry: import("../shared/types").VaultEntry) => void;3536  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3537  onDismiss?: () => void;3538}35393540/**3541 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3542 * passkey create or get. Renders as a fixed-position floating popup (no3543 * field anchor needed — passkeys don't require a focused input). Uses the3544 * same theme tokens and entrance animation as all other inline popup states.3545 */3546export function showPasskeyProGate(): void {3547  const domain = location.hostname.replace(/^www\./, "");35483549  const host = document.createElement("div");3550  host.setAttribute("data-peach-passkey-gate", "1");3551  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3552  const shadow = host.attachShadow({ mode: "closed" });35533554  const style = document.createElement("style");3555  style.textContent = `3556    :host { all: initial; }3557    .gate-wrap {3558      position: fixed;3559      top: 50%;3560      left: 50%;3561      transform: translate(-50%, -50%);3562      width: 280px;3563      pointer-events: auto;3564      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3565    }3566    @keyframes g-in {3567      from { opacity:0; transform: translate(-50%,-52%); }3568      to   { opacity:1; transform: translate(-50%,-50%); }3569    }3570    .gate-wrap.is-exiting {3571      animation: g-out 130ms ease-in forwards;3572    }3573    @keyframes g-out {3574      to { opacity:0; transform: translate(-50%,-52%); }3575    }3576    .gate {3577      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3578      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3579      border-radius: 12px;3580      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3581      padding: 16px;3582      font-family: Inter, sans-serif;3583    }3584    .gate-header {3585      display: flex;3586      align-items: center;3587      gap: 7px;3588      margin-bottom: 12px;3589      padding-bottom: 10px;3590      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3591    }3592    .gate-domain {3593      font-size: 12px;3594      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3595      font-family: "IBM Plex Mono", monospace;3596      overflow: hidden;3597      text-overflow: ellipsis;3598      white-space: nowrap;3599    }3600    .gate-title {3601      font-size: 14px;3602      font-weight: 500;3603      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3604      margin-bottom: 6px;3605    }3606    .gate-subtitle {3607      font-size: 12px;3608      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3609      line-height: 1.5;3610      margin-bottom: 14px;3611    }3612    .gate-btn {3613      display: block;3614      width: 100%;3615      padding: 9px 0;3616      border-radius: 8px;3617      border: none;3618      cursor: pointer;3619      font-size: 13px;3620      font-family: Inter, sans-serif;3621      font-weight: 500;3622      transition: opacity 100ms;3623      margin-bottom: 7px;3624      text-align: center;3625    }3626    .gate-btn:last-child { margin-bottom: 0; }3627    .gate-btn--accent {3628      background: ${accentHex};3629      color: #fff;3630    }3631    .gate-btn--accent:hover { opacity: 0.88; }3632    .gate-btn--ghost {3633      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3634      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3635    }3636    .gate-btn--ghost:hover { opacity: 0.75; }3637    .backdrop {3638      position: fixed;3639      inset: 0;3640      pointer-events: auto;3641    }3642  `;3643  shadow.appendChild(style);36443645  const backdrop = document.createElement("div");3646  backdrop.className = "backdrop";3647  shadow.appendChild(backdrop);36483649  const wrap = document.createElement("div");3650  wrap.className = "gate-wrap";3651  shadow.appendChild(wrap);36523653  const gate = document.createElement("div");3654  gate.className = "gate";3655  wrap.appendChild(gate);36563657  // Header: peach icon + domain3658  const header = document.createElement("div");3659  header.className = "gate-header";3660  const icon = document.createElement("span");3661  icon.innerHTML = peachIconSvg();3662  const domainEl = document.createElement("span");3663  domainEl.className = "gate-domain";3664  domainEl.textContent = domain;3665  header.append(icon, domainEl);3666  gate.appendChild(header);36673668  const title = document.createElement("div");3669  title.className = "gate-title";3670  title.textContent = "Passkeys are part of Peach Pro.";3671  gate.appendChild(title);36723673  const subtitle = document.createElement("div");3674  subtitle.className = "gate-subtitle";3675  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3676  gate.appendChild(subtitle);36773678  const upgradeBtn = document.createElement("button");3679  upgradeBtn.className = "gate-btn gate-btn--accent";3680  upgradeBtn.type = "button";3681  upgradeBtn.textContent = "Upgrade to Pro";3682  gate.appendChild(upgradeBtn);36833684  const laterBtn = document.createElement("button");3685  laterBtn.className = "gate-btn gate-btn--ghost";3686  laterBtn.type = "button";3687  laterBtn.textContent = "Not right now";3688  gate.appendChild(laterBtn);36893690  function dismiss() {3691    wrap.classList.add("is-exiting");3692    setTimeout(() => host.remove(), 130);3693  }36943695  upgradeBtn.addEventListener("click", () => {3696    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3697    dismiss();3698  });3699  laterBtn.addEventListener("click", dismiss);3700  backdrop.addEventListener("click", dismiss);37013702  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3703    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3704  });37053706  document.body.appendChild(host);3707}37083709/**3710 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3711 * detector sees the page invoke navigator.credentials.create(); content/index.ts3712 * checks vault + decline state then calls this. "Save passkey to Peach"3713 * initiates the popup-context credential flow; "Not now" records a 30-day3714 * decline for the domain so we don't re-show on every page reload.3715 */3716export function showPasskeyRegistrationOffer(args: {3717  rpId: string;3718  rpName?: string;3719  userName?: string;3720  userDisplayName?: string;3721}): void {3722  const domain = location.hostname.replace(/^www\./, "");3723  const displayName = args.rpName || domain;37243725  const host = document.createElement("div");3726  host.setAttribute("data-peach-passkey-offer", "1");3727  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3728  const shadow = host.attachShadow({ mode: "closed" });37293730  const style = document.createElement("style");3731  style.textContent = `3732    :host { all: initial; }3733    .offer-wrap {3734      position: fixed;3735      top: 16px;3736      right: 16px;3737      width: 320px;3738      pointer-events: auto;3739      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3740    }3741    @keyframes o-in {3742      from { opacity: 0; transform: translateY(-6px); }3743      to   { opacity: 1; transform: translateY(0); }3744    }3745    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3746    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3747    .offer {3748      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3749      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3750      border-radius: 12px;3751      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3752      padding: 14px 14px 12px;3753      font-family: Inter, sans-serif;3754      position: relative;3755    }3756    .offer-close {3757      position: absolute;3758      top: 8px;3759      right: 8px;3760      width: 18px;3761      height: 18px;3762      border: none;3763      background: transparent;3764      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3765      cursor: pointer;3766      font-size: 14px;3767      line-height: 1;3768      padding: 0;3769    }3770    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3771    .offer-header {3772      display: flex;3773      align-items: center;3774      gap: 7px;3775      margin-bottom: 8px;3776      padding-bottom: 8px;3777      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3778    }3779    .offer-domain {3780      font-size: 12px;3781      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3782      font-family: "IBM Plex Mono", monospace;3783      overflow: hidden;3784      text-overflow: ellipsis;3785      white-space: nowrap;3786    }3787    .offer-title {3788      font-size: 13px;3789      font-weight: 500;3790      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3791      margin-bottom: 4px;3792    }3793    .offer-subtitle {3794      font-size: 11px;3795      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3796      line-height: 1.45;3797      margin-bottom: 12px;3798    }3799    .offer-btn {3800      display: block;3801      width: 100%;3802      padding: 8px 0;3803      border-radius: 7px;3804      border: none;3805      cursor: pointer;3806      font-size: 12px;3807      font-family: Inter, sans-serif;3808      font-weight: 500;3809      transition: opacity 100ms;3810      margin-bottom: 6px;3811      text-align: center;3812    }3813    .offer-btn:last-child { margin-bottom: 0; }3814    .offer-btn--accent { background: ${accentHex}; color: #fff; }3815    .offer-btn--accent:hover { opacity: 0.88; }3816    .offer-btn--ghost {3817      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3818      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3819    }3820    .offer-btn--ghost:hover { opacity: 0.75; }3821  `;3822  shadow.appendChild(style);38233824  const wrap = document.createElement("div");3825  wrap.className = "offer-wrap";3826  shadow.appendChild(wrap);38273828  const offer = document.createElement("div");3829  offer.className = "offer";3830  wrap.appendChild(offer);38313832  const closeBtn = document.createElement("button");3833  closeBtn.className = "offer-close";3834  closeBtn.type = "button";3835  closeBtn.setAttribute("aria-label", "Dismiss");3836  closeBtn.textContent = "✕";3837  offer.appendChild(closeBtn);38383839  const header = document.createElement("div");3840  header.className = "offer-header";3841  const icon = document.createElement("span");3842  icon.innerHTML = peachIconSvg();3843  const domainEl = document.createElement("span");3844  domainEl.className = "offer-domain";3845  domainEl.textContent = domain;3846  header.append(icon, domainEl);3847  offer.appendChild(header);38483849  const title = document.createElement("div");3850  title.className = "offer-title";3851  title.textContent = "This site supports passkeys.";3852  offer.appendChild(title);38533854  const subtitle = document.createElement("div");3855  subtitle.className = "offer-subtitle";3856  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3857  offer.appendChild(subtitle);38583859  const saveBtn = document.createElement("button");3860  saveBtn.className = "offer-btn offer-btn--accent";3861  saveBtn.type = "button";3862  saveBtn.textContent = "Save passkey to Peach";3863  offer.appendChild(saveBtn);38643865  const laterBtn = document.createElement("button");3866  laterBtn.className = "offer-btn offer-btn--ghost";3867  laterBtn.type = "button";3868  laterBtn.textContent = "Not now";3869  offer.appendChild(laterBtn);38703871  function dismiss(decline: boolean) {3872    if (decline) {3873      chrome.runtime.sendMessage({3874        type: "PASSKEY_OFFER_DECLINE",3875        payload: { domain },3876      }).catch(() => {});3877    }3878    wrap.classList.add("is-exiting");3879    setTimeout(() => host.remove(), 130);3880  }38813882  saveBtn.addEventListener("click", () => {3883    chrome.runtime.sendMessage({3884      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3885      payload: {3886        rpId: args.rpId,3887        rpName: args.rpName ?? displayName,3888        userName: args.userName ?? "user",3889        userDisplayName: args.userDisplayName,3890      },3891    }).catch(() => {});3892    dismiss(false);3893  });3894  laterBtn.addEventListener("click", () => dismiss(true));3895  closeBtn.addEventListener("click", () => dismiss(true));38963897  document.body.appendChild(host);3898}38993900/**3901 * State 11 — passkey available indicator. Shown when the user lands on a3902 * domain for which they already have a stored passkey. Tells them where to3903 * find it (the entry already shows in the vault list); the "Sign in with3904 * passkey" button opens the popup so they can use the platform authenticator3905 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3906 * the actual sign-in transparently, so this banner is informational only.3907 */3908export function showPasskeyAvailable(args: {3909  rpId: string;3910  userName: string;3911  fromBrowser?: "chrome" | "firefox";3912  currentBrowser?: "chrome" | "firefox" | "unknown";3913}): void {3914  const domain = location.hostname.replace(/^www\./, "");3915  const crossBrowser =3916    args.fromBrowser &&3917    args.currentBrowser &&3918    args.currentBrowser !== "unknown" &&3919    args.fromBrowser !== args.currentBrowser;39203921  const host = document.createElement("div");3922  host.setAttribute("data-peach-passkey-available", "1");3923  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3924  const shadow = host.attachShadow({ mode: "closed" });39253926  const style = document.createElement("style");3927  style.textContent = `3928    :host { all: initial; }3929    .avail-wrap {3930      position: fixed;3931      top: 16px;3932      right: 16px;3933      width: 320px;3934      pointer-events: auto;3935      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3936    }3937    @keyframes a-in {3938      from { opacity: 0; transform: translateY(-6px); }3939      to   { opacity: 1; transform: translateY(0); }3940    }3941    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3942    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3943    .avail {3944      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3945      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3946      border-radius: 12px;3947      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3948      padding: 14px 14px 12px;3949      font-family: Inter, sans-serif;3950      position: relative;3951    }3952    .avail-close {3953      position: absolute;3954      top: 8px;3955      right: 8px;3956      width: 18px;3957      height: 18px;3958      border: none;3959      background: transparent;3960      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3961      cursor: pointer;3962      font-size: 14px;3963      line-height: 1;3964      padding: 0;3965    }3966    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3967    .avail-header {3968      display: flex;3969      align-items: center;3970      gap: 7px;3971      margin-bottom: 8px;3972      padding-bottom: 8px;3973      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3974    }3975    .avail-domain {3976      font-size: 12px;3977      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3978      font-family: "IBM Plex Mono", monospace;3979    }3980    .avail-label {3981      font-size: 9px;3982      letter-spacing: 0.16em;3983      text-transform: uppercase;3984      color: ${accentHex};3985      margin-bottom: 4px;3986    }3987    .avail-user {3988      font-size: 13px;3989      font-weight: 500;3990      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3991      margin-bottom: 12px;3992      overflow: hidden;3993      text-overflow: ellipsis;3994      white-space: nowrap;3995    }3996    .avail-cross {3997      font-size: 11px;3998      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3999      line-height: 1.45;4000      margin-bottom: 12px;4001      padding: 8px;4002      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};4003      border-radius: 6px;4004    }4005    .avail-btn {4006      display: block;4007      width: 100%;4008      padding: 8px 0;4009      border-radius: 7px;4010      border: none;4011      cursor: pointer;4012      font-size: 12px;4013      font-family: Inter, sans-serif;4014      font-weight: 500;4015      transition: opacity 100ms;4016      margin-bottom: 6px;4017      text-align: center;4018    }4019    .avail-btn:last-child { margin-bottom: 0; }4020    .avail-btn--accent { background: ${accentHex}; color: #fff; }4021    .avail-btn--accent:hover { opacity: 0.88; }4022    .avail-btn--ghost {4023      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};4024      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};4025    }4026    .avail-btn--ghost:hover { opacity: 0.75; }4027  `;4028  shadow.appendChild(style);40294030  const wrap = document.createElement("div");4031  wrap.className = "avail-wrap";4032  shadow.appendChild(wrap);40334034  const avail = document.createElement("div");4035  avail.className = "avail";4036  wrap.appendChild(avail);40374038  const closeBtn = document.createElement("button");4039  closeBtn.className = "avail-close";4040  closeBtn.type = "button";4041  closeBtn.setAttribute("aria-label", "Dismiss");4042  closeBtn.textContent = "✕";4043  avail.appendChild(closeBtn);40444045  const header = document.createElement("div");4046  header.className = "avail-header";4047  const icon = document.createElement("span");4048  icon.innerHTML = peachIconSvg();4049  const domainEl = document.createElement("span");4050  domainEl.className = "avail-domain";4051  domainEl.textContent = domain;4052  header.append(icon, domainEl);4053  avail.appendChild(header);40544055  const label = document.createElement("div");4056  label.className = "avail-label";4057  label.textContent = "PASSKEY";4058  avail.appendChild(label);40594060  const user = document.createElement("div");4061  user.className = "avail-user";4062  user.textContent = args.userName;4063  avail.appendChild(user);40644065  if (crossBrowser) {4066    const cross = document.createElement("div");4067    cross.className = "avail-cross";4068    cross.textContent =4069      args.fromBrowser === "chrome"4070        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."4071        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";4072    avail.appendChild(cross);4073  }40744075  const signInBtn = document.createElement("button");4076  signInBtn.className = "avail-btn avail-btn--accent";4077  signInBtn.type = "button";4078  signInBtn.textContent = "Sign in with passkey";4079  avail.appendChild(signInBtn);40804081  const passwordBtn = document.createElement("button");4082  passwordBtn.className = "avail-btn avail-btn--ghost";4083  passwordBtn.type = "button";4084  passwordBtn.textContent = "Use password instead";4085  avail.appendChild(passwordBtn);40864087  function dismiss() {4088    wrap.classList.add("is-exiting");4089    setTimeout(() => host.remove(), 130);4090  }40914092  signInBtn.addEventListener("click", () => {4093    // On Chrome: the user clicking the page's own Sign-in button is what4094    //   triggers webAuthenticationProxy → existing background flow handles it.4095    //   Our button just dismisses since the page itself drives auth.4096    // On Firefox: cross-browser passkeys can't be used, so we just dismiss4097    //   and surface the entry for manual reference (popup view).4098    dismiss();4099    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});4100  });4101  passwordBtn.addEventListener("click", dismiss);4102  closeBtn.addEventListener("click", dismiss);41034104  document.body.appendChild(host);4105}41064107/**4108 * State 7 — card silver platter. Single-card focused fill view rendered4109 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the4110 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes4111 * so card and login flows render identically. Multi-card list view is a4112 * follow-up; today this picks the first card.4113 */4114export function showCardSelector(4115  anchorEl: HTMLInputElement,4116  cards: CardSelectorEntry[],4117  options: CardSelectorOptions4118): () => void {4119  if (cards.length === 0) return () => {};4120  const card = cards[0]!;41214122  const host = document.createElement("div");4123  host.style.cssText = "position: absolute; z-index: 2147483647;";4124  host.style.setProperty("--peach-accent", accentHex);4125  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));4126  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));4127  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));4128  const shadow = host.attachShadow({ mode: "closed" });41294130  const style = shadow.appendChild(document.createElement("style"));4131  style.textContent = SELECTOR_STYLES;41324133  const rect = anchorEl.getBoundingClientRect();4134  host.style.top = `${rect.bottom + window.scrollY + 5}px`;4135  host.style.left = `${rect.left + window.scrollX}px`;4136  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;41374138  const container = shadow.appendChild(document.createElement("div"));4139  container.className = "peach-inline-popup";4140  container.setAttribute("data-theme", popupTheme);41414142  // Domain header — eyebrow communicates the card context, not the site4143  const domHdr = document.createElement("div");4144  domHdr.className = "domain-header";4145  const eyebrow = document.createElement("div");4146  eyebrow.className = "domain-eyebrow";4147  eyebrow.textContent = "Pay with Peach";4148  const domName = document.createElement("div");4149  domName.className = "domain-name";4150  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");4151  domHdr.append(eyebrow, domName);4152  container.appendChild(domHdr);41534154  const platter = document.createElement("div");4155  platter.className = "card-platter";41564157  if (card.network && card.network !== "unknown") {4158    const net = document.createElement("div");4159    net.className = "cp-network";4160    net.textContent = card.network;4161    platter.appendChild(net);4162  }41634164  const nick = document.createElement("div");4165  nick.className = "cp-nickname";4166  nick.textContent = card.title;4167  platter.appendChild(nick);41684169  if (card.last4) {4170    const l4 = document.createElement("div");4171    l4.className = "cp-last4";4172    l4.textContent = `•••• ${card.last4}`;4173    platter.appendChild(l4);4174  }41754176  const meta = document.createElement("div");4177  meta.className = "cp-meta";4178  if (card.cardholderName) {4179    const name = document.createElement("span");4180    name.textContent = card.cardholderName;4181    meta.appendChild(name);4182  }4183  if (card.expMonth && card.expYear) {4184    if (card.cardholderName) {4185      const sep = document.createElement("span");4186      sep.className = "cp-meta-sep";4187      sep.textContent = "·";4188      meta.appendChild(sep);4189    }4190    const exp = document.createElement("span");4191    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4192    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4193    meta.appendChild(exp);4194  }4195  if (meta.childElementCount > 0) platter.appendChild(meta);41964197  const fillWrap = document.createElement("div");4198  fillWrap.className = "cp-fill-wrap";4199  const fillBtn = document.createElement("button");4200  fillBtn.className = "sp-fill-btn";4201  fillBtn.type = "button";4202  fillBtn.textContent = "Fill card details";4203  fillBtn.addEventListener("click", async () => {4204    if (fillBtn.disabled) return;4205    fillBtn.disabled = true;4206    fillBtn.classList.add("filled");4207    fillBtn.innerHTML = checkSvgStr();4208    const resp = await chrome.runtime.sendMessage({4209      type: "GET_ENTRY_FOR_FILL",4210      payload: { id: card.id },4211    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4212    if (resp?.ok && resp.data) options.onFill(resp.data);4213    setTimeout(() => dismiss(), 400);4214  });4215  fillWrap.appendChild(fillBtn);4216  platter.appendChild(fillWrap);42174218  // Secondary actions — copy number, copy CVC, dismiss4219  const actions = document.createElement("div");4220  actions.className = "sp-actions";42214222  function flashBtn(b: HTMLButtonElement) {4223    b.classList.add("flashed");4224    setTimeout(() => b.classList.remove("flashed"), 700);4225  }42264227  // M3/QUA-005: clipboard + background COPY both failed — show user.4228  function flashCopyError(b: HTMLButtonElement) {4229    const original = b.textContent ?? "";4230    b.textContent = "Blocked";4231    b.classList.add("flashed");4232    setTimeout(() => {4233      b.classList.remove("flashed");4234      if (b.isConnected) b.textContent = original;4235    }, 1200);4236  }42374238  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4239    const resp = await chrome.runtime.sendMessage({4240      type: "GET_ENTRY_FOR_FILL",4241      payload: { id: card.id },4242    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4243    return resp?.ok && resp.data ? resp.data : null;4244  }42454246  const copyNum = document.createElement("button");4247  copyNum.className = "sp-action-btn";4248  copyNum.type = "button";4249  copyNum.title = "Copy card number";4250  copyNum.textContent = "Copy number";4251  copyNum.addEventListener("click", async (e) => {4252    e.stopPropagation();4253    const full = await fetchFullCard();4254    if (!full?.cardNumber) return;4255    let alreadyWritten = false;4256    try {4257      await navigator.clipboard.writeText(full.cardNumber);4258      alreadyWritten = true;4259    } catch (err) {4260      console.warn("[Peach] clipboard write denied:", err);4261    }4262    const resp = await chrome.runtime.sendMessage({4263      type: "COPY",4264      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4265    }).catch(() => null) as { ok?: boolean } | null;4266    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4267    else flashCopyError(copyNum);4268  });4269  actions.appendChild(copyNum);42704271  const copyCvc = document.createElement("button");4272  copyCvc.className = "sp-action-btn";4273  copyCvc.type = "button";4274  copyCvc.title = "Copy CVC";4275  copyCvc.textContent = "Copy CVC";4276  copyCvc.addEventListener("click", async (e) => {4277    e.stopPropagation();4278    const full = await fetchFullCard();4279    if (!full?.cvc) return;4280    let alreadyWritten = false;4281    try {4282      await navigator.clipboard.writeText(full.cvc);4283      alreadyWritten = true;4284    } catch (err) {4285      console.warn("[Peach] clipboard write denied:", err);4286    }4287    const resp = await chrome.runtime.sendMessage({4288      type: "COPY",4289      payload: { text: full.cvc, label: "CVC", alreadyWritten },4290    }).catch(() => null) as { ok?: boolean } | null;4291    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4292    else flashCopyError(copyCvc);4293  });4294  actions.appendChild(copyCvc);42954296  const closeBtn = document.createElement("button");4297  closeBtn.className = "sp-action-btn";4298  closeBtn.type = "button";4299  closeBtn.title = "Dismiss";4300  closeBtn.textContent = "✕";4301  closeBtn.addEventListener("click", (e) => {4302    e.stopPropagation();4303    dismiss(true);4304  });4305  actions.appendChild(closeBtn);43064307  platter.appendChild(actions);4308  container.appendChild(platter);43094310  document.body.appendChild(host);4311  function updatePosition() {4312    const r = anchorEl.getBoundingClientRect();4313    host.style.top = `${r.bottom + window.scrollY + 5}px`;4314    host.style.left = `${r.left + window.scrollX}px`;4315  }4316  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);43174318  function onKeyDown(e: KeyboardEvent) {4319    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4320  }4321  document.addEventListener("keydown", onKeyDown);43224323  let exitScheduled = false;4324  function dismiss(userAction = false) {4325    if (exitScheduled) return;4326    exitScheduled = true;4327    stopObserving();4328    document.removeEventListener("click", outsideClick, { capture: true });4329    document.removeEventListener("keydown", onKeyDown);4330    if (userAction) options.onDismiss?.();4331    container.classList.add("is-exiting");4332    setTimeout(() => host.remove(), 130);4333  }43344335  function outsideClick(ev: MouseEvent) {4336    const path = ev.composedPath();4337    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4338  }4339  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);43404341  return dismiss;4342}