inject.ts

178.1 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type 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  /**73   * MV-2: lazy loader for the vault-wide searchable list. Invoked only on an74   * explicit user search gesture, never on passive popup open, so the full75   * account inventory never ships into the page world unless the user asks.76   * Result is cached for the popup's lifetime.77   */78  loadSearchableEntries?: () => Promise<SelectorEntry[]>;79  /** True when shown on a signup form — changes header label and entry-click behaviour */80  isSignup?: boolean;81  /**82   * Identity kind the current signup field is expecting. Used to avoid83   * assuming email when the user is actually filling a username.84   */85  identityKind?: IdentityKind;86  /**87   * Derived identity list (emails then usernames) for signup mode (State 10).88   * When present, renderIdentityHelper() is used instead of renderList().89   */90  savedIdentities?: SavedIdentity[];91  /**92   * Called after the user picks a saved identity (signup mode only) or93   * after successfully saving a new entry on a signup form.94   * Lets the caller fill the visible username + password fields.95   */96  onFillFields?: (username: string, password: string, email?: string) => void;97  /**98   * True when the form has both a distinct username field AND a distinct email99   * field (e.g. Name / Username / Email / Password signup forms). Enables the100   * two-step identity wizard: first pick the field type the user clicked on,101   * then pick the other, then generate a password.102   */103  hasEmailField?: boolean;104  /**105   * When true, show an inline unlock form instead of the entries list.106   * Used when the vault is locked so the user can unlock without opening107   * the popup.108   */109  locked?: boolean;110  /**111   * Called after a successful inline unlock — the caller should re-query112   * entries and re-open the selector with real data.113   */114  onUnlocked?: () => void;115  /**116   * Called when the user explicitly dismisses the selector (Escape, Tab, or117   * click outside) — NOT when an entry is selected or on auto-close.118   * Used by the caller to suppress spurious reopens on the same field.119   */120  onDismiss?: () => void;121}122123function getDomainFromUrl(url: string): string {124  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }125}126127function keySvgStr(): string {128  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>`;129}130131function plusSvgStr(): string {132  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>`;133}134135function searchSvgStr(): string {136  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>`;137}138139function backSvgStr(): string {140  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>`;141}142143function peachIconSvg(): string {144  // Peach body stays brand-peach regardless of `accentHex` — a sage or145  // sky accent must not turn the autofill icon green or blue. Accent146  // color still tints surrounding glow/hover halos below.147  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>`;148}149150function checkSvgStr(): string {151  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>`;152}153154function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {155  const { hostname, origin } = location;156  const parts = hostname.split(".");157  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",158    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",159    "oidc", "federation", "saml", "cas", "ldap"];160  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());161  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;162  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);163  return { origin, title, loginSubdomain };164}165166/**167 * Shows a bottom-of-page toast after filling credentials when the entry has168 * never matched the current site — offering to add the current origin to the169 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.170 */171export function showRememberSiteToast(172  pageDomain: string,173  entryId: string,174): void {175  const host = document.createElement("div");176  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";177  host.style.setProperty("--peach-accent", accentHex);178  const shadow = host.attachShadow({ mode: "closed" });179180  const style = document.createElement("style");181  style.textContent = `182    .bar {183      display:flex;align-items:center;gap:10px;padding:10px 14px;184      background:#131109;border:1px solid rgba(240,232,216,0.09);185      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);186      font-family:Inter,sans-serif;white-space:nowrap;187      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;188    }189    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }190    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }191    .yes {192      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;193      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;194    }195    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }196    .no {197      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;198      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;199    }200  `;201  shadow.appendChild(style);202203  const bar = document.createElement("div"); bar.className = "bar";204  const txt = document.createElement("span"); txt.className = "txt";205  txt.textContent = `Remember ${pageDomain} for this entry?`;206  const yesBtn = document.createElement("button"); yesBtn.className = "yes";207  yesBtn.textContent = "Remember";208  yesBtn.addEventListener("click", async () => {209    await chrome.runtime.sendMessage({210      type: "ADD_ADDITIONAL_URL",211      payload: { id: entryId, url: location.origin },212    });213    host.remove();214  });215  const noBtn = document.createElement("button"); noBtn.className = "no";216  noBtn.textContent = "Not now";217  noBtn.addEventListener("click", () => host.remove());218  bar.append(txt, yesBtn, noBtn);219  shadow.appendChild(bar);220  document.body.appendChild(host);221  setTimeout(() => host.remove(), 9000);222}223224interface SmartGenerator {225  root: HTMLElement;226  getPassword: () => string;227  /** Copy the current password to the clipboard with the standard pulse UX. */228  copy: () => Promise<void>;229}230231interface SmartGeneratorOptions {232  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */233  policy: PasswordPolicy;234  /**235   * Seed value: used as the displayed password without regenerating, e.g. the236   * password the user already typed into the page. The generator still237   * regenerates the moment any control changes.238   */239  initialPassword?: string;240  /** Fires every time the password regenerates (initial + on changes). */241  onChange?: (pw: string) => void;242}243244/**245 * Build the inline-popup smart-password generator. Mirrors the main popup's246 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset247 * pills + a policy hint that names the constraints Peach detected on the248 * page. Writing this in pure DOM rather than reusing the Solid component249 * keeps the content-script bundle small.250 */251function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {252  const policy = opts.policy ?? {};253254  // Start at site max (strongest password the site accepts), fall back to 64255  let length = policy.maxLength ?? 64;256  if (policy.minLength) length = Math.max(length, policy.minLength);257  if (length < 8) length = 8;258  if (length > 128) length = 128;259260  let upper = true;261  let lower = true;262  let numbers = true;263  let symbols = !policy.forbidsSymbols;264  if (policy.requiresSymbols) symbols = true;265  const forbiddenChars = policy.forbiddenChars ?? "";266267  let password = "";268269  const root = document.createElement("div");270  root.className = "pwgen-block";271272  const displayRow = root.appendChild(document.createElement("div"));273  displayRow.className = "pwgen-display-row";274  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;275  output.type = "text";276  output.className = "pwgen-output";277  output.setAttribute("autocomplete", "off");278  output.setAttribute("spellcheck", "false");279  output.setAttribute("autocorrect", "off");280  output.setAttribute("autocapitalize", "off");281282  const regenBtn = displayRow.appendChild(document.createElement("button"));283  regenBtn.className = "pwgen-icon-btn";284  regenBtn.type = "button";285  regenBtn.setAttribute("aria-label", "Regenerate password");286  regenBtn.title = "Regenerate";287  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>`;288289  const copyBtn = displayRow.appendChild(document.createElement("button"));290  copyBtn.className = "pwgen-icon-btn";291  copyBtn.type = "button";292  copyBtn.setAttribute("aria-label", "Copy password");293  copyBtn.title = "Copy";294  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>`;295296  const controls = root.appendChild(document.createElement("div"));297  controls.className = "pwgen-controls-row";298  const slider = controls.appendChild(document.createElement("input"));299  slider.type = "range";300  slider.className = "pwgen-slider";301  slider.min = "8";302  slider.max = "128";303  slider.value = String(length);304  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));305  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));306  const lenNum = controls.appendChild(document.createElement("span"));307  lenNum.className = "pwgen-len-num pwgen-len-num--edit";308  lenNum.textContent = String(length);309  lenNum.addEventListener("click", () => {310    const li = document.createElement("input");311    li.type = "text"; li.inputMode = "numeric";312    li.className = "pwgen-len-input"; li.value = String(length);313    lenNum.replaceWith(li);314    requestAnimationFrame(() => li.select());315    function commitLenEdit() {316      const n = parseInt(li.value, 10);317      if (!isNaN(n)) {318        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));319        slider.value = String(length);320        regenerate();321      }322      lenNum.textContent = String(length);323      li.replaceWith(lenNum);324    }325    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });326    li.addEventListener("blur", commitLenEdit);327  });328329  const pills = root.appendChild(document.createElement("div"));330  pills.className = "pwgen-pills";331332  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {333    const b = document.createElement("button");334    b.type = "button";335    b.className = `pwgen-pill ${on ? "is-on" : ""}`;336    b.textContent = label;337    b.addEventListener("click", () => {338      const next = !b.classList.contains("is-on");339      b.classList.toggle("is-on", next);340      onToggle(next);341    });342    return b;343  }344  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));345  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));346  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));347  pills.appendChild(makePill("!@#", symbols, (next) => {348    // The site forbids symbols — UI lets the user override but still warn.349    symbols = next;350    regenerate();351  }));352353  // Policy hint — surfaces what Peach read off the site so the user knows the354  // generator is already tuned to it. Only shows when something interesting355  // was detected.356  const hintParts: string[] = [];357  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);358  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);359  if (policy.requiresSymbols) hintParts.push("requires symbols");360  if (policy.forbidsSymbols) hintParts.push("no symbols");361  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);362  if (hintParts.length > 0) {363    const hint = root.appendChild(document.createElement("div"));364    hint.className = "pwgen-policy-hint";365    const accent = document.createElement("span");366    accent.className = "pwgen-hint-accent";367    accent.textContent = "site rules · ";368    const text = document.createTextNode(hintParts.join(" · "));369    hint.appendChild(accent);370    hint.appendChild(text);371  }372373  function regenerate() {374    // Falls back gracefully when the user toggles every charset off — the375    // shared generator forces lowercase in that case rather than throwing.376    password = generatePassword({377      length,378      includeUppercase: upper,379      includeLowercase: lower,380      includeNumbers: numbers,381      includeSymbols: symbols,382      forbiddenChars,383    });384    output.value = password;385    opts.onChange?.(password);386  }387388  output.addEventListener("input", () => {389    password = output.value;390    length = password.length;391    slider.value = String(Math.max(8, Math.min(128, length)));392    lenNum.textContent = String(length);393    opts.onChange?.(password);394  });395396  slider.addEventListener("input", () => {397    length = parseInt(slider.value, 10);398    lenNum.textContent = String(length);399    regenerate();400  });401  regenBtn.addEventListener("click", regenerate);402403  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;404  async function copy(): Promise<void> {405    try {406      await navigator.clipboard.writeText(password);407      copyBtn.classList.add("is-copied");408      if (copyResetTimer) clearTimeout(copyResetTimer);409      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);410    } catch {411      // Clipboard API may be denied — silently no-op; user still has regen UI.412    }413  }414  copyBtn.addEventListener("click", () => { void copy(); });415416  if (opts.initialPassword) {417    password = opts.initialPassword;418    output.value = password;419    opts.onChange?.(password);420  } else {421    regenerate();422  }423424  return {425    root,426    getPassword: () => password,427    copy,428  };429}430431export function observeAnchorPosition(432  anchorEl: HTMLElement,433  onUpdate: () => void434): () => void {435  let rafId = 0;436  let burstUntil = 0;437438  const runUpdate = () => {439    rafId = 0;440    onUpdate();441    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);442  };443  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };444  const scheduleBurst = (ms = 220) => {445    burstUntil = Math.max(burstUntil, performance.now() + ms);446    scheduleUpdate();447  };448449  const resizeObserver = new ResizeObserver(() => scheduleBurst());450  resizeObserver.observe(anchorEl);451  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);452453  const mutationObserver = new MutationObserver(() => scheduleBurst());454  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });455  if (anchorEl.parentElement) {456    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });457  }458459  const onScroll = () => scheduleUpdate();460  window.addEventListener("scroll", onScroll, true);461  window.addEventListener("resize", onScroll);462  window.visualViewport?.addEventListener("resize", onScroll);463  window.visualViewport?.addEventListener("scroll", onScroll);464  anchorEl.addEventListener("focus", () => scheduleBurst());465  anchorEl.addEventListener("input", () => scheduleBurst());466467  scheduleBurst(260);468469  return () => {470    if (rafId) cancelAnimationFrame(rafId);471    resizeObserver.disconnect();472    mutationObserver.disconnect();473    window.removeEventListener("scroll", onScroll, true);474    window.removeEventListener("resize", onScroll);475    window.visualViewport?.removeEventListener("resize", onScroll);476    window.visualViewport?.removeEventListener("scroll", onScroll);477  };478}479480export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {481  const button = document.createElement("button");482  button.type = "button";483  button.setAttribute("aria-label", "Peach autofill");484  button.title = "Fill with Peach";485  button.innerHTML = peachIconSvg();486  // position: fixed is load-bearing — not absolute. Absolute positioning487  // inherits the nearest positioned ancestor's box, which on sites with488  // overflow:hidden or sticky parents clips or offsets the icon. Fixed489  // anchors to the viewport and escapes all parent layout.490  button.style.cssText = `491    position: fixed; z-index: 2147483646;492    width: 26px; height: 26px; cursor: pointer;493    pointer-events: auto; border: none; padding: 3px;494    display: inline-flex; align-items: center; justify-content: center;495    background: transparent; border-radius: 999px;496    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;497    opacity: 0;498  `;499  button.addEventListener("mouseenter", () => {500    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;501    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;502    button.style.transform = "scale(1.08)";503  });504  button.addEventListener("mouseleave", () => {505    button.style.background = "transparent";506    button.style.boxShadow = "none";507    button.style.transform = "none";508  });509  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });510  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });511512  document.body.appendChild(button);513514  function updatePosition() {515    const rect = field.getBoundingClientRect();516    if (rect.width === 0 || rect.height === 0) {517      button.style.opacity = "0"; button.style.pointerEvents = "none";518      return;519    }520    const sz = 26;521    const inset = Math.max(5, Math.min(10, rect.height * 0.22));522    const top = rect.top + rect.height / 2 - sz / 2;523    // Clamp left so the icon stays fully inside the field's right edge, never524    // spilling onto an adjacent sibling button.525    const minLeft = rect.left + 4;526    const left = Math.max(minLeft, rect.right - sz - inset);527    // Hide if the field is too narrow to fit the icon cleanly (< 40px)528    if (rect.width < 40) {529      button.style.opacity = "0"; button.style.pointerEvents = "none";530      return;531    }532    button.style.top = `${top}px`;533    button.style.left = `${left}px`;534    button.style.opacity = "1"; button.style.pointerEvents = "auto";535  }536  updatePosition();537  requestAnimationFrame(() => { button.style.opacity = "1"; });538  const stopObserving = observeAnchorPosition(field, updatePosition);539  return () => { stopObserving(); button.remove(); };540}541542// All theme-dependent values resolve through tokens scoped to543// .peach-inline-popup[data-theme="dark|light"]. Accent variables544// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)545// are identical in both themes — only surface tokens differ. See546// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the547// theme switch — only literal brand-peach in peachIconSvg may stay raw.548const SELECTOR_STYLES = `549  :host { all: initial; }550  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }551552  .peach-inline-popup[data-theme="dark"] {553    --peach-bg:           #1a1410;554    --peach-bg-card:      #221c16;555    --peach-text:         #f5f0ea;556    --peach-text-dim:     #8a7a6a;557    --peach-text-muted:   #4a3a2a;558    --peach-border:       rgba(255,255,255,0.07);559    --peach-input-bg:     rgba(255,255,255,0.05);560    --peach-input-border: rgba(255,255,255,0.08);561  }562  .peach-inline-popup[data-theme="light"] {563    --peach-bg:           #fdf8f4;564    --peach-bg-card:      #f5ede4;565    --peach-text:         #1c1310;566    --peach-text-dim:     #6b5a4a;567    --peach-text-muted:   #a89080;568    --peach-border:       rgba(0,0,0,0.08);569    --peach-input-bg:     rgba(0,0,0,0.04);570    --peach-input-border: rgba(0,0,0,0.10);571  }572573  .peach-inline-popup {574    background: var(--peach-bg);575    border: 1px solid var(--peach-border-accent, var(--peach-border));576    border-radius: 14px;577    overflow: hidden;578    box-shadow:579      0 8px 40px var(--peach-glow, transparent),580      0 2px 12px rgba(0,0,0,0.5);581    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;582    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;583    transition: height 220ms cubic-bezier(0.16,1,0.3,1);584  }585  /* Light theme: shadow against a light page is too strong otherwise — drop both586     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */587  .peach-inline-popup[data-theme="light"] {588    box-shadow:589      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),590      0 2px 12px rgba(0,0,0,0.12);591  }592  .peach-inline-popup.is-exiting {593    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;594    pointer-events: none;595  }596597  @keyframes peach-enter {598    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }599    65%  { opacity: 1; filter: blur(0); }600    100% { opacity: 1; transform: translateY(0) scale(1); }601  }602  @keyframes peach-exit {603    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }604    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }605  }606  @keyframes peach-slide-in {607    from { opacity: 0; transform: translateX(12px); }608    to   { opacity: 1; transform: translateX(0); }609  }610  @keyframes peach-slide-back {611    from { opacity: 0; transform: translateX(-12px); }612    to   { opacity: 1; transform: translateX(0); }613  }614  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }615  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }616617  /* Domain header */618  .domain-header {619    padding: 9px 13px 7px;620    border-bottom: 1px solid var(--peach-border);621    display: flex; align-items: center; justify-content: space-between;622    gap: 8px;623  }624  .domain-header-text {625    display: flex; flex-direction: column; gap: 2px;626    min-width: 0; flex: 1;627  }628  .domain-eyebrow {629    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;630    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;631  }632  .domain-name {633    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);634    font-family: "IBM Plex Mono", monospace;635    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;636  }637  .domain-header-actions {638    display: inline-flex; align-items: center; gap: 5px;639    flex-shrink: 0;640  }641  .domain-add-btn,642  .domain-search-btn {643    flex-shrink: 0;644    width: 22px; height: 22px;645    display: inline-flex; align-items: center; justify-content: center;646    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);647    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);648    border-radius: 6px;649    color: var(--peach-accent);650    cursor: pointer; padding: 0;651    transition: background 120ms, border-color 120ms, transform 80ms;652    font-family: "IBM Plex Mono", monospace;653    font-size: 14px; line-height: 1;654  }655  .domain-add-btn:hover,656  .domain-search-btn:hover {657    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);658    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);659    transform: scale(1.06);660  }661  .domain-add-btn:active,662  .domain-search-btn:active { transform: scale(0.96); }663664  /* Search */665  .search-wrap {666    padding: 9px 12px 7px;667    border-bottom: 1px solid var(--peach-border);668  }669  /* UI-2 / MV-2: brief loading hint while the vault-wide list lazy-loads. */670  .search-loading {671    display: block;672    margin-top: 5px;673    font-size: 10px;674    color: var(--peach-text-dim);675    font-family: "IBM Plex Mono", monospace;676    animation: search-loading-pulse 1s ease-in-out infinite;677  }678  @keyframes search-loading-pulse { 0%,100% { opacity: 0.45; } 50% { opacity: 0.9; } }679  .search {680    width: 100%; background: var(--peach-input-bg);681    border: 1px solid var(--peach-input-border);682    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;683    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;684    transition: border-color 120ms, box-shadow 120ms;685  }686  .search:focus {687    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);688    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);689  }690  .search::placeholder { color: var(--peach-text-muted); }691692  /* Results */693  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }694  .results::-webkit-scrollbar { display: none; }695696  /* Entry rows */697  .entry {698    display: flex; align-items: center; padding: 8px 12px;699    cursor: pointer; border-bottom: 1px solid var(--peach-border);700    transition: background 70ms; position: relative; outline: none;701  }702  .entry:last-child { border-bottom: none; }703  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }704  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }705  .entry.focused::before {706    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;707    width: 2px; border-radius: 2px;708    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);709  }710711  .entry-icon {712    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;713    background: var(--peach-input-bg); border: 1px solid var(--peach-border);714    display: flex; align-items: center; justify-content: center;715    overflow: hidden; margin-right: 10px;716  }717  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }718  .entry-icon.is-new {719    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);720    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);721    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);722  }723724  .entry-info { flex: 1; min-width: 0; }725  .entry-title {726    font-size: 12.5px; color: var(--peach-text);727    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;728    line-height: 1.3;729  }730  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }731  .entry-sub {732    font-size: 10px; color: var(--peach-text-dim);733    font-family: "IBM Plex Mono", monospace;734    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;735    margin-top: 1px;736  }737738  .totp-badge {739    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;740    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);741    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);742    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;743  }744  .passkey-badge {745    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;746    border-radius: 4px;747    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);748    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);749    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);750    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;751  }752753  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }754755  .empty-hint {756    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);757    font-family: "IBM Plex Mono", monospace;758  }759760  /* Create form */761  .create-form-wrap {762    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;763  }764  .create-head {765    display: flex; align-items: center; gap: 8px;766    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);767  }768  .back-btn {769    background: transparent; border: none; cursor: pointer;770    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;771    display: flex; align-items: center; line-height: 0;772    transition: color 100ms, background 100ms;773  }774  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }775  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }776  /* minmax(0, 1fr) caps the grid track at the popup width — without it,777     long monospace content (e.g. a 60-char generated password) would778     auto-size the track wider than the popup and overflow the right edge. */779  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }780  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }781  .f-label {782    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;783    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;784  }785  .f-input {786    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);787    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;788    font-size: 11px; font-family: "IBM Plex Mono", monospace;789    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;790  }791  .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); }792  .f-input::placeholder { color: var(--peach-text-muted); }793  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }794  .f-row { display: flex; gap: 6px; }795  .f-row .f-input { flex: 1; min-width: 0; }796  .gen-btn {797    padding: 0 10px; border-radius: 7px; border: none;798    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);799    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);800    font-size: 10px; font-family: "IBM Plex Mono", monospace;801    cursor: pointer; white-space: nowrap; flex-shrink: 0;802    display: flex; align-items: center; gap: 4px;803    transition: background 100ms;804  }805  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }806  .gen-toggle-link {807    background: none; border: none; padding: 2px 0;808    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);809    font-size: 10px; font-family: "IBM Plex Mono", monospace;810    cursor: pointer; text-align: left; transition: color 100ms;811  }812  .gen-toggle-link:hover { color: var(--peach-accent); }813  .pw-history {814    display: grid; gap: 4px; margin-top: 4px;815    max-height: 150px; overflow-y: auto; scrollbar-width: thin;816  }817  .pw-history-row {818    display: flex; align-items: center; justify-content: space-between; gap: 6px;819    padding: 5px 7px; border-radius: 7px;820    background: color-mix(in srgb, var(--peach-accent) 6%, transparent);821    border: 1px solid color-mix(in srgb, var(--peach-accent) 10%, transparent);822  }823  .pw-history-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }824  .pw-history-pw {825    font-family: "IBM Plex Mono", monospace; font-size: 11px;826    color: var(--peach-t1, #eee); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;827  }828  .pw-history-age {829    font-family: "IBM Plex Mono", monospace; font-size: 9px;830    color: color-mix(in srgb, var(--peach-accent) 55%, transparent); letter-spacing: 0.03em;831  }832  .pw-history-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }833  .pw-history-btn {834    background: none; border: none; padding: 2px 5px; border-radius: 5px;835    color: color-mix(in srgb, var(--peach-accent) 65%, transparent);836    font-size: 9px; font-family: "IBM Plex Mono", monospace; cursor: pointer;837    transition: color 100ms, background 100ms;838  }839  .pw-history-btn:hover {840    color: var(--peach-accent);841    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);842  }843  .pw-history-empty {844    font-family: "IBM Plex Mono", monospace; font-size: 10px; line-height: 1.45;845    color: color-mix(in srgb, var(--peach-accent) 55%, transparent);846    padding: 6px 8px; border-radius: 7px;847    background: color-mix(in srgb, var(--peach-accent) 5%, transparent);848    border: 1px solid color-mix(in srgb, var(--peach-accent) 9%, transparent);849  }850  .save-btn {851    width: 100%; padding: 8px; border-radius: 8px; border: none;852    background: var(--peach-accent); color: #fff; font-size: 12px;853    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;854    transition: background 120ms, box-shadow 120ms, transform 80ms;855    letter-spacing: 0.01em;856  }857  .save-btn:hover {858    background: color-mix(in srgb, var(--peach-accent) 82%, #000);859    box-shadow: 0 4px 20px var(--peach-glow, transparent);860  }861  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }862  .url-hint {863    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);864    font-family: "IBM Plex Mono", monospace; font-style: italic;865  }866867  /* Success */868  .success-wrap {869    display: flex; flex-direction: column; align-items: center;870    padding: 24px 16px 20px; gap: 8px;871    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;872  }873  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }874  .success-ring {875    width: 40px; height: 40px; border-radius: 50%;876    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);877    display: flex; align-items: center; justify-content: center;878  }879  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }880  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }881882  /* Silver platter (State 1 — single match) */883  .silver-platter {884    padding: 14px 14px 12px;885    display: flex; flex-direction: column; gap: 6px;886  }887  .sp-title {888    font-size: 14px; font-weight: 500; color: var(--peach-text);889    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;890    line-height: 1.25;891  }892  .sp-identity-row {893    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;894  }895  .sp-identity-label {896    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;897    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;898  }899  .sp-username {900    font-size: 12px; color: var(--peach-text-dim);901    font-family: "IBM Plex Mono", monospace;902    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;903    margin-bottom: 0;904  }905  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }906  .sp-fill-btn {907    width: 100%; padding: 11px; border-radius: 9px; border: none;908    background: var(--peach-accent); color: #fff;909    font-size: 13px; font-weight: 500; cursor: pointer;910    font-family: Inter, sans-serif; letter-spacing: 0.01em;911    display: flex; align-items: center; justify-content: center; min-height: 38px;912    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;913  }914  .sp-fill-btn:hover {915    filter: brightness(1.1);916    box-shadow: 0 4px 20px var(--peach-glow, transparent);917    transform: translateY(-1px);918  }919  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }920  .sp-fill-btn.filled {921    background: #16a34a; transform: none; filter: none;922    box-shadow: 0 4px 16px rgba(22,163,74,0.35);923    cursor: default;924  }925  .sp-fill-btn:disabled { cursor: default; }926  .sp-actions-group {927    margin-top: 6px;928    display: flex; flex-direction: column; gap: 4px;929  }930  .sp-actions-label {931    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;932    color: var(--peach-text-muted);933    font-family: "IBM Plex Mono", monospace;934    text-align: center;935  }936  .sp-actions {937    display: flex; gap: 4px; justify-content: space-between; align-items: center;938  }939  .sp-action-btn {940    flex: 1; height: 28px; border: none; border-radius: 6px;941    background: transparent; color: var(--peach-text-dim);942    font-size: 12px; cursor: pointer;943    transition: background 120ms ease, color 120ms ease;944    font-family: Inter, sans-serif; letter-spacing: 0.04em;945    display: inline-flex; align-items: center; justify-content: center; gap: 4px;946    white-space: nowrap; overflow: hidden;947  }948  .sp-action-btn:hover:not(:disabled) {949    background: color-mix(in srgb, var(--peach-text) 5%, transparent);950    color: var(--peach-text);951  }952  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }953  .sp-action-btn.flashed {954    color: var(--peach-accent);955    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);956  }957958  /* TOTP tray — shown below the silver-platter secondary actions */959  .sp-tray {960    margin-top: 8px;961    padding: 10px 12px;962    border-radius: 9px;963    background: var(--peach-input-bg);964    border: 1px solid var(--peach-input-border);965    display: flex; align-items: center; gap: 12px;966    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;967  }968  .sp-tray-label {969    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;970    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;971    flex-shrink: 0;972  }973  .sp-totp-code {974    font-size: 18px; font-weight: 500;975    color: var(--peach-text);976    font-family: "IBM Plex Mono", monospace;977    letter-spacing: 0.12em;978    flex: 1;979    text-align: center;980  }981  .sp-totp-ring {982    width: 22px; height: 22px; flex-shrink: 0;983  }984  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }985  .sp-totp-ring .ring-fill {986    stroke: var(--peach-accent);987    transition: stroke-dashoffset 1s linear;988    transform: rotate(-90deg);989    transform-origin: center;990  }991  .sp-totp-copy {992    background: transparent; border: none; cursor: pointer;993    padding: 4px 8px; border-radius: 5px;994    color: var(--peach-text-dim); font-size: 11px;995    font-family: Inter, sans-serif;996    transition: background 120ms, color 120ms;997  }998  .sp-totp-copy:hover {999    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1000    color: var(--peach-text);1001  }10021003  /* Card silver platter (State 7) — reuses .sp-* primary action classes */1004  .card-platter {1005    padding: 12px 14px 10px;1006    display: flex; flex-direction: column; gap: 4px;1007  }1008  .cp-network {1009    font-size: 10px; font-weight: 600;1010    color: var(--peach-accent);1011    letter-spacing: 0.08em; text-transform: uppercase;1012    font-family: Inter, sans-serif;1013  }1014  .cp-nickname {1015    font-size: 14px; font-weight: 500; color: var(--peach-text);1016    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1017    line-height: 1.2;1018  }1019  .cp-last4 {1020    font-size: 12px; color: var(--peach-text-dim);1021    font-family: "IBM Plex Mono", monospace;1022    letter-spacing: 0.04em;1023    margin-top: 2px;1024  }1025  .cp-meta {1026    font-size: 11px; color: var(--peach-text-dim);1027    font-family: "IBM Plex Mono", monospace;1028    margin-top: 2px;1029    display: flex; gap: 10px; align-items: center;1030  }1031  .cp-meta-sep { opacity: 0.5; }1032  .cp-fill-wrap { margin-top: 10px; }10331034  /* Locked state */1035  .locked-wrap {1036    display: flex; flex-direction: column; align-items: stretch;1037    padding: 14px 13px 13px; gap: 9px;1038  }1039  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }1040  .locked-icon {1041    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;1042    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1043    display: flex; align-items: center; justify-content: center;1044  }1045  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }1046  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }1047  .locked-input {1048    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1049    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;1050    font-size: 11px; font-family: "IBM Plex Mono", monospace;1051    outline: none; transition: border-color 120ms, box-shadow 120ms;1052  }1053  .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); }1054  .locked-input::placeholder { color: var(--peach-text-muted); }1055  .locked-btn {1056    width: 100%; padding: 8px; border-radius: 8px; border: none;1057    background: var(--peach-accent); color: #fff; font-size: 12px;1058    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;1059    transition: background 120ms;1060    letter-spacing: 0.01em;1061    box-shadow: 0 2px 16px var(--peach-glow, transparent);1062    animation: peach-pulse-glow 2.4s ease-in-out infinite;1063  }1064  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }1065  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }1066  .locked-error {1067    font-size: 10px; color: rgba(220,80,60,0.85);1068    font-family: "IBM Plex Mono", monospace;1069  }10701071  @keyframes peach-pulse-glow {1072    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }1073    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),1074                            0 0 48px var(--peach-glow, transparent); }1075  }10761077  /* ── State 10: identity helper ─────────────────────────────── */1078  .identity-list {1079    max-height: 192px; overflow-y: auto; padding: 4px 0;1080    scrollbar-width: none;1081  }1082  .identity-list::-webkit-scrollbar { display: none; }1083  .peach-identity-row {1084    display: flex; align-items: center; gap: 10px;1085    padding: 9px 12px; cursor: pointer; border-radius: 8px;1086    transition: background 100ms ease;1087  }1088  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1089  .peach-identity-value {1090    font-family: "IBM Plex Mono", monospace; font-size: 13px;1091    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1092  }1093  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1094  .identity-search-wrap {1095    display: flex; flex-direction: column; gap: 6px;1096  }1097  .identity-mode-toggle {1098    display: inline-flex; gap: 4px; flex-wrap: wrap;1099  }1100  .identity-mode-btn {1101    border: 1px solid var(--peach-input-border);1102    background: var(--peach-input-bg);1103    color: var(--peach-text-dim);1104    border-radius: 999px;1105    padding: 4px 9px;1106    cursor: pointer;1107    font-family: "IBM Plex Mono", monospace;1108    font-size: 9px;1109    letter-spacing: 0.03em;1110    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1111  }1112  .identity-mode-btn:hover {1113    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1114    color: var(--peach-text);1115  }1116  .identity-mode-btn.is-active {1117    color: var(--peach-accent);1118    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1119    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1120  }1121  .identity-mode-btn:active { transform: translateY(1px); }1122  .identity-custom-row {1123    display: flex; flex-direction: column; gap: 2px;1124    padding: 9px 12px; cursor: pointer; border-radius: 8px;1125    transition: background 100ms ease;1126  }1127  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1128  .identity-custom-row-title {1129    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1130  }1131  .identity-custom-row-sub {1132    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1133  }1134  .identity-empty {1135    padding: 10px 12px 2px; color: var(--peach-text-dim);1136    font-size: 10px; font-family: "IBM Plex Mono", monospace;1137  }1138  .identity-alt-row {1139    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1140    border-radius: 8px; transition: background 100ms ease;1141    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1142  }1143  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1144  .identity-escape-row {1145    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1146    border-radius: 8px; transition: background 100ms ease; outline: none;1147    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1148    margin-top: 2px;1149  }1150  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1151  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1152  .identity-alt-input-wrap.open { display: flex; }1153  .identity-alt-input {1154    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1155    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1156    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1157    outline: none; transition: border-color 120ms;1158  }1159  .identity-alt-input:focus {1160    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1161    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1162  }1163  .identity-alt-confirm {1164    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1165    background: var(--peach-accent); color: #fff; font-size: 12px;1166    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1167  }1168  /* ── Generator view (after identity picked) ────────────────── */1169  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1170  .gen-confirmed {1171    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1172    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1173    border-radius: 8px;1174  }1175  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1176  .gen-confirmed-val {1177    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1178    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1179  }1180  .gen-label {1181    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1182    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1183  }1184  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1185  .gen-pw-val {1186    flex: 1; padding: 8px 10px; border-radius: 7px;1187    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1188    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1189    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1190  }1191  .gen-regen-btn {1192    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1193    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1194    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1195    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1196  }1197  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1198  .gen-fill-btn {1199    padding: 10px; border-radius: 8px; border: none;1200    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1201    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1202    transition: filter 120ms ease, transform 80ms ease;1203  }1204  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1205  .gen-fill-btn:active { transform: translateY(0); }12061207  /* ── Smart password generator (parity with main UI compact mode) ─── */1208  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1209  .pwgen-display-row {1210    display: flex; align-items: center; gap: 6px;1211    padding: 8px 10px; border-radius: 7px;1212    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1213  }1214  .pwgen-output {1215    flex: 1; min-width: 0; width: 0;1216    font-family: "IBM Plex Mono", monospace; font-size: 12px;1217    color: var(--peach-text);1218    background: transparent; border: none; outline: none; padding: 0;1219  }1220  .pwgen-icon-btn {1221    flex-shrink: 0;1222    width: 26px; height: 26px;1223    display: inline-flex; align-items: center; justify-content: center;1224    background: transparent; border: 1px solid var(--peach-input-border);1225    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1226    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1227  }1228  .pwgen-icon-btn:hover {1229    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1230    color: var(--peach-accent);1231    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1232  }1233  .pwgen-icon-btn.is-copied {1234    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1235    color: var(--peach-accent);1236    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1237  }1238  .pwgen-controls-row {1239    display: flex; align-items: center; gap: 8px;1240    flex-wrap: wrap;1241  }1242  .pwgen-slider {1243    flex: 1; min-width: 110px;1244    accent-color: var(--peach-accent);1245    cursor: pointer; height: 2px; background: transparent;1246  }1247  .pwgen-len-num {1248    font-family: "IBM Plex Mono", monospace; font-size: 11px;1249    color: var(--peach-accent); min-width: 22px; text-align: right;1250  }1251  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1252  .pwgen-len-input {1253    font-family: "IBM Plex Mono", monospace; font-size: 11px;1254    color: var(--peach-accent); width: 28px; text-align: right;1255    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1256    outline: none; padding: 0; min-width: 22px;1257  }1258  @keyframes identity-suggest-in {1259    from { opacity: 0; transform: translateY(-4px); }1260    to   { opacity: 1; transform: none; }1261  }1262  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1263    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1264  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1265  .identity-collapse-btn {1266    margin-left: auto; background: transparent; border: none; cursor: pointer;1267    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1268    line-height: 0; border-radius: 3px;1269    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1270  }1271  .identity-collapse-btn:hover { color: var(--peach-text); }1272  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1273  .identity-rows { display: grid; grid-template-rows: 1fr;1274    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1275  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1276  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1277    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1278  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1279  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1280  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1281  .identity-filter-pill {1282    padding: 2px 7px; border-radius: 999px;1283    border: 1px solid var(--peach-input-border);1284    background: transparent; color: var(--peach-text-muted);1285    font-family: "IBM Plex Mono", monospace; font-size: 9px;1286    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1287  }1288  .identity-filter-pill.is-on {1289    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1290    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1291    color: var(--peach-accent);1292  }1293  .identity-suggest-row {1294    display: flex; align-items: center; gap: 5px;1295    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1296    background: transparent; cursor: pointer; text-align: left;1297    transition: background 80ms;1298  }1299  .identity-suggest-row:hover,1300  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1301  .identity-suggest-val {1302    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1303    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1304  }1305  .identity-suggest-type {1306    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1307    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1308  }1309  .identity-suggest-type--email {1310    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1311    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1312  }1313  .identity-suggest-type--username {1314    color: var(--peach-text-muted);1315    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1316  }1317  .identity-suggest-meta {1318    font-family: "IBM Plex Mono", monospace; font-size: 9px;1319    color: var(--peach-text-muted); flex-shrink: 0;1320  }1321  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1322  .pwgen-pill {1323    padding: 3px 8px; border-radius: 999px;1324    border: 1px solid var(--peach-input-border);1325    background: transparent; color: var(--peach-text-muted);1326    font-family: "IBM Plex Mono", monospace; font-size: 9px;1327    letter-spacing: 0.06em; cursor: pointer;1328    transition: all 130ms ease;1329  }1330  .pwgen-pill.is-on {1331    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1332    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1333    color: var(--peach-accent);1334  }1335  .pwgen-pill:not(.is-on):hover {1336    color: var(--peach-text-dim);1337    border-color: var(--peach-text-muted);1338  }1339  .pwgen-policy-hint {1340    font-size: 10px; color: var(--peach-text-muted);1341    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1342    line-height: 1.3;1343  }1344  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }13451346  /* ── Save offer (after password filled) ───────────────────── */1347  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1348  .save-offer-title {1349    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1350  }1351  .save-offer-row {1352    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1353    border-radius: 7px; background: var(--peach-input-bg);1354    border: 1px solid var(--peach-input-border);1355  }1356  .save-offer-lbl {1357    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1358    font-family: "IBM Plex Mono", monospace;1359  }1360  .save-offer-val {1361    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1362    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1363  }1364  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1365  .save-offer-save {1366    flex: 1; padding: 9px; border-radius: 8px; border: none;1367    background: var(--peach-accent); color: #fff; font-size: 13px;1368    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1369  }1370  .save-offer-save:hover { filter: brightness(1.08); }1371  .save-offer-skip {1372    flex: 1; padding: 9px; border-radius: 8px; border: none;1373    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1374    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1375    font-family: Inter, sans-serif; transition: background 100ms ease;1376  }1377  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1378`;13791380export function showAutofillSelector(1381  anchorEl: HTMLInputElement,1382  entries: SelectorEntry[],1383  onSelect: (id: string) => void,1384  options: SelectorOptions = {}1385): () => void {1386  const host = document.createElement("div");1387  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1388  // when Peach's internal inputs gain focus, immediately blurring them and closing1389  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1390  // as in-bounds (v3.6.131).1391  //1392  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1393  // A plain login page whose card uses transform/filter/backdrop-filter establishes1394  // a containing block for position:fixed, so a host mounted inside it lands offset1395  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1396  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1397  // the popup ~400px off the field and clipped it behind overflow:clip — the user1398  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1399  // everything else mounts at the document root, where fixed == viewport.1400  const modalAncestor = (1401    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1402    (() => {1403      let cur: HTMLElement | null = anchorEl.parentElement;1404      while (cur && cur !== document.body) {1405        if (window.getComputedStyle(cur).position === 'fixed') return cur;1406        cur = cur.parentElement;1407      }1408      return null;1409    })()1410  );1411  host.style.cssText = `position: fixed; z-index: 2147483647;`;1412  host.style.setProperty("--peach-accent", accentHex);1413  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1414  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1415  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1416  // Hint the compositor that top/left animate during scroll repositioning so the1417  // popup stays on the GPU layer and doesn't flicker as observeAnchorPosition1418  // re-asserts its coordinates.1419  host.style.willChange = "top, left";1420  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1421  // HOST appear focused to the outside DOM. Modal focus traps that monitor1422  // focusin then see the host (mounted inside the modal) as the focused element1423  // rather than an opaque closed-shadow node, so they don't fire their1424  // "focus escaped" handler and yank focus back. Harmless outside modals.1425  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });14261427  const style = shadow.appendChild(document.createElement("style"));1428  style.textContent = SELECTOR_STYLES;14291430  const rect = anchorEl.getBoundingClientRect();1431  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1432  // applying containing-block compensation once host.parentElement is known.1433  host.style.top = `${rect.bottom + 5}px`;1434  host.style.left = `${rect.left}px`;1435  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1436  // wide single-input fields (e.g. centered email input on signup pages).1437  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1438  // expand the host after the initial measurement.1439  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1440  host.style.width = `${popupWidth}px`;14411442  const container = shadow.appendChild(document.createElement("div"));1443  container.className = "peach-inline-popup";1444  container.setAttribute("data-theme", popupTheme);14451446  // MV-2: the vault-wide list is loaded lazily on the first search gesture,1447  // never eagerly on passive popup open. Cached for the popup's lifetime.1448  let searchableEntries: SelectorEntry[] = options.searchableEntries ?? [];1449  let searchableLoading = false;1450  let searchableLoaded = !options.loadSearchableEntries;14511452  async function ensureSearchableLoaded(rerender: () => void): Promise<void> {1453    if (searchableLoaded || searchableLoading || !options.loadSearchableEntries) {1454      return;1455    }1456    searchableLoading = true;1457    try {1458      searchableEntries = await options.loadSearchableEntries();1459    } catch {1460      searchableEntries = [];1461    } finally {1462      searchableLoaded = true;1463      searchableLoading = false;1464      rerender();1465    }1466  }1467  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();14681469  let query = "";1470  let focusedIndex = -1;1471  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" | "edit" = "list";1472  let searchInput: HTMLInputElement | null = null;1473  let identityMode: IdentityFilterMode = "both";1474  // Tracks the silver-platter entry the user pivoted away from, so the1475  // search/list header can offer a one-click way back to it. null when the1476  // popup never showed a single-match platter (e.g. multi-match list view).1477  let silverPlatterOrigin: SelectorEntry | null = null;1478  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1479  // setInterval. Add to this list — don't fan out the dismiss function.1480  const cleanupHooks: Array<() => void> = [];14811482  // Smooth height transitions whenever content changes height.1483  // ResizeObserver fires on natural height changes; we freeze the old height,1484  // then animate to the new one so the surface never jumps.1485  {1486    let prevH = 0;1487    let blocked = false;1488    const heightRo = new ResizeObserver(([entry]) => {1489      if (blocked) return;1490      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1491      if (prevH > 0 && Math.abs(h - prevH) > 1) {1492        blocked = true;1493        container.style.height = `${prevH}px`;1494        requestAnimationFrame(() => requestAnimationFrame(() => {1495          container.style.height = `${h}px`;1496          prevH = h;1497          const onEnd = (e: TransitionEvent) => {1498            if (e.propertyName !== "height") return;1499            container.style.height = "";1500            blocked = false;1501            container.removeEventListener("transitionend", onEnd);1502          };1503          container.addEventListener("transitionend", onEnd);1504        }));1505      } else {1506        prevH = h;1507      }1508    });1509    heightRo.observe(container);1510    cleanupHooks.push(() => heightRo.disconnect());1511  }15121513  // Pre-capture the anchor field value for username prefill1514  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1515  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1516  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";15171518  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1519    const seen = new Set<string>();1520    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1521  }15221523  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1524    const q = value.trim().toLowerCase();1525    const deduped = uniqueEntries(source);1526    if (!q) return deduped.slice(0, 8);1527    return deduped.filter(e =>1528      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1529    ).slice(0, 12);1530  }15311532  function activeEntries(): SelectorEntry[] {1533    // When user is typing a search, filter across all known entries (domain matches + vault)1534    if (query.trim()) {1535      const merged = uniqueEntries([...entries, ...searchableEntries]);1536      return filterEntries(merged, query);1537    }1538    // Default: show domain matches; fall back to vault search when no matches1539    if (entries.length > 0) return entries;1540    return filterEntries(searchableEntries, "").slice(0, 8);1541  }15421543  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1544    const icon = document.createElement("div");1545    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1546    if (isNew) {1547      icon.innerHTML = plusSvgStr();1548    } else {1549      // Use the generic key glyph for all entries in the page-injected selector.1550      // Avoids disclosing vault domains to any third party and avoids needing1551      // to expose the browser favicon API to page context via web_accessible_resources.1552      void url;1553      icon.innerHTML = keySvgStr();1554    }1555    return icon;1556  }15571558  function renderIdentityHelper() {1559    currentMode = "identity-helper";1560    container.innerHTML = "";1561    focusedIndex = -1;1562    searchInput = null;15631564    const fallbackKind: IdentityKind = options.identityKind ?? "username";1565    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1566    const typedQuery = query.trim();1567    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);15681569    function applyIdentity(identity: string) {1570      if (options.hasEmailField) {1571        if (options.identityKind === "email") {1572          options.onFillFields?.("", "", identity);       // fill email field now1573          renderSecondaryIdentityStep("username", identity);1574        } else {1575          options.onFillFields?.(identity, "", "");       // fill username field now1576          renderSecondaryIdentityStep("email", identity);1577        }1578      } else {1579        options.onFillFields?.(identity, "");1580        renderGenerator(identity);1581      }1582    }15831584    function applyCustomIdentity(identity: string) {1585      const trimmed = identity.trim();1586      if (!trimmed) return;1587      applyIdentity(trimmed);1588    }15891590    // Header: "NEW ACCOUNT" + domain name1591    const hdr = container.appendChild(document.createElement("div"));1592    hdr.className = "domain-header";1593    const headText = hdr.appendChild(document.createElement("div"));1594    headText.className = "domain-header-text";1595    const eyebrow = headText.appendChild(document.createElement("div"));1596    eyebrow.className = "domain-eyebrow";1597    eyebrow.textContent = "NEW ACCOUNT";1598    const domName = headText.appendChild(document.createElement("div"));1599    domName.className = "domain-name";1600    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");16011602    const actions = hdr.appendChild(document.createElement("div"));1603    actions.className = "identity-mode-toggle";1604    for (const mode of ["both", "email", "username"] as const) {1605      const btn = actions.appendChild(document.createElement("button"));1606      btn.type = "button";1607      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1608      btn.textContent = identityFilterLabel(mode);1609      btn.setAttribute("aria-pressed", String(identityMode === mode));1610      btn.addEventListener("click", () => {1611        identityMode = mode;1612        renderIdentityHelper();1613      });1614    }16151616    const searchWrap = container.appendChild(document.createElement("div"));1617    searchWrap.className = "search-wrap identity-search-wrap";1618    const search = searchWrap.appendChild(document.createElement("input"));1619    search.className = "search";1620    search.placeholder = "search identities…";1621    search.value = query;1622    search.addEventListener("input", () => {1623      query = search.value;1624      renderIdentityHelper();1625      searchInput?.focus();1626      searchInput?.setSelectionRange(query.length, query.length);1627    });1628    search.addEventListener("keydown", (e) => {1629      if (e.key === "Escape") {1630        e.preventDefault();1631        dismiss(true);1632        return;1633      }1634      if (e.key !== "Enter") return;1635      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1636      if (exact) {1637        e.preventDefault();1638        applyIdentity(exact.value);1639        return;1640      }1641      if (!typedQuery || identities.length > 0) return;1642      e.preventDefault();1643      applyCustomIdentity(typedQuery);1644    });1645    const searchTools = searchWrap.appendChild(document.createElement("div"));1646    searchTools.className = "identity-mode-toggle";1647    const sortHint = searchTools.appendChild(document.createElement("div"));1648    sortHint.className = "identity-empty";1649    sortHint.style.padding = "0";1650    sortHint.textContent = "sorted by recent use";1651    searchInput = search;1652    const customLabel = identityMode === "both"1653      ? customKind1654      : identityMode;16551656    // Identity rows1657    const list = container.appendChild(document.createElement("div"));1658    list.className = "identity-list";1659    // Bottom fade only when the list overflows its max-height and isn't scrolled1660    // to the end. A short list (1-2 identities) shows no fade, so it never looks1661    // prematurely cut off; a long list gets the affordance, which clears on1662    // reaching the bottom.1663    const updateListFade = () => {1664      const overflowing = list.scrollHeight > list.clientHeight + 1;1665      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1666      const mask = overflowing && !atBottom1667        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1668        : "none";1669      list.style.setProperty("mask-image", mask);1670      list.style.setProperty("-webkit-mask-image", mask);1671    };1672    list.addEventListener("scroll", updateListFade);1673    if (typedQuery && identities.length === 0) {1674      const empty = list.appendChild(document.createElement("div"));1675      empty.className = "identity-empty";1676      empty.textContent = identityMode === "both"1677        ? `No match for “${typedQuery}”.`1678        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1679      const custom = list.appendChild(document.createElement("div"));1680      custom.className = "identity-custom-row";1681      const customTitle = custom.appendChild(document.createElement("div"));1682      customTitle.className = "identity-custom-row-title";1683      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1684      const customSub = custom.appendChild(document.createElement("div"));1685      customSub.className = "identity-custom-row-sub";1686      customSub.textContent = "Press Enter or click to continue.";1687      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1688    }1689    for (const id of identities) {1690      const row = list.appendChild(document.createElement("div"));1691      row.className = "peach-identity-row";1692      row.setAttribute("tabindex", "-1");1693      const val = row.appendChild(document.createElement("div"));1694      val.className = "peach-identity-value";1695      val.textContent = id.value;1696      const meta = row.appendChild(document.createElement("div"));1697      meta.className = "peach-identity-meta";1698      meta.textContent = `used ${id.useCount}×`;1699      row.addEventListener("click", () => {1700        applyIdentity(id.value);1701      });1702    }17031704    updateListFade();17051706    // Divider before "Use a different email…"1707    if (identities.length > 0) {1708      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1709    }17101711    // "Use a different email/username…" expandable row1712    const altRow = container.appendChild(document.createElement("div"));1713    altRow.className = "identity-alt-row";1714    altRow.textContent = `+ Use a different ${customLabel}…`;17151716    const altInputWrap = container.appendChild(document.createElement("div"));1717    altInputWrap.className = "identity-alt-input-wrap";1718    const altInput = altInputWrap.appendChild(document.createElement("input"));1719    altInput.className = "identity-alt-input";1720    altInput.type = "text";1721    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1722    altInput.setAttribute("autocomplete", "off");1723    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1724    altConfirm.className = "identity-alt-confirm";1725    altConfirm.type = "button";1726    altConfirm.textContent = "✓";17271728    function fillCustomIdentity() {1729      const v = altInput.value.trim();1730      if (!v) return;1731      applyCustomIdentity(v);1732    }17331734    altRow.addEventListener("click", () => {1735      altRow.style.display = "none";1736      altInputWrap.classList.add("open");1737      altInput.value = typedQuery || altInput.value;1738      altInput.focus();1739      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1740    });1741    altConfirm.addEventListener("click", fillCustomIdentity);1742    altInput.addEventListener("keydown", (e) => {1743      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1744    });17451746    // Escape hatch: user already has a vault entry for this site but it1747    // wasn't detected (different domain, old entry, etc.). Tapping this1748    // switches to the full searchable list so they can find and fill it;1749    // selecting an entry there will trigger the remember-site toast if1750    // the domain isn't already associated.1751    // MV-2: with lazy loading we no longer know the vault-wide count up front,1752    // so offer the escape hatch whenever a loader (or an eager array) exists.1753    if (options.loadSearchableEntries || (options.searchableEntries?.length ?? 0) > 0) {1754      const escapeRow = container.appendChild(document.createElement("div"));1755      escapeRow.className = "identity-escape-row";1756      escapeRow.textContent = "I already have an account →";1757      escapeRow.setAttribute("tabindex", "0");1758      const toSearch = () => { void ensureSearchableLoaded(renderList); renderList(); };1759      escapeRow.addEventListener("click", toSearch);1760      escapeRow.addEventListener("keydown", (e) => {1761        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toSearch(); }1762      });1763    }17641765    requestAnimationFrame(() => {1766      search.focus();1767      search.setSelectionRange(query.length, query.length);1768    });1769  }17701771  /**1772   * Step 2 of the contextual signup wizard.1773   * `stepKind` is the identity type to collect in this step ("email" or "username").1774   * `firstValue` is what was picked in step 1 (the other type).1775   */1776  function renderSecondaryIdentityStep(stepKind: "email" | "username", firstValue: string) {1777    currentMode = "identity-helper";1778    container.innerHTML = "";17791780    const wrap = container.appendChild(document.createElement("div"));1781    wrap.className = "gen-view";17821783    // Header1784    const hdrRow = wrap.appendChild(document.createElement("div"));1785    hdrRow.className = "domain-header";1786    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1787    eyebrow2.className = "domain-eyebrow";1788    eyebrow2.textContent = "NEW ACCOUNT";1789    const domName2 = hdrRow.appendChild(document.createElement("div"));1790    domName2.className = "domain-name";1791    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");17921793    // Confirmed first step1794    const conf = wrap.appendChild(document.createElement("div"));1795    conf.className = "gen-confirmed";1796    const confCheck = conf.appendChild(document.createElement("span"));1797    confCheck.className = "gen-confirmed-check";1798    confCheck.textContent = "✓";1799    const confVal = conf.appendChild(document.createElement("div"));1800    confVal.className = "gen-confirmed-val";1801    confVal.textContent = firstValue;18021803    const stepLbl = wrap.appendChild(document.createElement("div"));1804    stepLbl.className = "gen-label";1805    stepLbl.textContent = stepKind === "email" ? "Now choose your email" : "Now choose your username";18061807    // Filter saved identities to the correct type for this step1808    const identities = (options.savedIdentities ?? [])1809      .filter(s => s.type === stepKind)1810      .sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0))1811      .slice(0, 6);18121813    const list = wrap.appendChild(document.createElement("div"));1814    list.className = "identity-list";1815    for (const id of identities) {1816      const row = list.appendChild(document.createElement("div"));1817      row.className = "peach-identity-row";1818      row.setAttribute("tabindex", "-1");1819      const val = row.appendChild(document.createElement("div"));1820      val.className = "peach-identity-value";1821      val.textContent = id.value;1822      const meta = row.appendChild(document.createElement("div"));1823      meta.className = "peach-identity-meta";1824      meta.textContent = `used ${id.useCount}×`;1825      row.addEventListener("click", () => applySecondIdentity(id.value));1826    }18271828    // Text input for a value not in the list1829    const altInputWrap = wrap.appendChild(document.createElement("div"));1830    altInputWrap.className = "identity-alt-input-wrap open";1831    const altInput = altInputWrap.appendChild(document.createElement("input"));1832    altInput.className = "identity-alt-input";1833    altInput.type = stepKind === "email" ? "email" : "text";1834    altInput.placeholder = stepKind === "email" ? "[email protected]" : "your username";1835    altInput.setAttribute("autocomplete", "off");1836    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1837    altConfirm.className = "identity-alt-confirm";1838    altConfirm.type = "button";1839    altConfirm.textContent = "→";18401841    function applySecondIdentity(value: string) {1842      const trimmed = value.trim();1843      if (!trimmed) return;1844      // Determine final email + username order before passing to the generator1845      const [email, username] = stepKind === "email"1846        ? [trimmed, firstValue]1847        : [firstValue, trimmed];1848      if (stepKind === "email") {1849        options.onFillFields?.("", "", trimmed); // fill email field1850      } else {1851        options.onFillFields?.(trimmed, "", ""); // fill username field1852      }1853      renderGenerator(email, username);1854    }18551856    altConfirm.addEventListener("click", () => applySecondIdentity(altInput.value));1857    altInput.addEventListener("keydown", (e) => {1858      if (e.key === "Enter") { e.preventDefault(); applySecondIdentity(altInput.value); }1859    });18601861    // Skip: proceed without this field1862    const skipRow = wrap.appendChild(document.createElement("div"));1863    skipRow.className = "identity-escape-row";1864    skipRow.textContent = `Skip ${stepKind} →`;1865    skipRow.setAttribute("tabindex", "0");1866    skipRow.addEventListener("click", () => {1867      const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1868      renderGenerator(email, username);1869    });1870    skipRow.addEventListener("keydown", (e) => {1871      if (e.key === "Enter" || e.key === " ") {1872        e.preventDefault();1873        const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];1874        renderGenerator(email, username);1875      }1876    });18771878    requestAnimationFrame(() => { altInput.focus(); });1879  }18801881  function renderGenerator(filledEmail: string, filledUsername?: string) {1882    container.innerHTML = "";1883    const sitePolicy = detectPasswordPolicy();18841885    const wrap = container.appendChild(document.createElement("div"));1886    wrap.className = "gen-view";18871888    // Header: domain + NEW ACCOUNT1889    const hdrRow = wrap.appendChild(document.createElement("div"));1890    hdrRow.className = "domain-header";1891    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1892    eyebrow2.className = "domain-eyebrow";1893    eyebrow2.textContent = "NEW ACCOUNT";1894    const domName2 = hdrRow.appendChild(document.createElement("div"));1895    domName2.className = "domain-name";1896    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");18971898    // Confirmed identity rows — show both username and email when both were collected1899    function confirmedRow(value: string) {1900      const conf = wrap.appendChild(document.createElement("div"));1901      conf.className = "gen-confirmed";1902      const confCheck = conf.appendChild(document.createElement("span"));1903      confCheck.className = "gen-confirmed-check";1904      confCheck.textContent = "✓";1905      const confVal = conf.appendChild(document.createElement("div"));1906      confVal.className = "gen-confirmed-val";1907      confVal.textContent = value;1908    }1909    if (filledEmail) confirmedRow(filledEmail);1910    if (filledUsername && filledUsername !== filledEmail) confirmedRow(filledUsername);19111912    const lbl = wrap.appendChild(document.createElement("div"));1913    lbl.className = "gen-label";1914    lbl.textContent = "Generate a password";19151916    let currentPw = "";1917    const smartGen = createSmartGenerator({1918      policy: sitePolicy,1919      onChange: (pw) => { currentPw = pw; },1920    });1921    wrap.appendChild(smartGen.root);19221923    const fillBtn = wrap.appendChild(document.createElement("button"));1924    fillBtn.className = "gen-fill-btn";1925    fillBtn.type = "button";1926    fillBtn.textContent = "Copy & fill";1927    fillBtn.addEventListener("click", async () => {1928      if (!currentPw) return;1929      fillBtn.disabled = true;1930      fillBtn.textContent = "Saving…";1931      // Fill the page fields first — password lands immediately.1932      options.onFillFields?.("", currentPw, "");1933      // Auto-save to vault. Fall back to the save-offer form only if the save fails1934      // (vault locked, quota exceeded, etc.) so the user sees the error and can retry.1935      const saveUsername = filledUsername || filledEmail;1936      const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;1937      try {1938        const res = await chrome.runtime.sendMessage({1939          type: "ADD_ENTRY",1940          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: currentPw, type: "login" },1941        });1942        if ((res as { ok?: boolean }).ok) {1943          showSuccess(sTitle);1944        } else {1945          renderSaveOffer(filledEmail, currentPw, filledUsername);1946        }1947      } catch {1948        renderSaveOffer(filledEmail, currentPw, filledUsername);1949      }1950    });1951  }19521953  function renderSaveOffer(filledEmail: string, filledPassword: string, filledUsername?: string) {1954    container.innerHTML = "";1955    const domain = options.domain ?? location.hostname.replace(/^www\./, "");19561957    const wrap = container.appendChild(document.createElement("div"));1958    wrap.className = "save-offer";19591960    const title = wrap.appendChild(document.createElement("div"));1961    title.className = "save-offer-title";1962    title.textContent = "Save this login to Peach?";19631964    function detailRow(label: string, value: string) {1965      const row = wrap.appendChild(document.createElement("div"));1966      row.className = "save-offer-row";1967      const lbl = row.appendChild(document.createElement("div"));1968      lbl.className = "save-offer-lbl";1969      lbl.textContent = label;1970      const val = row.appendChild(document.createElement("div"));1971      val.className = "save-offer-val";1972      val.textContent = value;1973    }19741975    detailRow("site", domain);1976    // When both username and email were collected, show both; otherwise show the identity as "email"1977    if (filledUsername) {1978      detailRow("username", filledUsername);1979      if (filledEmail) detailRow("email", filledEmail);1980    } else {1981      if (filledEmail) detailRow("email", filledEmail);1982    }1983    detailRow("password", "••••••••••••••••");19841985    const btns = wrap.appendChild(document.createElement("div"));1986    btns.className = "save-offer-btns";19871988    const saveBtn = btns.appendChild(document.createElement("button"));1989    saveBtn.className = "save-offer-save";1990    saveBtn.type = "button";1991    saveBtn.textContent = "Save";1992    saveBtn.addEventListener("click", async () => {1993      saveBtn.disabled = true;1994      saveBtn.textContent = "Saving…";1995      try {1996        // When both username and email were set, save them in the correct fields.1997        // Otherwise fall back to storing the identity as the username (current behaviour).1998        const saveUsername = filledUsername || filledEmail;1999        const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;2000        const res = await chrome.runtime.sendMessage({2001          type: "ADD_ENTRY",2002          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: filledPassword, type: "login" },2003        });2004        if ((res as { ok?: boolean }).ok) {2005          showSuccess(sTitle);2006        } else {2007          saveBtn.disabled = false;2008          saveBtn.textContent = "Save";2009        }2010      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }2011    });20122013    const skipBtn = btns.appendChild(document.createElement("button"));2014    skipBtn.className = "save-offer-skip";2015    skipBtn.type = "button";2016    skipBtn.textContent = "Not now";2017    skipBtn.addEventListener("click", () => { dismiss(true); });2018  }20192020  function renderList() {2021    container.innerHTML = "";2022    focusedIndex = -1;2023    searchInput = null;2024    currentMode = "list";20252026    const current = activeEntries();20272028    // Domain header (always show) — eyebrow + domain on the left,2029    // a "+" shortcut to the create form on the right so the user is never2030    // trapped in the search list when they want to make a new entry.2031    const domHdr = document.createElement("div");2032    domHdr.className = "domain-header";2033    const headText = document.createElement("div");2034    headText.className = "domain-header-text";2035    const eyebrow = document.createElement("div");2036    eyebrow.className = "domain-eyebrow";2037    eyebrow.textContent = options.isSignup2038      ? "Sign up as"2039      : entries.length > 0 ? "Saved for this site" : "No saved login";2040    const domName = document.createElement("div");2041    domName.className = "domain-name";2042    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2043    headText.append(eyebrow, domName);2044    domHdr.appendChild(headText);20452046    if (!options.isSignup) {2047      const actions = document.createElement("div");2048      actions.className = "domain-header-actions";20492050      // Back arrow takes the place of the silver-platter's search icon when2051      // the user has pivoted away from a single-match platter — gives them2052      // a one-click way back to the original recommendation.2053      if (silverPlatterOrigin) {2054        const backBtn = document.createElement("button");2055        backBtn.className = "domain-search-btn";2056        backBtn.type = "button";2057        backBtn.setAttribute("aria-label", "Back to suggested entry");2058        backBtn.title = "Back to suggested entry";2059        backBtn.innerHTML = backSvgStr();2060        backBtn.addEventListener("click", (e) => {2061          e.stopPropagation();2062          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);2063        });2064        actions.appendChild(backBtn);2065      }20662067      const addBtn = document.createElement("button");2068      addBtn.className = "domain-add-btn";2069      addBtn.type = "button";2070      addBtn.setAttribute("aria-label", "Create new entry");2071      addBtn.title = "Create new entry";2072      addBtn.textContent = "+";2073      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2074      actions.appendChild(addBtn);20752076      domHdr.appendChild(actions);2077    }20782079    container.appendChild(domHdr);20802081    // Search — always show so user can find entries beyond the domain matches2082    const sw = document.createElement("div"); sw.className = "search-wrap";2083    searchInput = document.createElement("input");2084    searchInput.className = "search";2085    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";2086    searchInput.value = query;2087    searchInput.addEventListener("input", () => {2088      query = searchInput?.value ?? "";2089      // MV-2: typing in the search box is the explicit gesture that loads the2090      // vault-wide list (once, cached); it re-renders when it resolves.2091      void ensureSearchableLoaded(renderList);2092      renderList();2093      searchInput?.focus();2094      searchInput?.setSelectionRange(query.length, query.length);2095    });2096    sw.appendChild(searchInput);2097    // UI-2 / MV-2: show a brief loading hint while the vault-wide list loads2098    // on the first search gesture (cached afterwards, so only the first time).2099    if (searchableLoading) {2100      const loadingHint = document.createElement("span");2101      loadingHint.className = "search-loading";2102      loadingHint.textContent = "searching…";2103      sw.appendChild(loadingHint);2104    }2105    container.appendChild(sw);21062107    // Results2108    const results = document.createElement("div");2109    results.className = "results";2110    container.appendChild(results);21112112    if (current.length === 0 && entries.length > 0) {2113      // Show a hint but don't render empty entries2114    }21152116    for (let i = 0; i < current.length; i++) {2117      const e = current[i]!;2118      const entryEl = document.createElement("div");2119      entryEl.className = "entry";2120      entryEl.dataset.id = e.id;2121      entryEl.dataset.index = String(i);2122      entryEl.setAttribute("tabindex", "-1");21232124      entryEl.appendChild(makeEntryIcon(e.url));21252126      const info = document.createElement("div"); info.className = "entry-info";2127      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;2128      const subEl = document.createElement("div"); subEl.className = "entry-sub";2129      const domain = e.url ? getDomainFromUrl(e.url) : "";2130      subEl.textContent = domain || e.username || "";2131      info.append(titleEl, subEl);2132      entryEl.appendChild(info);21332134      if (e.hasTotp) {2135        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";2136        entryEl.appendChild(badge);2137      }2138      if (e.hasPasskey) {2139        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";2140        entryEl.appendChild(badge);2141      }21422143      entryEl.addEventListener("click", () => {2144        if (options.isSignup && options.onFillFields) {2145          // Fill username, email, and leave password for the user to confirm2146          options.onFillFields(e.username ?? "", "", e.email);2147          dismiss();2148        } else {2149          onSelect(e.id);2150          dismiss();2151        }2152      });2153      results.appendChild(entryEl);2154    }21552156    // Divider before "New entry"2157    if (current.length > 0) {2158      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));2159    }21602161    // "New entry" row — always present2162    const newEl = document.createElement("div");2163    newEl.className = "entry";2164    newEl.setAttribute("tabindex", "-1");2165    newEl.appendChild(makeEntryIcon(undefined, true));21662167    const newInfo = document.createElement("div"); newInfo.className = "entry-info";2168    const newTitle = document.createElement("div");2169    newTitle.className = "entry-title is-new";2170    newTitle.textContent = `New entry for ${sTitle}`;2171    const newSub = document.createElement("div");2172    newSub.className = "entry-sub";2173    newSub.textContent = sOrigin;2174    newInfo.append(newTitle, newSub);2175    newEl.appendChild(newInfo);2176    newEl.addEventListener("click", showCreateForm);2177    results.appendChild(newEl);21782179    // Focus search if present2180    if (searchInput) {2181      requestAnimationFrame(() => {2182        searchInput?.focus();2183        // Seed query (from type-to-search or domain-search-btn) lands at the2184        // end so the next keystroke extends it, not overwrites.2185        searchInput?.setSelectionRange(query.length, query.length);2186      });2187    }2188  }21892190  function setFocused(idx: number) {2191    const all = container.querySelectorAll<HTMLElement>(".entry");2192    all.forEach((el, i) => el.classList.toggle("focused", i === idx));2193    focusedIndex = idx;2194    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });2195  }21962197  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {2198    const typed = identities.filter(s => s.type === fieldType);2199    if (!typed.length) return;2200    let collapsed = false;2201    let suppressNextFocus = false;22022203    const list = g.appendChild(document.createElement("div"));2204    list.className = "identity-suggest-list";2205    list.style.display = "none";22062207    // Collapse toggle — sits alone now that filter pills are gone2208    const collapseRow = list.appendChild(document.createElement("div"));2209    collapseRow.className = "identity-filter-row";2210    collapseRow.style.justifyContent = "flex-end";2211    const collapseBtn = collapseRow.appendChild(document.createElement("button"));2212    collapseBtn.type = "button";2213    collapseBtn.className = "identity-collapse-btn";2214    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>`;2215    collapseBtn.addEventListener("mousedown", (e) => {2216      e.preventDefault();2217      collapsed = !collapsed;2218      collapseBtn.classList.toggle("is-collapsed", collapsed);2219      rowsWrapper.classList.toggle("is-collapsed", collapsed);2220    });22212222    const rowsWrapper = list.appendChild(document.createElement("div"));2223    rowsWrapper.className = "identity-rows";2224    const rows = rowsWrapper.appendChild(document.createElement("div"));2225    rows.className = "identity-rows-inner";22262227    // Bottom fade only when the list actually overflows and isn't scrolled to2228    // the end — a static mask-image fades the last row even on a 1-2 item list2229    // that fits entirely, making it look cut off. Driven off live scroll state.2230    const updateRowsFade = () => {2231      const overflowing = rows.scrollHeight > rows.clientHeight + 1;2232      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;2233      const mask = overflowing && !atBottom2234        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"2235        : "none";2236      rows.style.setProperty("mask-image", mask);2237      rows.style.setProperty("-webkit-mask-image", mask);2238    };2239    rows.addEventListener("scroll", updateRowsFade);22402241    // Hides the list and removes the document-level click watcher.2242    function hideList() {2243      list.style.display = "none";2244      document.removeEventListener("mousedown", onDocMousedown, { capture: true });2245    }22462247    // Dismiss list on any mousedown that originates outside the popup's shadow2248    // DOM. This is the ONLY close trigger for the list — blur is intentionally2249    // NOT used, because modal focus traps fire blur without a mousedown (they2250    // call element.focus() programmatically in response to focusin/focusout),2251    // which caused the list to vanish before the user could pick from it.2252    function onDocMousedown(e: MouseEvent) {2253      if (e.composedPath().includes(host)) return;2254      hideList();2255    }22562257    function pick(value: string) {2258      inp.value = value;2259      hideList();2260      suppressNextFocus = true;2261      inp.focus();2262      // If a focus trap intercepts inp.focus() and redirects to anchorEl before2263      // inp ever fires its focus event, suppressNextFocus would strand the user.2264      // Clear after a short window so subsequent clicks still work.2265      setTimeout(() => { suppressNextFocus = false; }, 120);2266    }22672268    function render() {2269      const q = inp.value.toLowerCase();2270      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2271      rows.innerHTML = "";2272      if (!filtered.length) { hideList(); return; }2273      for (const s of filtered) {2274        const row = rows.appendChild(document.createElement("button"));2275        row.type = "button"; row.className = "identity-suggest-row";2276        const val = row.appendChild(document.createElement("span"));2277        val.className = "identity-suggest-val"; val.textContent = s.value;2278        const meta = row.appendChild(document.createElement("span"));2279        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2280        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2281        row.addEventListener("keydown", (e) => {2282          if (e.key === "ArrowDown") {2283            e.preventDefault();2284            (row.nextElementSibling as HTMLElement | null)?.focus();2285          } else if (e.key === "ArrowUp") {2286            e.preventDefault();2287            const prev = row.previousElementSibling as HTMLElement | null;2288            if (prev) prev.focus();2289            else inp.focus();2290          } else if (e.key === "Enter" || e.key === " ") {2291            e.preventDefault();2292            pick(s.value);2293          } else if (e.key === "Escape") {2294            e.preventDefault();2295            hideList();2296            suppressNextFocus = true;2297            inp.focus();2298          }2299        });2300        // Row blur only fires during keyboard navigation (arrow keys / Tab).2301        // Focus traps don't produce row blur events since rows aren't focused2302        // when the trap fires; this handler is therefore trap-safe.2303        row.addEventListener("blur", (e) => {2304          const rt = (e as FocusEvent).relatedTarget as Node | null;2305          if (rt && (rt === inp || list.contains(rt))) return;2306          setTimeout(() => { hideList(); }, 150);2307        });2308      }2309      list.style.display = "";2310      updateRowsFade();2311      // Register the close-on-outside-click watcher each time the list shows.2312      // addEventListener deduplicates identical (fn, options) pairs, so2313      // re-rendering on input events does not stack up listeners.2314      document.addEventListener("mousedown", onDocMousedown, { capture: true });2315    }23162317    inp.addEventListener("focus", () => {2318      if (suppressNextFocus) { suppressNextFocus = false; return; }2319      render();2320    });2321    inp.addEventListener("input", render);2322    inp.addEventListener("keydown", (e) => {2323      if (list.style.display === "none") return;2324      if (e.key === "ArrowDown" && !collapsed) {2325        e.preventDefault();2326        (rows.firstElementChild as HTMLElement | null)?.focus();2327      } else if (e.key === "Escape") {2328        e.preventDefault();2329        hideList();2330      } else if (e.key === "Tab") {2331        // Tab moves focus away intentionally — close the list.2332        hideList();2333      }2334    });2335    // No blur handler on inp. Blur fires for ANY focus movement including2336    // programmatic focus() calls from modal focus traps, which caused the list2337    // to close before the user could interact. The document mousedown listener2338    // (registered in render()) handles intentional click-outside dismissal,2339    // and the keydown handler above covers keyboard Tab/Escape.23402341    // Ensure the watcher is removed if the main popup is dismissed while the2342    // list is visible.2343    cleanupHooks.push(hideList);2344  }23452346  async function showCreateForm() {2347    currentMode = "create";2348    container.innerHTML = "";23492350    // Guard: the service worker may lock the vault between when the selector2351    // opens and when the user clicks "New entry". Show the inline unlock form2352    // instead of silently failing on save.2353    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;2354    if (!statusRes?.unlocked) {2355      renderLocked();2356      return;2357    }23582359    // Detect page password policy once for this form — reused on every2360    // regenerate click so the user always gets a compliant password.2361    const sitePolicy = detectPasswordPolicy();23622363    // Fetch identities on-demand — they're passed in signup context but not2364    // in login/search context where the user still clicks "New entry".2365    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];2366    if (!formIdentities.length) {2367      try {2368        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;2369        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;2370      } catch { /* silent fallback */ }2371    }23722373    const wrap = document.createElement("div");2374    wrap.className = "create-form-wrap";23752376    // Header2377    const head = document.createElement("div"); head.className = "create-head";2378    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2379    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>`;2380    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2381    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2382    head.append(backBtn, lbl);23832384    // Body2385    const body = document.createElement("div"); body.className = "create-body";23862387    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2388      const g = document.createElement("div"); g.className = "f-group";2389      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2390      const inp = document.createElement("input"); inp.className = "f-input";2391      g.append(l, inp); return { g, inp };2392    }23932394    // Title2395    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2396    body.appendChild(tg.g);23972398    // URL2399    const ug = fGroup("website");2400    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2401    if (loginSubdomain) {2402      const h = document.createElement("div"); h.className = "url-hint";2403      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2404    }2405    body.appendChild(ug.g);24062407    // Username — pre-fill from anchor if it doesn't look like an email2408    const xg = fGroup("username");2409    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2410    xg.inp.placeholder = "johndoe";2411    xg.inp.setAttribute("autocomplete", "off");2412    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2413    body.appendChild(xg.g);24142415    // Email — pre-fill from anchor if it looks like an email2416    const eg = fGroup("email");2417    (eg.inp as HTMLInputElement).type = "email";2418    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2419    eg.inp.placeholder = "[email protected]";2420    eg.inp.setAttribute("autocomplete", "off");2421    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2422    body.appendChild(eg.g);24232424    // Password — full smart generator with charset pills + length slider +2425    // policy hint. Mirrors the main UI's compact generator so users get the2426    // same controls inline as in the popup.2427    const pg = fGroup("password");2428    pg.inp.remove(); // smartGen provides its own display — no separate input needed2429    let currentPassword = prePassword || "";2430    const smartGen = createSmartGenerator({2431      policy: sitePolicy,2432      initialPassword: prePassword || undefined,2433      onChange: (pw) => { currentPassword = pw; },2434    });2435    pg.g.appendChild(smartGen.root);2436    body.appendChild(pg.g);24372438    // Save2439    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2440    saveBtn.textContent = "Save entry";2441    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2442    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2443    saveBtn.addEventListener("click", async () => {2444      const title = tg.inp.value.trim();2445      const pw = currentPassword.trim();2446      const username = xg.inp.value.trim();2447      const email = eg.inp.value.trim();2448      if (!title) {2449        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2450        showFormError("Entry needs a title");2451        return;2452      }2453      if (!pw) {2454        showFormError("Entry needs a password — tap regen to make one");2455        return;2456      }2457      errEl.style.display = "none";2458      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2459      try {2460        const res = await chrome.runtime.sendMessage({2461          type: "ADD_ENTRY",2462          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2463        });2464        if ((res as { ok?: boolean }).ok) {2465          // Fill the detected form. onFillFields uses whichever identity the2466          // page anchored on — the vault captures both username and email.2467          options.onFillFields?.(username || email, pw);2468          showSuccess(title);2469        } else {2470          const err = (res as { error?: string })?.error;2471          const errMsg = err === "vault_locked"2472            ? "Vault locked — open Peach to save"2473            : err === "STORAGE_QUOTA_EXCEEDED"2474              ? "Out of storage — open Peach → Settings to free space"2475              : err2476                ? `Could not save: ${err}`2477                : "Could not save entry";2478          showFormError(errMsg);2479          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2480        }2481      } catch (e) {2482        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2483        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2484      }2485    });2486    body.appendChild(saveBtn);2487    body.appendChild(errEl);24882489    wrap.append(head, body);2490    container.appendChild(wrap);2491    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2492  }24932494  function showSuccess(title: string) {2495    currentMode = "success";2496    container.innerHTML = "";2497    const wrap = document.createElement("div"); wrap.className = "success-wrap";2498    const ring = document.createElement("div"); ring.className = "success-ring";2499    ring.innerHTML = checkSvgStr();2500    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2501    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2502    wrap.append(ring, t, s);2503    container.appendChild(wrap);2504    setTimeout(() => dismiss(), 1600);2505  }25062507  function flashActionBtn(btn: HTMLButtonElement) {2508    btn.classList.add("flashed");2509    setTimeout(() => btn.classList.remove("flashed"), 700);2510  }25112512  // M3/QUA-005: when both the direct clipboard write and the background COPY2513  // fallback fail, briefly show the user that the copy did not happen.2514  function flashCopyError(btn: HTMLButtonElement) {2515    const original = btn.textContent ?? "";2516    btn.textContent = "Blocked";2517    btn.classList.add("flashed");2518    setTimeout(() => {2519      btn.classList.remove("flashed");2520      if (btn.isConnected) btn.textContent = original;2521    }, 1200);2522  }25232524  function renderSilverPlatter(entry: SelectorEntry) {2525    container.innerHTML = "";2526    searchInput = null;2527    focusedIndex = -1;2528    currentMode = "silver-platter";2529    silverPlatterOrigin = entry;25302531    const domHdr = document.createElement("div");2532    domHdr.className = "domain-header";2533    const headText = document.createElement("div");2534    headText.className = "domain-header-text";2535    const eyebrow = document.createElement("div");2536    eyebrow.className = "domain-eyebrow";2537    eyebrow.textContent = "Saved for this site";2538    const domName = document.createElement("div");2539    domName.className = "domain-name";2540    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2541    headText.append(eyebrow, domName);2542    domHdr.appendChild(headText);2543    if (!options.isSignup) {2544      const actions = document.createElement("div");2545      actions.className = "domain-header-actions";25462547      // Search shortcut — same idea as type-to-search below, but visible so2548      // the user can discover that another entry is reachable from a2549      // single-match platter. Sits to the left of the create button.2550      const searchBtn = document.createElement("button");2551      searchBtn.className = "domain-search-btn";2552      searchBtn.type = "button";2553      searchBtn.setAttribute("aria-label", "Search for a different entry");2554      searchBtn.title = "Search for a different entry";2555      searchBtn.innerHTML = searchSvgStr();2556      searchBtn.addEventListener("click", (e) => {2557        e.stopPropagation();2558        query = "";2559        renderList();2560      });2561      actions.appendChild(searchBtn);25622563      const addBtn = document.createElement("button");2564      addBtn.className = "domain-add-btn";2565      addBtn.type = "button";2566      addBtn.setAttribute("aria-label", "Create new entry");2567      addBtn.title = "Create new entry";2568      addBtn.textContent = "+";2569      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2570      actions.appendChild(addBtn);25712572      domHdr.appendChild(actions);2573    }2574    container.appendChild(domHdr);25752576    const platter = document.createElement("div");2577    platter.className = "silver-platter";25782579    const titleEl = document.createElement("div");2580    titleEl.className = "sp-title";2581    titleEl.textContent = entry.title;2582    platter.appendChild(titleEl);25832584    if (entry.email) {2585      const emailEl = document.createElement("div");2586      emailEl.className = "sp-identity-row";2587      const emailLbl = document.createElement("span");2588      emailLbl.className = "sp-identity-label";2589      emailLbl.textContent = "email";2590      const emailVal = document.createElement("span");2591      emailVal.className = "sp-username";2592      emailVal.textContent = entry.email;2593      emailEl.append(emailLbl, emailVal);2594      platter.appendChild(emailEl);2595    }25962597    if (entry.username) {2598      const userEl = document.createElement("div");2599      userEl.className = "sp-identity-row";2600      const userLbl = document.createElement("span");2601      userLbl.className = "sp-identity-label";2602      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2603      const userVal = document.createElement("span");2604      userVal.className = "sp-username";2605      userVal.textContent = entry.username;2606      userEl.append(userLbl, userVal);2607      platter.appendChild(userEl);2608    }26092610    const fillBtn = document.createElement("button");2611    fillBtn.className = "sp-fill-btn";2612    fillBtn.type = "button";2613    fillBtn.textContent = "Fill credentials";2614    fillBtn.addEventListener("click", () => {2615      if (fillBtn.disabled) return;2616      fillBtn.disabled = true;2617      fillBtn.classList.add("filled");2618      fillBtn.innerHTML = checkSvgStr();2619      // Fire the fill, then exit via the standard exit animation. The fill2620      // itself is async (handled in index.ts) — by 400ms the form is filled2621      // and the popup begins its exit. Total dwell from click to host2622      // removal: 400ms + 130ms (exit animation) = 530ms.2623      onSelect(entry.id);2624      setTimeout(() => dismiss(), 400);2625    });2626    platter.appendChild(fillBtn);26272628    const actionsGroup = document.createElement("div");2629    actionsGroup.className = "sp-actions-group";2630    const actionsLabel = document.createElement("div");2631    actionsLabel.className = "sp-actions-label";2632    actionsLabel.textContent = "Copy";2633    actionsGroup.appendChild(actionsLabel);26342635    const actions = document.createElement("div");2636    actions.className = "sp-actions";2637    actionsGroup.appendChild(actions);26382639    if (entry.email) {2640      const copyEmail = document.createElement("button");2641      copyEmail.className = "sp-action-btn";2642      copyEmail.type = "button";2643      copyEmail.title = "Copy email";2644      copyEmail.textContent = "Email";2645      copyEmail.addEventListener("click", async (e) => {2646        e.stopPropagation();2647        let alreadyWritten = false;2648        try {2649          await navigator.clipboard.writeText(entry.email!);2650          alreadyWritten = true;2651        } catch (err) {2652          console.warn("[Peach] clipboard write denied:", err);2653        }2654        const resp = await chrome.runtime.sendMessage({2655          type: "COPY",2656          payload: { text: entry.email, label: "Email", alreadyWritten },2657        }).catch(() => null) as { ok?: boolean } | null;2658        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2659        else flashCopyError(copyEmail);2660      });2661      actions.appendChild(copyEmail);2662    }26632664    const copyU = document.createElement("button");2665    copyU.className = "sp-action-btn";2666    copyU.type = "button";2667    const usernameIsEmail = entry.username?.includes("@") ?? false;2668    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2669    copyU.textContent = usernameIsEmail ? "Email" : "Username";2670    copyU.disabled = !entry.username;2671    copyU.addEventListener("click", async (e) => {2672      e.stopPropagation();2673      if (!entry.username) return;2674      let alreadyWritten = false;2675      try {2676        await navigator.clipboard.writeText(entry.username);2677        alreadyWritten = true;2678      } catch (err) {2679        console.warn("[Peach] clipboard write denied:", err);2680      }2681      const resp = await chrome.runtime.sendMessage({2682        type: "COPY",2683        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2684      }).catch(() => null) as { ok?: boolean } | null;2685      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2686      else flashCopyError(copyU);2687    });2688    actions.appendChild(copyU);26892690    const copyP = document.createElement("button");2691    copyP.className = "sp-action-btn";2692    copyP.type = "button";2693    copyP.title = "Copy password";2694    copyP.textContent = "Password";2695    copyP.addEventListener("click", async (e) => {2696      e.stopPropagation();2697      const resp = await chrome.runtime.sendMessage({2698        type: "GET_ENTRY_FOR_FILL",2699        // MV-1: user explicitly picked this entry from Peach's inline summon UI.2700        payload: { id: entry.id, explicitSummon: true },2701      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2702      if (!resp?.ok || !resp.data?.password) return;2703      let alreadyWritten = false;2704      try {2705        await navigator.clipboard.writeText(resp.data.password);2706        alreadyWritten = true;2707      } catch (err) {2708        console.warn("[Peach] clipboard write denied:", err);2709      }2710      const copyResp = await chrome.runtime.sendMessage({2711        type: "COPY",2712        payload: { text: resp.data.password, label: "Password", alreadyWritten },2713      }).catch(() => null) as { ok?: boolean } | null;2714      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2715      else flashCopyError(copyP);2716    });2717    actions.appendChild(copyP);27182719    let trayEl: HTMLDivElement | null = null;2720    let trayInterval: ReturnType<typeof setInterval> | null = null;27212722    function closeTray() {2723      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2724      trayEl?.remove();2725      trayEl = null;2726    }2727    // Register so dismiss() will close the tray and clear the interval2728    // even if the user dismisses without explicitly closing the tray.2729    cleanupHooks.push(closeTray);27302731    async function openTOTPTray() {2732      // Fetch the current TOTP code from the background. The raw base32 seed2733      // never enters the content script (SEV-3-C): we receive the live 6-digit2734      // code plus the seconds remaining, count down locally, and re-fetch a2735      // fresh code only when the 30s window rolls over.2736      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2737        const r = await chrome.runtime.sendMessage({2738          type: "GET_ENTRY_FOR_FILL",2739          // MV-1: explicit user summon of this entry's live TOTP code.2740          payload: { id: entry.id, explicitSummon: true },2741        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2742        if (!r?.ok || !r.data?.totpCode) return null;2743        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2744      }2745      let current = await fetchCode();2746      if (!current) return;27472748      trayEl = document.createElement("div");2749      trayEl.className = "sp-tray";27502751      const label = document.createElement("span");2752      label.className = "sp-tray-label";2753      label.textContent = "2FA";2754      trayEl.appendChild(label);27552756      const codeEl = document.createElement("div");2757      codeEl.className = "sp-totp-code";2758      trayEl.appendChild(codeEl);27592760      const ringNs = "http://www.w3.org/2000/svg";2761      const ring = document.createElementNS(ringNs, "svg");2762      ring.setAttribute("class", "sp-totp-ring");2763      ring.setAttribute("viewBox", "0 0 24 24");2764      const trackC = document.createElementNS(ringNs, "circle");2765      trackC.setAttribute("class", "ring-track");2766      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2767      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2768      const fillC = document.createElementNS(ringNs, "circle");2769      fillC.setAttribute("class", "ring-fill");2770      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2771      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2772      fillC.setAttribute("stroke-linecap", "round");2773      fillC.setAttribute("stroke-dasharray", "62.83");2774      ring.append(trackC, fillC);2775      trayEl.appendChild(ring);27762777      const copyBtn = document.createElement("button");2778      copyBtn.className = "sp-totp-copy";2779      copyBtn.type = "button";2780      copyBtn.textContent = "Copy";2781      trayEl.appendChild(copyBtn);27822783      function render() {2784        const { code, remaining } = current!;2785        // Group as "847 291" — easier to read than "847291"2786        codeEl.textContent = code.length === 62787          ? `${code.slice(0, 3)} ${code.slice(3)}`2788          : code;2789        // Ring fills counter-clockwise as time elapses: dashoffset goes from2790        // 0 (full ring) to 62.83 (empty) over the 30s window.2791        const fraction = (30 - remaining) / 30;2792        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2793      }2794      render();2795      trayInterval = setInterval(async () => {2796        if (!current) return;2797        current = { code: current.code, remaining: current.remaining - 1 };2798        // Window rolled over — pull a fresh code from the background.2799        if (current.remaining <= 0) {2800          const next = await fetchCode();2801          current = next ?? { code: current.code, remaining: 30 };2802        }2803        render();2804      }, 1000);28052806      copyBtn.addEventListener("click", async (e) => {2807        e.stopPropagation();2808        const code = current?.code;2809        if (!code) return;2810        let alreadyWritten = false;2811        try {2812          await navigator.clipboard.writeText(code);2813          alreadyWritten = true;2814        } catch (err) {2815          console.warn("[Peach] clipboard write denied:", err);2816        }2817        const resp = await chrome.runtime.sendMessage({2818          type: "COPY",2819          payload: { text: code, label: "TOTP", alreadyWritten },2820        }).catch(() => null) as { ok?: boolean } | null;2821        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2822        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2823      });28242825      platter.appendChild(trayEl);2826    }28272828    const editBtn = document.createElement("button");2829    editBtn.className = "sp-action-btn sp-action-edit";2830    editBtn.type = "button";2831    editBtn.title = "Edit entry";2832    editBtn.textContent = "Edit";2833    editBtn.addEventListener("click", (e) => {2834      e.stopPropagation();2835      closeTray();2836      void renderInlineEdit(entry);2837    });2838    actions.appendChild(editBtn);28392840    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2841    // "···" toggle was zero-savings (the toggle button took the same space2842    // the "2FA" label needed) and made the code one extra click away.2843    if (entry.hasTotp) void openTOTPTray();28442845    platter.appendChild(actionsGroup);2846    container.appendChild(platter);2847  }28482849  /**2850   * Inline-popup edit mode. Swaps the silver platter for an editable form2851   * over the same shadow-DOM surface so the user never leaves the page.2852   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2853   * with the new fields. Cancel returns without writing.2854   */2855  async function renderInlineEdit(summary: SelectorEntry) {2856    currentMode = "edit";2857    container.innerHTML = "";2858    const wrap = document.createElement("div");2859    wrap.className = "create-form-wrap";28602861    const head = document.createElement("div");2862    head.className = "create-head";2863    const back = document.createElement("button");2864    back.className = "back-btn";2865    back.type = "button";2866    back.title = "Cancel";2867    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>`;2868    back.addEventListener("click", () => renderSilverPlatter(summary));2869    head.appendChild(back);2870    const headLbl = document.createElement("div");2871    headLbl.className = "create-label";2872    headLbl.textContent = "Edit entry";2873    head.appendChild(headLbl);2874    wrap.appendChild(head);28752876    const body = document.createElement("div");2877    body.className = "create-body";28782879    // Loading shimmer while we fetch the full entry2880    const loading = document.createElement("div");2881    loading.className = "empty-hint";2882    loading.textContent = "loading…";2883    body.appendChild(loading);2884    wrap.appendChild(body);2885    container.appendChild(wrap);28862887    const [res, idRes] = await Promise.all([2888      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2889      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2890      chrome.runtime.sendMessage({2891        type: "GET_ENTRY_FOR_EDIT",2892        payload: { id: summary.id },2893      }).catch(() => null),2894      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2895    ]);2896    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string; passwordHistory?: PasswordHistoryItem[] } } | null;2897    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];28982899    if (!entryRes || !entryRes.ok || !entryRes.data) {2900      loading.textContent = "couldn't load this entry. try again from the popup.";2901      return;2902    }2903    body.innerHTML = "";29042905    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2906      const group = document.createElement("div");2907      group.className = "f-group";2908      const lbl = document.createElement("div");2909      lbl.className = "f-label";2910      lbl.textContent = label;2911      const input = document.createElement("input");2912      input.className = "f-input";2913      input.type = type;2914      input.value = value;2915      input.autocomplete = "off";2916      group.append(lbl, input);2917      body.appendChild(group);2918      return { g: group, inp: input };2919    }29202921    const titleInput = field("title", entryRes.data.title ?? "").inp;2922    const urlInput = field("url", entryRes.data.url ?? "").inp;2923    urlInput.classList.add("url-f");2924    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2925    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2926    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2927    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2928    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");29292930    // Password row with reveal toggle + generator2931    const pwGroup = document.createElement("div");2932    pwGroup.className = "f-group";2933    const pwLbl = document.createElement("div");2934    pwLbl.className = "f-label";2935    pwLbl.textContent = "password";2936    const pwRow = document.createElement("div");2937    pwRow.className = "f-row";2938    const pwInput = document.createElement("input");2939    pwInput.className = "f-input";2940    pwInput.type = "password";2941    pwInput.value = entryRes.data.password ?? "";2942    pwInput.autocomplete = "new-password";2943    const revealBtn = document.createElement("button");2944    revealBtn.className = "gen-btn";2945    revealBtn.type = "button";2946    revealBtn.textContent = "show";2947    revealBtn.addEventListener("click", () => {2948      const reveal = pwInput.type === "password";2949      pwInput.type = reveal ? "text" : "password";2950      revealBtn.textContent = reveal ? "hide" : "show";2951    });2952    pwRow.append(pwInput, revealBtn);2953    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2954    editSmartGen.root.style.display = "none";2955    let editGenVisible = false;2956    const genToggleBtn = document.createElement("button");2957    genToggleBtn.className = "gen-toggle-link";2958    genToggleBtn.type = "button";2959    genToggleBtn.textContent = "⚙ generate";2960    genToggleBtn.addEventListener("click", () => {2961      editGenVisible = !editGenVisible;2962      pwRow.style.display = editGenVisible ? "none" : "";2963      editSmartGen.root.style.display = editGenVisible ? "" : "none";2964      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2965    });2966    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);29672968    // Past-password history: reveal, copy, or restore a previously-used value.2969    // Rows are masked by default; "use" loads the old value into the editor so2970    // the standard save flow records the swap (no separate write path). The2971    // toggle is always present (matching the main popup) so the affordance is2972    // discoverable — even before any history exists it explains how it fills.2973    const history = entryRes.data.passwordHistory ?? [];2974    {2975      const histList = document.createElement("div");2976      histList.className = "pw-history";2977      histList.style.display = "none";2978      let histVisible = false;29792980      const restLabel = history.length ? `↺ history (${history.length})` : "↺ history";2981      const histToggle = document.createElement("button");2982      histToggle.className = "gen-toggle-link";2983      histToggle.type = "button";2984      histToggle.textContent = restLabel;2985      histToggle.addEventListener("click", () => {2986        histVisible = !histVisible;2987        histList.style.display = histVisible ? "" : "none";2988        histToggle.textContent = histVisible ? "↺ hide history" : restLabel;2989      });29902991      if (history.length === 0) {2992        const empty = document.createElement("div");2993        empty.className = "pw-history-empty";2994        empty.textContent = "No earlier passwords yet. When you change this password, the old one is saved here so you can copy or restore it.";2995        histList.appendChild(empty);2996      }29972998      for (const item of history) {2999        const row = document.createElement("div");3000        row.className = "pw-history-row";3001        const main = document.createElement("div");3002        main.className = "pw-history-main";3003        const pwText = document.createElement("div");3004        pwText.className = "pw-history-pw";3005        let revealed = false;3006        const mask = "••••••••••••";3007        pwText.textContent = mask;3008        const age = document.createElement("div");3009        age.className = "pw-history-age";3010        age.textContent = timeSince(item.changedAt);3011        main.append(pwText, age);30123013        const acts = document.createElement("div");3014        acts.className = "pw-history-actions";3015        const revealBtn2 = document.createElement("button");3016        revealBtn2.className = "pw-history-btn";3017        revealBtn2.type = "button";3018        revealBtn2.textContent = "show";3019        revealBtn2.addEventListener("click", () => {3020          revealed = !revealed;3021          pwText.textContent = revealed ? item.password : mask;3022          revealBtn2.textContent = revealed ? "hide" : "show";3023        });3024        const copyBtn2 = document.createElement("button");3025        copyBtn2.className = "pw-history-btn";3026        copyBtn2.type = "button";3027        copyBtn2.textContent = "copy";3028        copyBtn2.addEventListener("click", async () => {3029          let alreadyWritten = false;3030          try {3031            await navigator.clipboard.writeText(item.password);3032            alreadyWritten = true;3033          } catch (err) {3034            console.warn("[Peach] clipboard write denied:", err);3035          }3036          await chrome.runtime.sendMessage({3037            type: "COPY",3038            payload: { text: item.password, label: "Password", alreadyWritten },3039          }).catch(() => null);3040          copyBtn2.textContent = "copied";3041          setTimeout(() => { if (copyBtn2.isConnected) copyBtn2.textContent = "copy"; }, 1200);3042        });3043        const useBtn = document.createElement("button");3044        useBtn.className = "pw-history-btn";3045        useBtn.type = "button";3046        useBtn.textContent = "use";3047        useBtn.title = "Use this password again";3048        useBtn.addEventListener("click", () => {3049          pwInput.value = item.password;3050          pwInput.type = "text";3051          revealBtn.textContent = "hide";3052          if (editGenVisible) {3053            editGenVisible = false;3054            pwRow.style.display = "";3055            editSmartGen.root.style.display = "none";3056            genToggleBtn.textContent = "⚙ generate";3057          }3058          histVisible = false;3059          histList.style.display = "none";3060          histToggle.textContent = `↺ history (${history.length})`;3061        });3062        acts.append(revealBtn2, copyBtn2, useBtn);3063        row.append(main, acts);3064        histList.appendChild(row);3065      }30663067      pwGroup.append(histToggle, histList);3068    }30693070    body.appendChild(pwGroup);30713072    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;30733074    // Notes3075    const notesGroup = document.createElement("div");3076    notesGroup.className = "f-group";3077    const notesLbl = document.createElement("div");3078    notesLbl.className = "f-label";3079    notesLbl.textContent = "notes";3080    const notesInput = document.createElement("textarea");3081    notesInput.className = "f-input";3082    notesInput.rows = 3;3083    notesInput.value = entryRes.data.notes ?? "";3084    notesInput.style.fontFamily = "Inter, sans-serif";3085    notesInput.style.resize = "vertical";3086    notesGroup.append(notesLbl, notesInput);3087    body.appendChild(notesGroup);30883089    // Save / Cancel row3090    const actionsRow = document.createElement("div");3091    actionsRow.className = "f-row";3092    const saveBtn = document.createElement("button");3093    saveBtn.className = "save-btn";3094    saveBtn.type = "button";3095    saveBtn.textContent = "Save changes";3096    saveBtn.style.flex = "1";3097    const cancelBtn = document.createElement("button");3098    cancelBtn.className = "gen-btn";3099    cancelBtn.type = "button";3100    cancelBtn.textContent = "cancel";3101    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));3102    actionsRow.append(saveBtn, cancelBtn);3103    body.appendChild(actionsRow);31043105    saveBtn.addEventListener("click", async () => {3106      saveBtn.disabled = true;3107      const originalLabel = saveBtn.textContent;3108      saveBtn.textContent = "Saving…";3109      const patch: Record<string, unknown> = {3110        title: titleInput.value.trim(),3111        url: urlInput.value.trim(),3112        username: usernameInput.value.trim(),3113        email: emailInput.value.trim() || undefined,3114        password: pwInput.value,3115        totp: totpInput.value.trim(),3116        notes: notesInput.value,3117      };3118      const updateRes = (await chrome.runtime.sendMessage({3119        type: "UPDATE_ENTRY",3120        payload: { id: summary.id, patch },3121      }).catch(() => null)) as { ok: boolean; error?: string } | null;3122      if (!updateRes?.ok) {3123        saveBtn.disabled = false;3124        saveBtn.textContent = originalLabel;3125        const err = document.createElement("div");3126        err.className = "empty-hint";3127        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";3128        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";3129        body.appendChild(err);3130        setTimeout(() => err.remove(), 3000);3131        return;3132      }3133      // Refresh the platter with updated summary fields3134      const refreshed: SelectorEntry = {3135        id: summary.id,3136        title: patch.title as string,3137        username: patch.username as string,3138        email: patch.email as string | undefined,3139        url: patch.url as string,3140        hasTotp: Boolean(patch.totp),3141        hasPasskey: summary.hasPasskey,3142      };3143      renderSilverPlatter(refreshed);3144    });31453146    queueMicrotask(() => titleInput.focus());3147  }31483149  function renderLocked() {3150    container.innerHTML = "";31513152    // Domain header (same as list view)3153    const domHdr = document.createElement("div");3154    domHdr.className = "domain-header";3155    const eyebrow = document.createElement("div");3156    eyebrow.className = "domain-eyebrow";3157    eyebrow.textContent = "vault locked";3158    const domName = document.createElement("div");3159    domName.className = "domain-name";3160    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3161    domHdr.append(eyebrow, domName);3162    container.appendChild(domHdr);31633164    const wrap = document.createElement("div");3165    wrap.className = "locked-wrap";31663167    // Icon + label row3168    const head = document.createElement("div"); head.className = "locked-head";3169    const icon = document.createElement("div"); icon.className = "locked-icon";3170    icon.innerHTML = keySvgStr();3171    const title = document.createElement("div"); title.className = "locked-title";3172    title.textContent = "unlock to autofill";3173    head.append(icon, title);31743175    // The master password is NEVER collected in page-hosted DOM. A malicious3176    // page can observe keystrokes on the shared DOM event stream (a capture-3177    // phase listener registered before Peach injects sees every key before any3178    // stopImmediatePropagation), which would leak the vault's root secret3179    // (audit HIGH). Instead, route unlocking to the trusted extension popup,3180    // where keystrokes are isolated from the page. After the user unlocks3181    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill3182    // automatically (see content/index.ts), so the flow resumes on its own.3183    const sub = document.createElement("div");3184    sub.className = "locked-sub";3185    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";31863187    const openBtn = document.createElement("button");3188    openBtn.className = "locked-btn";3189    openBtn.type = "button";3190    openBtn.textContent = "Open Peach to unlock";3191    openBtn.addEventListener("click", () => {3192      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});3193      openBtn.textContent = "opening Peach…";3194      openBtn.disabled = true;3195      // openPopup() can't always open programmatically (browser/version/gesture3196      // limits); reset so the user can retry or click the toolbar icon.3197      setTimeout(() => {3198        if (openBtn.isConnected) {3199          openBtn.textContent = "Open Peach to unlock";3200          openBtn.disabled = false;3201        }3202      }, 2500);3203    });32043205    wrap.append(head, sub, openBtn);3206    container.appendChild(wrap);3207  }32083209  function handleKeyDown(e: KeyboardEvent) {3210    // PCH-01-007: reject page-synthesised KeyboardEvents — only genuine3211    // keystrokes may drive selection/fill. A page hosting an open selector could3212    // otherwise dispatch ArrowDown/Enter at `document` to fill without user intent.3213    if (!e.isTrusted) return;3214    if (options.locked) {3215      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3216      return;3217    }3218    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {3219      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3220      return;3221    }3222    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");3223    const count = allEntryEls.length;3224    const activeElement = shadow.activeElement ?? document.activeElement;3225    if (activeElement === searchInput) {3226      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }3227      if (count === 0) return;3228      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;3229    }3230    if (count === 0) return;3231    switch (e.key) {3232      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3233      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3234      case "Enter": {3235        if (focusedIndex >= 0) {3236          const el = allEntryEls[focusedIndex] as HTMLElement;3237          const id = el.dataset.id;3238          if (id) { onSelect(id); dismiss(); }3239          else if (el.classList.contains("is-new") || !id) {3240            // "New entry" row (last item, no data-id)3241            showCreateForm();3242          }3243        }3244        break;3245      }3246      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3247    }3248  }32493250  document.addEventListener("keydown", handleKeyDown);32513252  // Type-to-search from the silver platter. A printable single-character3253  // keystroke (no modifier) seeds the search query and switches into the3254  // list view, so the user can pivot to a different entry without first3255  // clicking the search icon. Capture phase so the anchor input does not3256  // receive the character before we hijack it.3257  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3258    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3259    if (currentMode !== "silver-platter") return;3260    if (e.ctrlKey || e.metaKey || e.altKey) return;3261    if (e.key.length !== 1) return;3262    e.preventDefault();3263    e.stopImmediatePropagation();3264    query = e.key;3265    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3266    void ensureSearchableLoaded(renderList);3267    renderList();3268  };3269  document.addEventListener("keydown", silverPlatterTypeHandler, true);3270  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));32713272  const identityHelperTypeHandler = (e: KeyboardEvent) => {3273    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3274    if (currentMode !== "identity-helper") return;3275    if (e.ctrlKey || e.metaKey || e.altKey) return;3276    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3277    if (active === searchInput) return;3278    if (3279      active instanceof HTMLInputElement ||3280      active instanceof HTMLTextAreaElement ||3281      (active instanceof HTMLElement && active.isContentEditable)3282    ) {3283      return;3284    }3285    if (e.key.length !== 1) return;3286    e.preventDefault();3287    e.stopImmediatePropagation();3288    query = e.key;3289    renderIdentityHelper();3290  };3291  document.addEventListener("keydown", identityHelperTypeHandler, true);3292  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));32933294  (modalAncestor ?? document.body).appendChild(host);32953296  // position:fixed normally resolves to the viewport, but an ancestor with3297  // transform / filter / backdrop-filter / perspective / contain / will-change3298  // establishes a containing block, so "fixed" then resolves to that ancestor's3299  // padding box instead. When the host is mounted inside such an ancestor (a3300  // modal) we subtract its border-box origin so the popup still lands at the3301  // field's true viewport position. At the document root there is no such3302  // ancestor and the offset is zero.3303  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3304    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3305    return (3306      has("transform") || has("perspective") || has("translate") ||3307      has("rotate") || has("scale") || has("filter") ||3308      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3309      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3310      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3311    );3312  }3313  function containingBlockOffset(): { dx: number; dy: number } {3314    let el: HTMLElement | null = host.parentElement;3315    while (el && el !== document.documentElement) {3316      const s = getComputedStyle(el);3317      if (establishesFixedContainingBlock(s)) {3318        const r = el.getBoundingClientRect();3319        return {3320          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3321          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3322        };3323      }3324      el = el.parentElement;3325    }3326    return { dx: 0, dy: 0 };3327  }33283329  function updatePosition() {3330    const r = anchorEl.getBoundingClientRect();3331    const { dx, dy } = containingBlockOffset();3332    host.style.top = `${r.bottom - dy + 5}px`;3333    host.style.left = `${r.left - dx}px`;3334    host.style.width = `${popupWidth}px`;3335  }3336  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3337  updatePosition();33383339  // observeAnchorPosition listens on window scroll, but a modal with its own3340  // internal scroll container doesn't move the window — track the modal's scroll3341  // too so the popup follows the field inside it.3342  if (modalAncestor) {3343    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3344    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3345  }33463347  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3348  // swap) removes the field without firing blur/click, so none of the normal3349  // dismiss triggers fire and the popup would otherwise linger over nothing.3350  const removalObserver = new MutationObserver(() => {3351    if (!document.contains(anchorEl)) dismiss();3352  });3353  removalObserver.observe(document.body, { childList: true, subtree: true });3354  cleanupHooks.push(() => removalObserver.disconnect());33553356  if (options.locked) {3357    renderLocked();3358  } else if (options.isSignup && options.savedIdentities) {3359    // State 10: identity helper — signup form detected, show derived3360    // identity list (emails then usernames) instead of vault entry list.3361    renderIdentityHelper();3362  } else if (entries.length === 1 && !options.isSignup) {3363    // Silver platter (State 1): single domain match → focused fill view.3364    // Multi-match goes through renderList instead.3365    renderSilverPlatter(entries[0]!);3366  } else {3367    renderList();3368  }33693370  let exitScheduled = false;3371  function dismiss(userAction = false) {3372    // Idempotent: dismiss() can be called from multiple paths (Escape,3373    // outside click, entry select, fill success, host page nav). The exit3374    // animation must only play once and host.remove() must run exactly once.3375    if (exitScheduled) return;3376    exitScheduled = true;3377    // Detach listeners synchronously so nothing can re-trigger during the3378    // 130ms exit window (a focusin firing here would race against the3379    // dismiss-lock work in Pass 2).3380    stopObserving();3381    document.removeEventListener("click", outsideClick, { capture: true });3382    document.removeEventListener("keydown", handleKeyDown);3383    for (const cleanup of cleanupHooks) {3384      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3385    }3386    if (userAction) options.onDismiss?.();3387    container.classList.add("is-exiting");3388    setTimeout(() => host.remove(), 130);3389  }33903391  function outsideClick(ev: MouseEvent) {3392    const path = ev.composedPath();3393    // Never dismiss when clicking the anchor field itself — that click is3394    // what triggered the selector to open, and the user may click the field3395    // again to re-focus it without intending to close the selector.3396    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3397  }3398  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3399  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);34003401  return dismiss;3402}34033404export function showTOTPSelector(3405  anchorEl: HTMLInputElement,3406  entries: SelectorEntry[],3407  onFill: (id: string) => void,3408  options: { domain?: string; onDismiss?: () => void } = {}3409): () => void {3410  const host = document.createElement("div");3411  host.style.cssText = "position: absolute; z-index: 2147483647;";3412  host.style.setProperty("--peach-accent", accentHex);3413  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3414  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3415  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3416  const shadow = host.attachShadow({ mode: "closed" });34173418  const style = shadow.appendChild(document.createElement("style"));3419  style.textContent = SELECTOR_STYLES;34203421  const rect = anchorEl.getBoundingClientRect();3422  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3423  host.style.left = `${rect.left + window.scrollX}px`;3424  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3425  host.style.width = `${popupWidth}px`;34263427  const container = shadow.appendChild(document.createElement("div"));3428  container.className = "peach-inline-popup";3429  container.setAttribute("data-theme", popupTheme);34303431  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3432  const current = entries.filter((entry) => entry.hasTotp);3433  let focusedIndex = current.length === 1 ? 0 : -1;34343435  function updatePosition() {3436    const r = anchorEl.getBoundingClientRect();3437    host.style.top = `${r.bottom + window.scrollY + 5}px`;3438    host.style.left = `${r.left + window.scrollX}px`;3439    host.style.width = `${popupWidth}px`;3440  }34413442  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);34433444  function choose(entry: SelectorEntry) {3445    onFill(entry.id);3446    dismiss();3447  }34483449  function render() {3450    container.innerHTML = "";34513452    const domHdr = document.createElement("div");3453    domHdr.className = "domain-header";3454    const headText = document.createElement("div");3455    headText.className = "domain-header-text";3456    const eyebrow = document.createElement("div");3457    eyebrow.className = "domain-eyebrow";3458    eyebrow.textContent = "2FA code";3459    const domName = document.createElement("div");3460    domName.className = "domain-name";3461    domName.textContent = domain;3462    headText.append(eyebrow, domName);3463    domHdr.appendChild(headText);3464    container.appendChild(domHdr);34653466    if (current.length === 1) {3467      const entry = current[0]!;3468      const platter = document.createElement("div");3469      platter.className = "silver-platter";34703471      const title = document.createElement("div");3472      title.className = "sp-title";3473      title.textContent = entry.title;3474      platter.appendChild(title);34753476      const sub = document.createElement("div");3477      sub.className = "sp-username";3478      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3479      platter.appendChild(sub);34803481      const fill = document.createElement("button");3482      fill.className = "sp-fill-btn";3483      fill.type = "button";3484      fill.textContent = "Fill 2FA code";3485      fill.addEventListener("click", () => choose(entry));3486      platter.appendChild(fill);34873488      container.appendChild(platter);3489      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3490      return;3491    }34923493    const results = document.createElement("div");3494    results.className = "results";3495    container.appendChild(results);34963497    for (let i = 0; i < current.length; i++) {3498      const entry = current[i]!;3499      const row = document.createElement("div");3500      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3501      row.dataset.index = String(i);3502      row.setAttribute("tabindex", "-1");35033504      const icon = document.createElement("div");3505      icon.className = "entry-icon";3506      icon.innerHTML = keySvgStr();3507      row.appendChild(icon);3508      const info = document.createElement("div");3509      info.className = "entry-info";3510      const title = document.createElement("div");3511      title.className = "entry-title";3512      title.textContent = entry.title;3513      const sub = document.createElement("div");3514      sub.className = "entry-sub";3515      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3516      info.append(title, sub);3517      row.appendChild(info);35183519      const badge = document.createElement("span");3520      badge.className = "totp-badge";3521      badge.textContent = "Fill";3522      row.appendChild(badge);3523      row.addEventListener("click", () => choose(entry));3524      results.appendChild(row);3525    }3526  }35273528  function setFocused(index: number) {3529    focusedIndex = index;3530    container.querySelectorAll(".entry").forEach((el, i) => {3531      el.classList.toggle("focused", i === focusedIndex);3532      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3533    });3534  }35353536  function handleKeyDown(e: KeyboardEvent) {3537    if (e.key === "Escape" || e.key === "Tab") {3538      e.preventDefault();3539      dismiss(true);3540      return;3541    }3542    if (current.length === 0) return;3543    if (e.key === "Enter") {3544      e.preventDefault();3545      choose(current[Math.max(0, focusedIndex)]!);3546      return;3547    }3548    if (current.length === 1) return;3549    if (e.key === "ArrowDown") {3550      e.preventDefault();3551      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3552    } else if (e.key === "ArrowUp") {3553      e.preventDefault();3554      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3555    }3556  }35573558  let exitScheduled = false;3559  function dismiss(userAction = false) {3560    if (exitScheduled) return;3561    exitScheduled = true;3562    stopObserving();3563    document.removeEventListener("click", outsideClick, { capture: true });3564    document.removeEventListener("keydown", handleKeyDown);3565    if (userAction) options.onDismiss?.();3566    container.classList.add("is-exiting");3567    setTimeout(() => host.remove(), 130);3568  }35693570  function outsideClick(ev: MouseEvent) {3571    const path = ev.composedPath();3572    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3573  }35743575  document.addEventListener("keydown", handleKeyDown);3576  document.body.appendChild(host);3577  render();3578  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);35793580  return dismiss;3581}35823583export interface CardSelectorEntry {3584  id: string;3585  title: string;3586  cardholderName?: string;3587  last4?: string;3588  expMonth?: string;3589  expYear?: string;3590  network?: import("../shared/types").CardNetwork;3591}35923593interface CardSelectorOptions {3594  domain?: string;3595  /** Caller-provided fill — receives the full CardEntry payload from the SW. */3596  onFill: (entry: import("../shared/types").VaultEntry) => void;3597  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3598  onDismiss?: () => void;3599}36003601/**3602 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3603 * passkey create or get. Renders as a fixed-position floating popup (no3604 * field anchor needed — passkeys don't require a focused input). Uses the3605 * same theme tokens and entrance animation as all other inline popup states.3606 */3607export function showPasskeyProGate(): void {3608  const domain = location.hostname.replace(/^www\./, "");36093610  const host = document.createElement("div");3611  host.setAttribute("data-peach-passkey-gate", "1");3612  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3613  const shadow = host.attachShadow({ mode: "closed" });36143615  const style = document.createElement("style");3616  style.textContent = `3617    :host { all: initial; }3618    .gate-wrap {3619      position: fixed;3620      top: 50%;3621      left: 50%;3622      transform: translate(-50%, -50%);3623      width: 280px;3624      pointer-events: auto;3625      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3626    }3627    @keyframes g-in {3628      from { opacity:0; transform: translate(-50%,-52%); }3629      to   { opacity:1; transform: translate(-50%,-50%); }3630    }3631    .gate-wrap.is-exiting {3632      animation: g-out 130ms ease-in forwards;3633    }3634    @keyframes g-out {3635      to { opacity:0; transform: translate(-50%,-52%); }3636    }3637    .gate {3638      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3639      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3640      border-radius: 12px;3641      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3642      padding: 16px;3643      font-family: Inter, sans-serif;3644    }3645    .gate-header {3646      display: flex;3647      align-items: center;3648      gap: 7px;3649      margin-bottom: 12px;3650      padding-bottom: 10px;3651      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3652    }3653    .gate-domain {3654      font-size: 12px;3655      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3656      font-family: "IBM Plex Mono", monospace;3657      overflow: hidden;3658      text-overflow: ellipsis;3659      white-space: nowrap;3660    }3661    .gate-title {3662      font-size: 14px;3663      font-weight: 500;3664      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3665      margin-bottom: 6px;3666    }3667    .gate-subtitle {3668      font-size: 12px;3669      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3670      line-height: 1.5;3671      margin-bottom: 14px;3672    }3673    .gate-btn {3674      display: block;3675      width: 100%;3676      padding: 9px 0;3677      border-radius: 8px;3678      border: none;3679      cursor: pointer;3680      font-size: 13px;3681      font-family: Inter, sans-serif;3682      font-weight: 500;3683      transition: opacity 100ms;3684      margin-bottom: 7px;3685      text-align: center;3686    }3687    .gate-btn:last-child { margin-bottom: 0; }3688    .gate-btn--accent {3689      background: ${accentHex};3690      color: #fff;3691    }3692    .gate-btn--accent:hover { opacity: 0.88; }3693    .gate-btn--ghost {3694      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3695      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3696    }3697    .gate-btn--ghost:hover { opacity: 0.75; }3698    .backdrop {3699      position: fixed;3700      inset: 0;3701      pointer-events: auto;3702    }3703  `;3704  shadow.appendChild(style);37053706  const backdrop = document.createElement("div");3707  backdrop.className = "backdrop";3708  shadow.appendChild(backdrop);37093710  const wrap = document.createElement("div");3711  wrap.className = "gate-wrap";3712  shadow.appendChild(wrap);37133714  const gate = document.createElement("div");3715  gate.className = "gate";3716  wrap.appendChild(gate);37173718  // Header: peach icon + domain3719  const header = document.createElement("div");3720  header.className = "gate-header";3721  const icon = document.createElement("span");3722  icon.innerHTML = peachIconSvg();3723  const domainEl = document.createElement("span");3724  domainEl.className = "gate-domain";3725  domainEl.textContent = domain;3726  header.append(icon, domainEl);3727  gate.appendChild(header);37283729  const title = document.createElement("div");3730  title.className = "gate-title";3731  title.textContent = "Passkeys are part of Peach Pro.";3732  gate.appendChild(title);37333734  const subtitle = document.createElement("div");3735  subtitle.className = "gate-subtitle";3736  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3737  gate.appendChild(subtitle);37383739  const upgradeBtn = document.createElement("button");3740  upgradeBtn.className = "gate-btn gate-btn--accent";3741  upgradeBtn.type = "button";3742  upgradeBtn.textContent = "Upgrade to Pro";3743  gate.appendChild(upgradeBtn);37443745  const laterBtn = document.createElement("button");3746  laterBtn.className = "gate-btn gate-btn--ghost";3747  laterBtn.type = "button";3748  laterBtn.textContent = "Not right now";3749  gate.appendChild(laterBtn);37503751  function dismiss() {3752    wrap.classList.add("is-exiting");3753    setTimeout(() => host.remove(), 130);3754  }37553756  upgradeBtn.addEventListener("click", () => {3757    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3758    dismiss();3759  });3760  laterBtn.addEventListener("click", dismiss);3761  backdrop.addEventListener("click", dismiss);37623763  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3764    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3765  });37663767  document.body.appendChild(host);3768}37693770/**3771 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3772 * detector sees the page invoke navigator.credentials.create(); content/index.ts3773 * checks vault + decline state then calls this. "Save passkey to Peach"3774 * initiates the popup-context credential flow; "Not now" records a 30-day3775 * decline for the domain so we don't re-show on every page reload.3776 */3777export function showPasskeyRegistrationOffer(args: {3778  rpId: string;3779  rpName?: string;3780  userName?: string;3781  userDisplayName?: string;3782}): void {3783  const domain = location.hostname.replace(/^www\./, "");3784  const displayName = args.rpName || domain;37853786  const host = document.createElement("div");3787  host.setAttribute("data-peach-passkey-offer", "1");3788  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3789  const shadow = host.attachShadow({ mode: "closed" });37903791  const style = document.createElement("style");3792  style.textContent = `3793    :host { all: initial; }3794    .offer-wrap {3795      position: fixed;3796      top: 16px;3797      right: 16px;3798      width: 320px;3799      pointer-events: auto;3800      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3801    }3802    @keyframes o-in {3803      from { opacity: 0; transform: translateY(-6px); }3804      to   { opacity: 1; transform: translateY(0); }3805    }3806    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3807    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3808    .offer {3809      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3810      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3811      border-radius: 12px;3812      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3813      padding: 14px 14px 12px;3814      font-family: Inter, sans-serif;3815      position: relative;3816    }3817    .offer-close {3818      position: absolute;3819      top: 8px;3820      right: 8px;3821      width: 18px;3822      height: 18px;3823      border: none;3824      background: transparent;3825      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3826      cursor: pointer;3827      font-size: 14px;3828      line-height: 1;3829      padding: 0;3830    }3831    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3832    .offer-header {3833      display: flex;3834      align-items: center;3835      gap: 7px;3836      margin-bottom: 8px;3837      padding-bottom: 8px;3838      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3839    }3840    .offer-domain {3841      font-size: 12px;3842      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3843      font-family: "IBM Plex Mono", monospace;3844      overflow: hidden;3845      text-overflow: ellipsis;3846      white-space: nowrap;3847    }3848    .offer-title {3849      font-size: 13px;3850      font-weight: 500;3851      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3852      margin-bottom: 4px;3853    }3854    .offer-subtitle {3855      font-size: 11px;3856      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3857      line-height: 1.45;3858      margin-bottom: 12px;3859    }3860    .offer-btn {3861      display: block;3862      width: 100%;3863      padding: 8px 0;3864      border-radius: 7px;3865      border: none;3866      cursor: pointer;3867      font-size: 12px;3868      font-family: Inter, sans-serif;3869      font-weight: 500;3870      transition: opacity 100ms;3871      margin-bottom: 6px;3872      text-align: center;3873    }3874    .offer-btn:last-child { margin-bottom: 0; }3875    .offer-btn--accent { background: ${accentHex}; color: #fff; }3876    .offer-btn--accent:hover { opacity: 0.88; }3877    .offer-btn--ghost {3878      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3879      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3880    }3881    .offer-btn--ghost:hover { opacity: 0.75; }3882  `;3883  shadow.appendChild(style);38843885  const wrap = document.createElement("div");3886  wrap.className = "offer-wrap";3887  shadow.appendChild(wrap);38883889  const offer = document.createElement("div");3890  offer.className = "offer";3891  wrap.appendChild(offer);38923893  const closeBtn = document.createElement("button");3894  closeBtn.className = "offer-close";3895  closeBtn.type = "button";3896  closeBtn.setAttribute("aria-label", "Dismiss");3897  closeBtn.textContent = "✕";3898  offer.appendChild(closeBtn);38993900  const header = document.createElement("div");3901  header.className = "offer-header";3902  const icon = document.createElement("span");3903  icon.innerHTML = peachIconSvg();3904  const domainEl = document.createElement("span");3905  domainEl.className = "offer-domain";3906  domainEl.textContent = domain;3907  header.append(icon, domainEl);3908  offer.appendChild(header);39093910  const title = document.createElement("div");3911  title.className = "offer-title";3912  title.textContent = "This site supports passkeys.";3913  offer.appendChild(title);39143915  const subtitle = document.createElement("div");3916  subtitle.className = "offer-subtitle";3917  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3918  offer.appendChild(subtitle);39193920  const saveBtn = document.createElement("button");3921  saveBtn.className = "offer-btn offer-btn--accent";3922  saveBtn.type = "button";3923  saveBtn.textContent = "Save passkey to Peach";3924  offer.appendChild(saveBtn);39253926  const laterBtn = document.createElement("button");3927  laterBtn.className = "offer-btn offer-btn--ghost";3928  laterBtn.type = "button";3929  laterBtn.textContent = "Not now";3930  offer.appendChild(laterBtn);39313932  function dismiss(decline: boolean) {3933    if (decline) {3934      chrome.runtime.sendMessage({3935        type: "PASSKEY_OFFER_DECLINE",3936        payload: { domain },3937      }).catch(() => {});3938    }3939    wrap.classList.add("is-exiting");3940    setTimeout(() => host.remove(), 130);3941  }39423943  saveBtn.addEventListener("click", () => {3944    chrome.runtime.sendMessage({3945      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3946      payload: {3947        rpId: args.rpId,3948        rpName: args.rpName ?? displayName,3949        userName: args.userName ?? "user",3950        userDisplayName: args.userDisplayName,3951      },3952    }).catch(() => {});3953    dismiss(false);3954  });3955  laterBtn.addEventListener("click", () => dismiss(true));3956  closeBtn.addEventListener("click", () => dismiss(true));39573958  document.body.appendChild(host);3959}39603961/**3962 * State 11 — passkey available indicator. Shown when the user lands on a3963 * domain for which they already have a stored passkey. Tells them where to3964 * find it (the entry already shows in the vault list); the "Sign in with3965 * passkey" button opens the popup so they can use the platform authenticator3966 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3967 * the actual sign-in transparently, so this banner is informational only.3968 */3969export function showPasskeyAvailable(args: {3970  rpId: string;3971  userName: string;3972  fromBrowser?: "chrome" | "firefox";3973  currentBrowser?: "chrome" | "firefox" | "unknown";3974}): void {3975  const domain = location.hostname.replace(/^www\./, "");3976  const crossBrowser =3977    args.fromBrowser &&3978    args.currentBrowser &&3979    args.currentBrowser !== "unknown" &&3980    args.fromBrowser !== args.currentBrowser;39813982  const host = document.createElement("div");3983  host.setAttribute("data-peach-passkey-available", "1");3984  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3985  const shadow = host.attachShadow({ mode: "closed" });39863987  const style = document.createElement("style");3988  style.textContent = `3989    :host { all: initial; }3990    .avail-wrap {3991      position: fixed;3992      top: 16px;3993      right: 16px;3994      width: 320px;3995      pointer-events: auto;3996      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3997    }3998    @keyframes a-in {3999      from { opacity: 0; transform: translateY(-6px); }4000      to   { opacity: 1; transform: translateY(0); }4001    }4002    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }4003    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }4004    .avail {4005      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};4006      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};4007      border-radius: 12px;4008      box-shadow: 0 12px 48px rgba(0,0,0,0.55);4009      padding: 14px 14px 12px;4010      font-family: Inter, sans-serif;4011      position: relative;4012    }4013    .avail-close {4014      position: absolute;4015      top: 8px;4016      right: 8px;4017      width: 18px;4018      height: 18px;4019      border: none;4020      background: transparent;4021      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};4022      cursor: pointer;4023      font-size: 14px;4024      line-height: 1;4025      padding: 0;4026    }4027    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }4028    .avail-header {4029      display: flex;4030      align-items: center;4031      gap: 7px;4032      margin-bottom: 8px;4033      padding-bottom: 8px;4034      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};4035    }4036    .avail-domain {4037      font-size: 12px;4038      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};4039      font-family: "IBM Plex Mono", monospace;4040    }4041    .avail-label {4042      font-size: 9px;4043      letter-spacing: 0.16em;4044      text-transform: uppercase;4045      color: ${accentHex};4046      margin-bottom: 4px;4047    }4048    .avail-user {4049      font-size: 13px;4050      font-weight: 500;4051      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};4052      margin-bottom: 12px;4053      overflow: hidden;4054      text-overflow: ellipsis;4055      white-space: nowrap;4056    }4057    .avail-cross {4058      font-size: 11px;4059      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};4060      line-height: 1.45;4061      margin-bottom: 12px;4062      padding: 8px;4063      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};4064      border-radius: 6px;4065    }4066    .avail-btn {4067      display: block;4068      width: 100%;4069      padding: 8px 0;4070      border-radius: 7px;4071      border: none;4072      cursor: pointer;4073      font-size: 12px;4074      font-family: Inter, sans-serif;4075      font-weight: 500;4076      transition: opacity 100ms;4077      margin-bottom: 6px;4078      text-align: center;4079    }4080    .avail-btn:last-child { margin-bottom: 0; }4081    .avail-btn--accent { background: ${accentHex}; color: #fff; }4082    .avail-btn--accent:hover { opacity: 0.88; }4083    .avail-btn--ghost {4084      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};4085      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};4086    }4087    .avail-btn--ghost:hover { opacity: 0.75; }4088  `;4089  shadow.appendChild(style);40904091  const wrap = document.createElement("div");4092  wrap.className = "avail-wrap";4093  shadow.appendChild(wrap);40944095  const avail = document.createElement("div");4096  avail.className = "avail";4097  wrap.appendChild(avail);40984099  const closeBtn = document.createElement("button");4100  closeBtn.className = "avail-close";4101  closeBtn.type = "button";4102  closeBtn.setAttribute("aria-label", "Dismiss");4103  closeBtn.textContent = "✕";4104  avail.appendChild(closeBtn);41054106  const header = document.createElement("div");4107  header.className = "avail-header";4108  const icon = document.createElement("span");4109  icon.innerHTML = peachIconSvg();4110  const domainEl = document.createElement("span");4111  domainEl.className = "avail-domain";4112  domainEl.textContent = domain;4113  header.append(icon, domainEl);4114  avail.appendChild(header);41154116  const label = document.createElement("div");4117  label.className = "avail-label";4118  label.textContent = "PASSKEY";4119  avail.appendChild(label);41204121  const user = document.createElement("div");4122  user.className = "avail-user";4123  user.textContent = args.userName;4124  avail.appendChild(user);41254126  if (crossBrowser) {4127    const cross = document.createElement("div");4128    cross.className = "avail-cross";4129    cross.textContent =4130      args.fromBrowser === "chrome"4131        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."4132        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";4133    avail.appendChild(cross);4134  }41354136  const signInBtn = document.createElement("button");4137  signInBtn.className = "avail-btn avail-btn--accent";4138  signInBtn.type = "button";4139  signInBtn.textContent = "Sign in with passkey";4140  avail.appendChild(signInBtn);41414142  const passwordBtn = document.createElement("button");4143  passwordBtn.className = "avail-btn avail-btn--ghost";4144  passwordBtn.type = "button";4145  passwordBtn.textContent = "Use password instead";4146  avail.appendChild(passwordBtn);41474148  function dismiss() {4149    wrap.classList.add("is-exiting");4150    setTimeout(() => host.remove(), 130);4151  }41524153  signInBtn.addEventListener("click", () => {4154    // On Chrome: the user clicking the page's own Sign-in button is what4155    //   triggers webAuthenticationProxy → existing background flow handles it.4156    //   Our button just dismisses since the page itself drives auth.4157    // On Firefox: cross-browser passkeys can't be used, so we just dismiss4158    //   and surface the entry for manual reference (popup view).4159    dismiss();4160    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});4161  });4162  passwordBtn.addEventListener("click", dismiss);4163  closeBtn.addEventListener("click", dismiss);41644165  document.body.appendChild(host);4166}41674168/**4169 * State 7 — card silver platter. Single-card focused fill view rendered4170 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the4171 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes4172 * so card and login flows render identically. Multi-card list view is a4173 * follow-up; today this picks the first card.4174 */4175export function showCardSelector(4176  anchorEl: HTMLInputElement,4177  cards: CardSelectorEntry[],4178  options: CardSelectorOptions4179): () => void {4180  if (cards.length === 0) return () => {};4181  const card = cards[0]!;41824183  const host = document.createElement("div");4184  host.style.cssText = "position: absolute; z-index: 2147483647;";4185  host.style.setProperty("--peach-accent", accentHex);4186  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));4187  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));4188  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));4189  const shadow = host.attachShadow({ mode: "closed" });41904191  const style = shadow.appendChild(document.createElement("style"));4192  style.textContent = SELECTOR_STYLES;41934194  const rect = anchorEl.getBoundingClientRect();4195  host.style.top = `${rect.bottom + window.scrollY + 5}px`;4196  host.style.left = `${rect.left + window.scrollX}px`;4197  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;41984199  const container = shadow.appendChild(document.createElement("div"));4200  container.className = "peach-inline-popup";4201  container.setAttribute("data-theme", popupTheme);42024203  // Domain header — eyebrow communicates the card context, not the site4204  const domHdr = document.createElement("div");4205  domHdr.className = "domain-header";4206  const eyebrow = document.createElement("div");4207  eyebrow.className = "domain-eyebrow";4208  eyebrow.textContent = "Pay with Peach";4209  const domName = document.createElement("div");4210  domName.className = "domain-name";4211  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");4212  domHdr.append(eyebrow, domName);4213  container.appendChild(domHdr);42144215  const platter = document.createElement("div");4216  platter.className = "card-platter";42174218  if (card.network && card.network !== "unknown") {4219    const net = document.createElement("div");4220    net.className = "cp-network";4221    net.textContent = card.network;4222    platter.appendChild(net);4223  }42244225  const nick = document.createElement("div");4226  nick.className = "cp-nickname";4227  nick.textContent = card.title;4228  platter.appendChild(nick);42294230  if (card.last4) {4231    const l4 = document.createElement("div");4232    l4.className = "cp-last4";4233    l4.textContent = `•••• ${card.last4}`;4234    platter.appendChild(l4);4235  }42364237  const meta = document.createElement("div");4238  meta.className = "cp-meta";4239  if (card.cardholderName) {4240    const name = document.createElement("span");4241    name.textContent = card.cardholderName;4242    meta.appendChild(name);4243  }4244  if (card.expMonth && card.expYear) {4245    if (card.cardholderName) {4246      const sep = document.createElement("span");4247      sep.className = "cp-meta-sep";4248      sep.textContent = "·";4249      meta.appendChild(sep);4250    }4251    const exp = document.createElement("span");4252    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4253    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4254    meta.appendChild(exp);4255  }4256  if (meta.childElementCount > 0) platter.appendChild(meta);42574258  const fillWrap = document.createElement("div");4259  fillWrap.className = "cp-fill-wrap";4260  const fillBtn = document.createElement("button");4261  fillBtn.className = "sp-fill-btn";4262  fillBtn.type = "button";4263  fillBtn.textContent = "Fill card details";4264  fillBtn.addEventListener("click", async () => {4265    if (fillBtn.disabled) return;4266    fillBtn.disabled = true;4267    fillBtn.classList.add("filled");4268    fillBtn.innerHTML = checkSvgStr();4269    const resp = await chrome.runtime.sendMessage({4270      type: "GET_ENTRY_FOR_FILL",4271      // MV-1: explicit user click to fill this card's details.4272      payload: { id: card.id, explicitSummon: true },4273    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4274    if (resp?.ok && resp.data) options.onFill(resp.data);4275    setTimeout(() => dismiss(), 400);4276  });4277  fillWrap.appendChild(fillBtn);4278  platter.appendChild(fillWrap);42794280  // Secondary actions — copy number, copy CVC, dismiss4281  const actions = document.createElement("div");4282  actions.className = "sp-actions";42834284  function flashBtn(b: HTMLButtonElement) {4285    b.classList.add("flashed");4286    setTimeout(() => b.classList.remove("flashed"), 700);4287  }42884289  // M3/QUA-005: clipboard + background COPY both failed — show user.4290  function flashCopyError(b: HTMLButtonElement) {4291    const original = b.textContent ?? "";4292    b.textContent = "Blocked";4293    b.classList.add("flashed");4294    setTimeout(() => {4295      b.classList.remove("flashed");4296      if (b.isConnected) b.textContent = original;4297    }, 1200);4298  }42994300  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4301    const resp = await chrome.runtime.sendMessage({4302      type: "GET_ENTRY_FOR_FILL",4303      // MV-1: explicit user action on a card the user opened in Peach's UI.4304      payload: { id: card.id, explicitSummon: true },4305    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4306    return resp?.ok && resp.data ? resp.data : null;4307  }43084309  const copyNum = document.createElement("button");4310  copyNum.className = "sp-action-btn";4311  copyNum.type = "button";4312  copyNum.title = "Copy card number";4313  copyNum.textContent = "Copy number";4314  copyNum.addEventListener("click", async (e) => {4315    e.stopPropagation();4316    const full = await fetchFullCard();4317    if (!full?.cardNumber) return;4318    let alreadyWritten = false;4319    try {4320      await navigator.clipboard.writeText(full.cardNumber);4321      alreadyWritten = true;4322    } catch (err) {4323      console.warn("[Peach] clipboard write denied:", err);4324    }4325    const resp = await chrome.runtime.sendMessage({4326      type: "COPY",4327      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4328    }).catch(() => null) as { ok?: boolean } | null;4329    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4330    else flashCopyError(copyNum);4331  });4332  actions.appendChild(copyNum);43334334  const copyCvc = document.createElement("button");4335  copyCvc.className = "sp-action-btn";4336  copyCvc.type = "button";4337  copyCvc.title = "Copy CVC";4338  copyCvc.textContent = "Copy CVC";4339  copyCvc.addEventListener("click", async (e) => {4340    e.stopPropagation();4341    const full = await fetchFullCard();4342    if (!full?.cvc) return;4343    let alreadyWritten = false;4344    try {4345      await navigator.clipboard.writeText(full.cvc);4346      alreadyWritten = true;4347    } catch (err) {4348      console.warn("[Peach] clipboard write denied:", err);4349    }4350    const resp = await chrome.runtime.sendMessage({4351      type: "COPY",4352      payload: { text: full.cvc, label: "CVC", alreadyWritten },4353    }).catch(() => null) as { ok?: boolean } | null;4354    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4355    else flashCopyError(copyCvc);4356  });4357  actions.appendChild(copyCvc);43584359  const closeBtn = document.createElement("button");4360  closeBtn.className = "sp-action-btn";4361  closeBtn.type = "button";4362  closeBtn.title = "Dismiss";4363  closeBtn.textContent = "✕";4364  closeBtn.addEventListener("click", (e) => {4365    e.stopPropagation();4366    dismiss(true);4367  });4368  actions.appendChild(closeBtn);43694370  platter.appendChild(actions);4371  container.appendChild(platter);43724373  document.body.appendChild(host);4374  function updatePosition() {4375    const r = anchorEl.getBoundingClientRect();4376    host.style.top = `${r.bottom + window.scrollY + 5}px`;4377    host.style.left = `${r.left + window.scrollX}px`;4378  }4379  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);43804381  function onKeyDown(e: KeyboardEvent) {4382    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4383  }4384  document.addEventListener("keydown", onKeyDown);43854386  let exitScheduled = false;4387  function dismiss(userAction = false) {4388    if (exitScheduled) return;4389    exitScheduled = true;4390    stopObserving();4391    document.removeEventListener("click", outsideClick, { capture: true });4392    document.removeEventListener("keydown", onKeyDown);4393    if (userAction) options.onDismiss?.();4394    container.classList.add("is-exiting");4395    setTimeout(() => host.remove(), 130);4396  }43974398  function outsideClick(ev: MouseEvent) {4399    const path = ev.composedPath();4400    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4401  }4402  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);44034404  return dismiss;4405}