inject.ts

176.8 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { detectHomograph, getSecurityOriginDisplay } from "../shared/domain";14import {15  DEFAULT_PASSPHRASE_WORDS,16  generatePassphrase,17  generatePassword,18  MAX_PASSPHRASE_WORDS,19  MIN_PASSPHRASE_WORDS,20  type PassphraseSeparator,21} from "../shared/generate";22import { detectPasswordPolicy } from "./policy";23import {24  filterSavedIdentities,25  identityFilterLabel,26  resolveCustomIdentityKind,27  type IdentityFilterMode,28  type IdentityKind,29} from "./identity-helper";3031function showEntryAccessError(): void {32  const error = document.createElement("div");33  error.setAttribute("role", "alert");34  error.textContent = "Could not access this entry. Open Peach to check it.";35  error.style.cssText = "position:fixed;bottom:20px;left:20px;z-index:2147483647;background:#131109;color:#F0E8D8;padding:12px;font:12px monospace;";36  document.body.appendChild(error);37  setTimeout(() => error.remove(), 4000);38}3940let accentHex = "#E8956D";41let popupTheme: "dark" | "light" = "dark";42chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {43  const data = resp?.data;44  const name = data?.accentColor ?? "peach";45  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";46  popupTheme = data?.theme === "light" ? "light" : "dark";47});4849// 8-digit hex alpha helpers for the accent-derived shadow tokens.50// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing51// two hex digits as the alpha channel.52function withAlpha(hex: string, alpha: string): string {53  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS54  // always exposes 6-digit hex, so this is a guard against future changes55  // shipping shorthand colors that would silently break the var injection.56  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;57}5859export interface SelectorEntry {60  id: string;61  title: string;62  username?: string;63  email?: string;64  url?: string;65  hasTotp?: boolean;66  /** True when the entry also has a passkey credential attached. */67  hasPasskey?: boolean;68}6970interface SelectorOptions {71  domain?: string;72  /** Full browser origin shown for security decisions; never used for matching. */73  securityOrigin?: string;74  /** Browser-issued one-shot authorization for a user-summoned cross-origin selection. */75  capability?: string;76  searchableEntries?: SelectorEntry[];77  /**78   * MV-2: lazy loader for the vault-wide searchable list. Invoked only on an79   * explicit user search gesture, never on passive popup open, so the full80   * account inventory never ships into the page world unless the user asks.81   * Result is cached for the popup's lifetime.82   */83  loadSearchableEntries?: () => Promise<SelectorEntry[]>;84  /** True when shown on a signup form — changes header label and entry-click behaviour */85  isSignup?: boolean;86  /**87   * Identity kind the current signup field is expecting. Used to avoid88   * assuming email when the user is actually filling a username.89   */90  identityKind?: IdentityKind;91  /**92   * Derived identity list (emails then usernames) for signup mode (State 10).93   * When present, renderIdentityHelper() is used instead of renderList().94   */95  savedIdentities?: SavedIdentity[];96  /**97   * Called after the user picks a saved identity (signup mode only) or98   * after successfully saving a new entry on a signup form.99   * Lets the caller fill the visible username + password fields.100   */101  onFillFields?: (username: string, password: string, email?: string) => void;102  /**103   * True when the form has both a distinct username field AND a distinct email104   * field (e.g. Name / Username / Email / Password signup forms). Enables the105   * two-step identity wizard: first pick the field type the user clicked on,106   * then pick the other, then generate a password.107   */108  hasEmailField?: boolean;109  /**110   * When true, show an inline unlock form instead of the entries list.111   * Used when the vault is locked so the user can unlock without opening112   * the popup.113   */114  locked?: boolean;115  /**116   * Called after a successful inline unlock — the caller should re-query117   * entries and re-open the selector with real data.118   */119  onUnlocked?: () => void;120  /**121   * Called when the user explicitly dismisses the selector (Escape, Tab, or122   * click outside) — NOT when an entry is selected or on auto-close.123   * Used by the caller to suppress spurious reopens on the same field.124   */125  onDismiss?: () => void;126}127128function getDomainFromUrl(url: string): string {129  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }130}131132function keySvgStr(): string {133  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>`;134}135136function plusSvgStr(): string {137  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>`;138}139140function searchSvgStr(): string {141  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>`;142}143144function backSvgStr(): string {145  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>`;146}147148function peachIconSvg(): string {149  // Peach body stays brand-peach regardless of `accentHex` — a sage or150  // sky accent must not turn the autofill icon green or blue. Accent151  // color still tints surrounding glow/hover halos below.152  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>`;153}154155function checkSvgStr(): string {156  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>`;157}158159function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {160  const { hostname, origin } = location;161  const parts = hostname.split(".");162  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",163    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",164    "oidc", "federation", "saml", "cas", "ldap"];165  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());166  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;167  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);168  return { origin, title, loginSubdomain };169}170171/**172 * Shows a bottom-of-page toast after filling credentials when the entry has173 * never matched the current site — offering to add the current origin to the174 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.175 */176export function showRememberSiteToast(177  pageOrigin: string,178  entryId: string,179): void {180  const host = document.createElement("div");181  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";182  host.style.setProperty("--peach-accent", accentHex);183  const shadow = host.attachShadow({ mode: "closed" });184185  const style = document.createElement("style");186  style.textContent = `187    .bar {188      display:flex;align-items:center;gap:10px;padding:10px 14px;189      background:#131109;border:1px solid rgba(240,232,216,0.09);190      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);191      font-family:Inter,sans-serif;white-space:nowrap;192      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;193    }194    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }195    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }196    .yes {197      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;198      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;199    }200    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }201    .no {202      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;203      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;204    }205  `;206  shadow.appendChild(style);207208  const bar = document.createElement("div"); bar.className = "bar";209  const txt = document.createElement("span"); txt.className = "txt";210  const origin = getSecurityOriginDisplay(pageOrigin);211  const warning = detectHomograph(origin) ? "⚠ Look-alike domain: " : "";212  txt.textContent = `${warning}Remember ${origin} for this entry?`;213  const yesBtn = document.createElement("button"); yesBtn.className = "yes";214  yesBtn.textContent = "Remember";215  yesBtn.addEventListener("click", async () => {216    // The write itself is popup-confirmed: growing an entry's domain set is217    // the one autofill decision a page must not make for itself, because the218    // domain set is what gates future fills (PB-26-106).219    await chrome.runtime.sendMessage({220      type: "REQUEST_REMEMBER_SITE",221      payload: { id: entryId, url: location.origin },222    });223    host.remove();224  });225  const noBtn = document.createElement("button"); noBtn.className = "no";226  noBtn.textContent = "Not now";227  noBtn.addEventListener("click", () => host.remove());228  bar.append(txt, yesBtn, noBtn);229  shadow.appendChild(bar);230  document.body.appendChild(host);231  setTimeout(() => host.remove(), 9000);232}233234// Module handle so a second auto-copy resets the dismiss timer rather than235// letting the first toast's teardown race the replacement.236let totpToastDismissTimer: ReturnType<typeof setTimeout> | null = null;237238/**239 * Shows a brief top-right toast when Peach automatically copies a TOTP code,240 * telling the user how long until the clipboard self-clears. Auto-dismisses241 * after 3s; a second call while visible replaces the toast and resets the timer.242 * Rendered in the light DOM (not a closed shadow) so the copy is announced to243 * assistive tech via aria-live — the code itself is never placed in the DOM.244 */245export function showTotpCopyToast(secondsUntilClear: number): void {246  document.getElementById("peach-totp-toast")?.remove();247  if (totpToastDismissTimer) {248    clearTimeout(totpToastDismissTimer);249    totpToastDismissTimer = null;250  }251252  const toast = document.createElement("div");253  toast.id = "peach-totp-toast";254  toast.className = "peach-totp-toast";255  toast.setAttribute("data-peach-toast", "totp-copy");256  toast.setAttribute("aria-live", "polite");257258  // Inline styles — matches the passkey toast family (warm, minimal, top right).259  Object.assign(toast.style, {260    position: "fixed",261    top: "16px",262    right: "16px",263    zIndex: "2147483647",264    padding: "10px 14px",265    borderRadius: "8px",266    background: "rgba(30, 20, 10, 0.92)",267    border: "1px solid rgba(210, 140, 60, 0.3)",268    color: "#e8d5b0",269    fontFamily: '"IBM Plex Mono", monospace',270    fontSize: "11px",271    lineHeight: "1.5",272    boxShadow: "0 4px 24px rgba(0,0,0,0.4)",273    pointerEvents: "none",274  });275276  // secondsUntilClear is a typed number — safe to interpolate; no page-derived277  // string ever reaches this markup.278  toast.innerHTML = `279    <div style="font-style: italic; font-family: 'Cormorant Garamond', serif; font-size: 13px; margin-bottom: 2px;">280      2FA code copied281    </div>282    <div style="opacity: 0.6; font-size: 10px;">283      clears in ${secondsUntilClear}s284    </div>285  `;286287  document.body.appendChild(toast);288289  totpToastDismissTimer = setTimeout(() => {290    totpToastDismissTimer = null;291    toast.style.transition = "opacity 0.3s ease";292    toast.style.opacity = "0";293    setTimeout(() => toast.remove(), 300);294  }, 3000);295}296297interface SmartGenerator {298  root: HTMLElement;299  getPassword: () => string;300  /** Copy the current password to the clipboard with the standard pulse UX. */301  copy: () => Promise<void>;302}303304interface SmartGeneratorOptions {305  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */306  policy: PasswordPolicy;307  /**308   * Seed value: used as the displayed password without regenerating, e.g. the309   * password the user already typed into the page. The generator still310   * regenerates the moment any control changes.311   */312  initialPassword?: string;313  /** Fires every time the password regenerates (initial + on changes). */314  onChange?: (pw: string) => void;315}316317/**318 * Build the inline-popup smart-password generator. Mirrors the main popup's319 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset320 * pills + a policy hint that names the constraints Peach detected on the321 * page. Writing this in pure DOM rather than reusing the Solid component322 * keeps the content-script bundle small.323 */324export function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {325  const policy = opts.policy ?? {};326  let mode: "password" | "passphrase" = "password";327  let wordCount = DEFAULT_PASSPHRASE_WORDS;328  let separator: PassphraseSeparator = "-";329330  // Start at site max (strongest password the site accepts), fall back to 64331  let length = policy.maxLength ?? 64;332  if (policy.minLength) length = Math.max(length, policy.minLength);333  if (length < 8) length = 8;334  if (length > 256) length = 256;335336  let upper = true;337  let lower = true;338  let numbers = true;339  let symbols = !policy.forbidsSymbols;340  if (policy.requiresSymbols) symbols = true;341  const forbiddenChars = policy.forbiddenChars ?? "";342343  let password = "";344345  const root = document.createElement("div");346  root.className = "pwgen-block";347348  const modePills = root.appendChild(document.createElement("div"));349  modePills.className = "pwgen-pills";350  modePills.setAttribute("aria-label", "Generator type");351  const passwordModeBtn = modePills.appendChild(document.createElement("button"));352  passwordModeBtn.type = "button";353  passwordModeBtn.className = "pwgen-pill is-on";354  passwordModeBtn.textContent = "password";355  passwordModeBtn.setAttribute("aria-pressed", "true");356  const passphraseModeBtn = modePills.appendChild(document.createElement("button"));357  passphraseModeBtn.type = "button";358  passphraseModeBtn.className = "pwgen-pill";359  passphraseModeBtn.textContent = "passphrase";360  passphraseModeBtn.setAttribute("aria-pressed", "false");361362  const displayRow = root.appendChild(document.createElement("div"));363  displayRow.className = "pwgen-display-row";364  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;365  output.type = "text";366  output.className = "pwgen-output";367  output.setAttribute("autocomplete", "off");368  output.setAttribute("spellcheck", "false");369  output.setAttribute("autocorrect", "off");370  output.setAttribute("autocapitalize", "off");371372  const regenBtn = displayRow.appendChild(document.createElement("button"));373  regenBtn.className = "pwgen-icon-btn";374  regenBtn.type = "button";375  regenBtn.setAttribute("aria-label", "Regenerate password");376  regenBtn.title = "Regenerate";377  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>`;378379  const copyBtn = displayRow.appendChild(document.createElement("button"));380  copyBtn.className = "pwgen-icon-btn";381  copyBtn.type = "button";382  copyBtn.setAttribute("aria-label", "Copy password");383  copyBtn.title = "Copy";384  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>`;385386  const controls = root.appendChild(document.createElement("div"));387  controls.className = "pwgen-controls-row";388  const slider = controls.appendChild(document.createElement("input"));389  slider.type = "range";390  slider.className = "pwgen-slider";391  slider.min = "8";392  slider.max = "256";393  slider.value = String(length);394  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));395  if (policy.maxLength) slider.max = String(Math.min(256, policy.maxLength));396  slider.setAttribute("aria-label", "Password length");397  const amountLabel = controls.appendChild(document.createElement("span"));398  amountLabel.className = "pwgen-amount-label";399  amountLabel.textContent = "characters";400  const lenNum = controls.appendChild(document.createElement("span"));401  lenNum.className = "pwgen-len-num pwgen-len-num--edit";402  lenNum.textContent = String(length);403  lenNum.addEventListener("click", () => {404    const li = document.createElement("input");405    li.type = "text"; li.inputMode = "numeric";406    li.className = "pwgen-len-input"; li.value = String(length);407    lenNum.replaceWith(li);408    requestAnimationFrame(() => li.select());409    function commitLenEdit() {410      const n = parseInt(li.value, 10);411      if (!Number.isNaN(n)) {412        const clamped = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));413        if (mode === "passphrase") wordCount = clamped;414        else length = clamped;415        slider.value = String(mode === "passphrase" ? wordCount : length);416        regenerate();417      }418      lenNum.textContent = String(mode === "passphrase" ? wordCount : length);419      li.replaceWith(lenNum);420    }421    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });422    li.addEventListener("blur", commitLenEdit);423  });424425  const pills = root.appendChild(document.createElement("div"));426  pills.className = "pwgen-pills";427428  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {429    const b = document.createElement("button");430    b.type = "button";431    b.className = `pwgen-pill ${on ? "is-on" : ""}`;432    b.textContent = label;433    b.addEventListener("click", () => {434      const next = !b.classList.contains("is-on");435      b.classList.toggle("is-on", next);436      onToggle(next);437    });438    return b;439  }440  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));441  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));442  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));443  pills.appendChild(makePill("!@#", symbols, (next) => {444    // The site forbids symbols — UI lets the user override but still warn.445    symbols = next;446    regenerate();447  }));448449  const separatorPills = root.appendChild(document.createElement("div"));450  separatorPills.className = "pwgen-pills";451  separatorPills.hidden = true;452  for (const value of ["-", " ", ".", "_"] as PassphraseSeparator[]) {453    const button = separatorPills.appendChild(document.createElement("button"));454    button.type = "button";455    button.className = `pwgen-pill ${value === separator ? "is-on" : ""}`;456    button.textContent = value === " " ? "space" : value;457    button.setAttribute("aria-label", value === " " ? "Space separator" : `${value} separator`);458    button.setAttribute("aria-pressed", String(value === separator));459    button.addEventListener("click", () => {460      separator = value;461      for (const sibling of separatorPills.querySelectorAll("button")) {462        const selected = sibling === button;463        sibling.classList.toggle("is-on", selected);464        sibling.setAttribute("aria-pressed", String(selected));465      }466      regenerate();467    });468  }469470  // Policy hint — surfaces what Peach read off the site so the user knows the471  // generator is already tuned to it. Only shows when something interesting472  // was detected.473  const hintParts: string[] = [];474  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);475  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);476  if (policy.requiresSymbols) hintParts.push("requires symbols");477  if (policy.forbidsSymbols) hintParts.push("no symbols");478  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);479  let policyHint: HTMLDivElement | null = null;480  if (hintParts.length > 0) {481    const hint = root.appendChild(document.createElement("div"));482    policyHint = hint;483    hint.className = "pwgen-policy-hint";484    const accent = document.createElement("span");485    accent.className = "pwgen-hint-accent";486    accent.textContent = "site rules · ";487    const text = document.createTextNode(hintParts.join(" · "));488    hint.appendChild(accent);489    hint.appendChild(text);490  }491492  function regenerate() {493    // Falls back gracefully when the user toggles every charset off — the494    // shared generator forces lowercase in that case rather than throwing.495    password = mode === "passphrase"496      ? generatePassphrase({ wordCount, separator })497      : generatePassword({498          length,499          includeUppercase: upper,500          includeLowercase: lower,501          includeNumbers: numbers,502          includeSymbols: symbols,503          forbiddenChars,504        });505    output.value = password;506    opts.onChange?.(password);507  }508509  output.addEventListener("input", () => {510    password = output.value;511    if (mode === "password") {512      length = password.length;513      slider.value = String(Math.max(8, Math.min(256, length)));514      lenNum.textContent = String(length);515    }516    opts.onChange?.(password);517  });518519  slider.addEventListener("input", () => {520    if (mode === "passphrase") wordCount = parseInt(slider.value, 10);521    else length = parseInt(slider.value, 10);522    lenNum.textContent = String(mode === "passphrase" ? wordCount : length);523    regenerate();524  });525  regenBtn.addEventListener("click", regenerate);526527  function selectMode(nextMode: "password" | "passphrase") {528    mode = nextMode;529    const isPassphrase = mode === "passphrase";530    passwordModeBtn.classList.toggle("is-on", !isPassphrase);531    passwordModeBtn.setAttribute("aria-pressed", String(!isPassphrase));532    passphraseModeBtn.classList.toggle("is-on", isPassphrase);533    passphraseModeBtn.setAttribute("aria-pressed", String(isPassphrase));534    pills.hidden = isPassphrase;535    separatorPills.hidden = !isPassphrase;536    if (policyHint) policyHint.hidden = isPassphrase;537    slider.min = String(isPassphrase ? MIN_PASSPHRASE_WORDS : Math.max(8, policy.minLength ?? 8));538    slider.max = String(isPassphrase ? MAX_PASSPHRASE_WORDS : Math.min(256, policy.maxLength ?? 256));539    slider.value = String(isPassphrase ? wordCount : length);540    slider.setAttribute("aria-label", isPassphrase ? "Word count" : "Password length");541    amountLabel.textContent = isPassphrase ? "words" : "characters";542    lenNum.textContent = String(isPassphrase ? wordCount : length);543    regenerate();544  }545  passwordModeBtn.addEventListener("click", () => selectMode("password"));546  passphraseModeBtn.addEventListener("click", () => selectMode("passphrase"));547548  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;549  async function copy(): Promise<void> {550    try {551      await navigator.clipboard.writeText(password);552      copyBtn.classList.add("is-copied");553      if (copyResetTimer) clearTimeout(copyResetTimer);554      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);555    } catch {556      // Clipboard API may be denied — silently no-op; user still has regen UI.557    }558  }559  copyBtn.addEventListener("click", () => { void copy(); });560561  if (opts.initialPassword) {562    password = opts.initialPassword;563    output.value = password;564    opts.onChange?.(password);565  } else {566    regenerate();567  }568569  return {570    root,571    getPassword: () => password,572    copy,573  };574}575576export function observeAnchorPosition(577  anchorEl: HTMLElement,578  onUpdate: () => void579): () => void {580  let rafId = 0;581  let burstUntil = 0;582583  const runUpdate = () => {584    rafId = 0;585    onUpdate();586    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);587  };588  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };589  const scheduleBurst = (ms = 220) => {590    burstUntil = Math.max(burstUntil, performance.now() + ms);591    scheduleUpdate();592  };593594  const resizeObserver = new ResizeObserver(() => scheduleBurst());595  resizeObserver.observe(anchorEl);596  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);597598  const mutationObserver = new MutationObserver(() => scheduleBurst());599  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });600  if (anchorEl.parentElement) {601    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });602  }603604  const onScroll = () => scheduleUpdate();605  window.addEventListener("scroll", onScroll, true);606  window.addEventListener("resize", onScroll);607  window.visualViewport?.addEventListener("resize", onScroll);608  window.visualViewport?.addEventListener("scroll", onScroll);609  anchorEl.addEventListener("focus", () => scheduleBurst());610  anchorEl.addEventListener("input", () => scheduleBurst());611612  scheduleBurst(260);613614  return () => {615    if (rafId) cancelAnimationFrame(rafId);616    resizeObserver.disconnect();617    mutationObserver.disconnect();618    window.removeEventListener("scroll", onScroll, true);619    window.removeEventListener("resize", onScroll);620    window.visualViewport?.removeEventListener("resize", onScroll);621    window.visualViewport?.removeEventListener("scroll", onScroll);622  };623}624625export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {626  const button = document.createElement("button");627  button.type = "button";628  button.setAttribute("aria-label", "Peach autofill");629  button.title = "Fill with Peach";630  button.innerHTML = peachIconSvg();631  // position: fixed is load-bearing — not absolute. Absolute positioning632  // inherits the nearest positioned ancestor's box, which on sites with633  // overflow:hidden or sticky parents clips or offsets the icon. Fixed634  // anchors to the viewport and escapes all parent layout.635  button.style.cssText = `636    position: fixed; z-index: 2147483646;637    width: 26px; height: 26px; cursor: pointer;638    pointer-events: auto; border: none; padding: 3px;639    display: inline-flex; align-items: center; justify-content: center;640    background: transparent; border-radius: 999px;641    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;642    opacity: 0;643  `;644  button.addEventListener("mouseenter", () => {645    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;646    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;647    button.style.transform = "scale(1.08)";648  });649  button.addEventListener("mouseleave", () => {650    button.style.background = "transparent";651    button.style.boxShadow = "none";652    button.style.transform = "none";653  });654  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });655  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });656657  document.body.appendChild(button);658659  function updatePosition() {660    const rect = field.getBoundingClientRect();661    if (rect.width === 0 || rect.height === 0) {662      button.style.opacity = "0"; button.style.pointerEvents = "none";663      return;664    }665    const sz = 26;666    const inset = Math.max(5, Math.min(10, rect.height * 0.22));667    const top = rect.top + rect.height / 2 - sz / 2;668    // Clamp left so the icon stays fully inside the field's right edge, never669    // spilling onto an adjacent sibling button.670    const minLeft = rect.left + 4;671    const left = Math.max(minLeft, rect.right - sz - inset);672    // Hide if the field is too narrow to fit the icon cleanly (< 40px)673    if (rect.width < 40) {674      button.style.opacity = "0"; button.style.pointerEvents = "none";675      return;676    }677    button.style.top = `${top}px`;678    button.style.left = `${left}px`;679    button.style.opacity = "1"; button.style.pointerEvents = "auto";680  }681  updatePosition();682  requestAnimationFrame(() => { button.style.opacity = "1"; });683  const stopObserving = observeAnchorPosition(field, updatePosition);684  return () => { stopObserving(); button.remove(); };685}686687// All theme-dependent values resolve through tokens scoped to688// .peach-inline-popup[data-theme="dark|light"]. Accent variables689// (--peach-accent, --peach-glow, --peach-border-accent)690// are identical in both themes — only surface tokens differ. See691// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the692// theme switch — only literal brand-peach in peachIconSvg may stay raw.693const SELECTOR_STYLES = `694  :host { all: initial; }695  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }696697  .peach-inline-popup[data-theme="dark"] {698    --peach-bg:           #1a1410;699    --peach-bg-card:      #221c16;700    --peach-text:         #f5f0ea;701    --peach-text-dim:     #8a7a6a;702    --peach-text-muted:   #4a3a2a;703    --peach-border:       rgba(255,255,255,0.07);704    --peach-input-bg:     rgba(255,255,255,0.05);705    --peach-input-border: rgba(255,255,255,0.08);706  }707  .peach-inline-popup[data-theme="light"] {708    --peach-bg:           #fdf8f4;709    --peach-bg-card:      #f5ede4;710    --peach-text:         #1c1310;711    --peach-text-dim:     #6b5a4a;712    --peach-text-muted:   #a89080;713    --peach-border:       rgba(0,0,0,0.08);714    --peach-input-bg:     rgba(0,0,0,0.04);715    --peach-input-border: rgba(0,0,0,0.10);716  }717718  .peach-inline-popup {719    background: var(--peach-bg);720    border: 1px solid var(--peach-border-accent, var(--peach-border));721    border-radius: 14px;722    overflow: hidden;723    box-shadow:724      0 8px 40px var(--peach-glow, transparent),725      0 2px 12px rgba(0,0,0,0.5);726    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;727    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;728    transition: height 220ms cubic-bezier(0.16,1,0.3,1);729  }730  /* Light theme: shadow against a light page is too strong otherwise — drop both731     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */732  .peach-inline-popup[data-theme="light"] {733    box-shadow:734      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),735      0 2px 12px rgba(0,0,0,0.12);736  }737  .peach-inline-popup.is-exiting {738    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;739    pointer-events: none;740  }741742  @keyframes peach-enter {743    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }744    65%  { opacity: 1; filter: blur(0); }745    100% { opacity: 1; transform: translateY(0) scale(1); }746  }747  @keyframes peach-exit {748    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }749    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }750  }751  @keyframes peach-slide-in {752    from { opacity: 0; transform: translateX(12px); }753    to   { opacity: 1; transform: translateX(0); }754  }755  @keyframes peach-slide-back {756    from { opacity: 0; transform: translateX(-12px); }757    to   { opacity: 1; transform: translateX(0); }758  }759  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }760  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }761762  /* Domain header */763  .domain-header {764    padding: 9px 13px 7px;765    border-bottom: 1px solid var(--peach-border);766    display: flex; align-items: center; justify-content: space-between;767    gap: 8px;768  }769  .domain-header-text {770    display: flex; flex-direction: column; gap: 2px;771    min-width: 0; flex: 1;772  }773  .domain-eyebrow {774    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;775    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;776  }777  .domain-name {778    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);779    font-family: "IBM Plex Mono", monospace;780    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;781  }782  .domain-header-actions {783    display: inline-flex; align-items: center; gap: 5px;784    flex-shrink: 0;785  }786  .domain-add-btn,787  .domain-search-btn {788    flex-shrink: 0;789    width: 22px; height: 22px;790    display: inline-flex; align-items: center; justify-content: center;791    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);792    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);793    border-radius: 6px;794    color: var(--peach-accent);795    cursor: pointer; padding: 0;796    transition: background 120ms, border-color 120ms, transform 80ms;797    font-family: "IBM Plex Mono", monospace;798    font-size: 14px; line-height: 1;799  }800  .domain-add-btn:hover,801  .domain-search-btn:hover {802    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);803    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);804    transform: scale(1.06);805  }806  .domain-add-btn:active,807  .domain-search-btn:active { transform: scale(0.96); }808809  /* Search */810  .search-wrap {811    padding: 9px 12px 7px;812    border-bottom: 1px solid var(--peach-border);813  }814  /* UI-2 / MV-2: brief loading hint while the vault-wide list lazy-loads. */815  .search-loading {816    display: block;817    margin-top: 5px;818    font-size: 10px;819    color: var(--peach-text-dim);820    font-family: "IBM Plex Mono", monospace;821    animation: search-loading-pulse 1s ease-in-out infinite;822  }823  @keyframes search-loading-pulse { 0%,100% { opacity: 0.45; } 50% { opacity: 0.9; } }824  .search {825    width: 100%; background: var(--peach-input-bg);826    border: 1px solid var(--peach-input-border);827    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;828    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;829    transition: border-color 120ms, box-shadow 120ms;830  }831  .search:focus {832    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);833    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);834  }835  .search::placeholder { color: var(--peach-text-muted); }836837  /* Results */838  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }839  .results::-webkit-scrollbar { display: none; }840841  /* Entry rows */842  .entry {843    display: flex; align-items: center; padding: 8px 12px;844    cursor: pointer; border-bottom: 1px solid var(--peach-border);845    transition: background 70ms; position: relative; outline: none;846  }847  .entry:last-child { border-bottom: none; }848  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }849  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }850  .entry.focused::before {851    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;852    width: 2px; border-radius: 2px;853    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);854  }855856  .entry-icon {857    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;858    background: var(--peach-input-bg); border: 1px solid var(--peach-border);859    display: flex; align-items: center; justify-content: center;860    overflow: hidden; margin-right: 10px;861  }862  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }863  .entry-icon.is-new {864    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);865    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);866    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);867  }868869  .entry-info { flex: 1; min-width: 0; }870  .entry-title {871    font-size: 12.5px; color: var(--peach-text);872    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;873    line-height: 1.3;874  }875  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }876  .entry-sub {877    font-size: 10px; color: var(--peach-text-dim);878    font-family: "IBM Plex Mono", monospace;879    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;880    margin-top: 1px;881  }882883  .totp-badge {884    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;885    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);886    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);887    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;888  }889  .passkey-badge {890    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;891    border-radius: 4px;892    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);893    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);894    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);895    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;896  }897898  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }899900  .empty-hint {901    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);902    font-family: "IBM Plex Mono", monospace;903  }904905  /* Create form */906  .create-form-wrap {907    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;908  }909  .create-head {910    display: flex; align-items: center; gap: 8px;911    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);912  }913  .back-btn {914    background: transparent; border: none; cursor: pointer;915    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;916    display: flex; align-items: center; line-height: 0;917    transition: color 100ms, background 100ms;918  }919  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }920  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }921  /* minmax(0, 1fr) caps the grid track at the popup width — without it,922     long monospace content (e.g. a 60-char generated password) would923     auto-size the track wider than the popup and overflow the right edge. */924  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }925  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }926  .f-label {927    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;928    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;929  }930  .f-input {931    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);932    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;933    font-size: 11px; font-family: "IBM Plex Mono", monospace;934    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;935  }936  .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); }937  .f-input::placeholder { color: var(--peach-text-muted); }938  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }939  .f-row { display: flex; gap: 6px; }940  .f-row .f-input { flex: 1; min-width: 0; }941  .gen-btn {942    padding: 0 10px; border-radius: 7px; border: none;943    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);944    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);945    font-size: 10px; font-family: "IBM Plex Mono", monospace;946    cursor: pointer; white-space: nowrap; flex-shrink: 0;947    display: flex; align-items: center; gap: 4px;948    transition: background 100ms;949  }950  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }951  .gen-toggle-link {952    background: none; border: none; padding: 2px 0;953    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);954    font-size: 10px; font-family: "IBM Plex Mono", monospace;955    cursor: pointer; text-align: left; transition: color 100ms;956  }957  .gen-toggle-link:hover { color: var(--peach-accent); }958  .pw-history {959    display: grid; gap: 4px; margin-top: 4px;960    max-height: 150px; overflow-y: auto; scrollbar-width: thin;961  }962  .pw-history-row {963    display: flex; align-items: center; justify-content: space-between; gap: 6px;964    padding: 5px 7px; border-radius: 7px;965    background: color-mix(in srgb, var(--peach-accent) 6%, transparent);966    border: 1px solid color-mix(in srgb, var(--peach-accent) 10%, transparent);967  }968  .pw-history-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }969  .pw-history-pw {970    font-family: "IBM Plex Mono", monospace; font-size: 11px;971    color: var(--peach-t1, #eee); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;972  }973  .pw-history-age {974    font-family: "IBM Plex Mono", monospace; font-size: 9px;975    color: color-mix(in srgb, var(--peach-accent) 55%, transparent); letter-spacing: 0.03em;976  }977  .pw-history-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }978  .pw-history-btn {979    background: none; border: none; padding: 2px 5px; border-radius: 5px;980    color: color-mix(in srgb, var(--peach-accent) 65%, transparent);981    font-size: 9px; font-family: "IBM Plex Mono", monospace; cursor: pointer;982    transition: color 100ms, background 100ms;983  }984  .pw-history-btn:hover {985    color: var(--peach-accent);986    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);987  }988  .pw-history-empty {989    font-family: "IBM Plex Mono", monospace; font-size: 10px; line-height: 1.45;990    color: color-mix(in srgb, var(--peach-accent) 55%, transparent);991    padding: 6px 8px; border-radius: 7px;992    background: color-mix(in srgb, var(--peach-accent) 5%, transparent);993    border: 1px solid color-mix(in srgb, var(--peach-accent) 9%, transparent);994  }995  .save-btn {996    width: 100%; padding: 8px; border-radius: 8px; border: none;997    background: var(--peach-accent); color: #fff; font-size: 12px;998    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;999    transition: background 120ms, box-shadow 120ms, transform 80ms;1000    letter-spacing: 0.01em;1001  }1002  .save-btn:hover {1003    background: color-mix(in srgb, var(--peach-accent) 82%, #000);1004    box-shadow: 0 4px 20px var(--peach-glow, transparent);1005  }1006  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }1007  .url-hint {1008    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1009    font-family: "IBM Plex Mono", monospace; font-style: italic;1010  }10111012  /* Success */1013  .success-wrap {1014    display: flex; flex-direction: column; align-items: center;1015    padding: 24px 16px 20px; gap: 8px;1016    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;1017  }1018  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }1019  .success-ring {1020    width: 40px; height: 40px; border-radius: 50%;1021    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);1022    display: flex; align-items: center; justify-content: center;1023  }1024  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }1025  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }10261027  /* Silver platter (State 1 — single match) */1028  .silver-platter {1029    padding: 14px 14px 12px;1030    display: flex; flex-direction: column; gap: 6px;1031  }1032  .sp-title {1033    font-size: 14px; font-weight: 500; color: var(--peach-text);1034    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1035    line-height: 1.25;1036  }1037  .sp-identity-row {1038    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;1039  }1040  .sp-identity-label {1041    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;1042    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;1043  }1044  .sp-username {1045    font-size: 12px; color: var(--peach-text-dim);1046    font-family: "IBM Plex Mono", monospace;1047    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1048    margin-bottom: 0;1049  }1050  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }1051  .sp-fill-btn {1052    width: 100%; padding: 11px; border-radius: 9px; border: none;1053    background: var(--peach-accent); color: #fff;1054    font-size: 13px; font-weight: 500; cursor: pointer;1055    font-family: Inter, sans-serif; letter-spacing: 0.01em;1056    display: flex; align-items: center; justify-content: center; min-height: 38px;1057    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;1058  }1059  .sp-fill-btn:hover {1060    filter: brightness(1.1);1061    box-shadow: 0 4px 20px var(--peach-glow, transparent);1062    transform: translateY(-1px);1063  }1064  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }1065  .sp-fill-btn.filled {1066    background: #16a34a; transform: none; filter: none;1067    box-shadow: 0 4px 16px rgba(22,163,74,0.35);1068    cursor: default;1069  }1070  .sp-fill-btn:disabled { cursor: default; }1071  .sp-actions-group {1072    margin-top: 6px;1073    display: flex; flex-direction: column; gap: 4px;1074  }1075  .sp-actions-label {1076    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;1077    color: var(--peach-text-muted);1078    font-family: "IBM Plex Mono", monospace;1079    text-align: center;1080  }1081  .sp-actions {1082    display: flex; gap: 4px; justify-content: space-between; align-items: center;1083  }1084  .sp-action-btn {1085    flex: 1; height: 28px; border: none; border-radius: 6px;1086    background: transparent; color: var(--peach-text-dim);1087    font-size: 12px; cursor: pointer;1088    transition: background 120ms ease, color 120ms ease;1089    font-family: Inter, sans-serif; letter-spacing: 0.04em;1090    display: inline-flex; align-items: center; justify-content: center; gap: 4px;1091    white-space: nowrap; overflow: hidden;1092  }1093  .sp-action-btn:hover:not(:disabled) {1094    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1095    color: var(--peach-text);1096  }1097  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }1098  .sp-action-btn.flashed {1099    color: var(--peach-accent);1100    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1101  }11021103  /* TOTP tray — shown below the silver-platter secondary actions */1104  .sp-tray {1105    margin-top: 8px;1106    padding: 10px 12px;1107    border-radius: 9px;1108    background: var(--peach-input-bg);1109    border: 1px solid var(--peach-input-border);1110    display: flex; align-items: center; gap: 12px;1111    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;1112  }1113  .sp-tray-label {1114    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;1115    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;1116    flex-shrink: 0;1117  }1118  .sp-totp-code {1119    font-size: 18px; font-weight: 500;1120    color: var(--peach-text);1121    font-family: "IBM Plex Mono", monospace;1122    letter-spacing: 0.12em;1123    flex: 1;1124    text-align: center;1125  }1126  .sp-totp-ring {1127    width: 22px; height: 22px; flex-shrink: 0;1128  }1129  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }1130  .sp-totp-ring .ring-fill {1131    stroke: var(--peach-accent);1132    transition: stroke-dashoffset 1s linear;1133    transform: rotate(-90deg);1134    transform-origin: center;1135  }1136  .sp-totp-copy {1137    background: transparent; border: none; cursor: pointer;1138    padding: 4px 8px; border-radius: 5px;1139    color: var(--peach-text-dim); font-size: 11px;1140    font-family: Inter, sans-serif;1141    transition: background 120ms, color 120ms;1142  }1143  .sp-totp-copy:hover {1144    background: color-mix(in srgb, var(--peach-text) 5%, transparent);1145    color: var(--peach-text);1146  }11471148  /* Card silver platter (State 7) — reuses .sp-* primary action classes */1149  .card-platter {1150    padding: 12px 14px 10px;1151    display: flex; flex-direction: column; gap: 4px;1152  }1153  .cp-network {1154    font-size: 10px; font-weight: 600;1155    color: var(--peach-accent);1156    letter-spacing: 0.08em; text-transform: uppercase;1157    font-family: Inter, sans-serif;1158  }1159  .cp-nickname {1160    font-size: 14px; font-weight: 500; color: var(--peach-text);1161    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1162    line-height: 1.2;1163  }1164  .cp-last4 {1165    font-size: 12px; color: var(--peach-text-dim);1166    font-family: "IBM Plex Mono", monospace;1167    letter-spacing: 0.04em;1168    margin-top: 2px;1169  }1170  .cp-meta {1171    font-size: 11px; color: var(--peach-text-dim);1172    font-family: "IBM Plex Mono", monospace;1173    margin-top: 2px;1174    display: flex; gap: 10px; align-items: center;1175  }1176  .cp-meta-sep { opacity: 0.5; }1177  .cp-fill-wrap { margin-top: 10px; }11781179  /* Locked state */1180  .locked-wrap {1181    display: flex; flex-direction: column; align-items: stretch;1182    padding: 14px 13px 13px; gap: 9px;1183  }1184  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }1185  .locked-icon {1186    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;1187    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1188    display: flex; align-items: center; justify-content: center;1189  }1190  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }1191  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }1192  .locked-input {1193    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1194    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;1195    font-size: 11px; font-family: "IBM Plex Mono", monospace;1196    outline: none; transition: border-color 120ms, box-shadow 120ms;1197  }1198  .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); }1199  .locked-input::placeholder { color: var(--peach-text-muted); }1200  .locked-btn {1201    width: 100%; padding: 8px; border-radius: 8px; border: none;1202    background: var(--peach-accent); color: #fff; font-size: 12px;1203    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;1204    transition: background 120ms;1205    letter-spacing: 0.01em;1206    box-shadow: 0 2px 16px var(--peach-glow, transparent);1207    animation: peach-pulse-glow 2.4s ease-in-out infinite;1208  }1209  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }1210  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }1211  .locked-error {1212    font-size: 10px; color: rgba(220,80,60,0.85);1213    font-family: "IBM Plex Mono", monospace;1214  }12151216  @keyframes peach-pulse-glow {1217    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }1218    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),1219                            0 0 48px var(--peach-glow, transparent); }1220  }12211222  /* ── State 10: identity helper ─────────────────────────────── */1223  .identity-list {1224    max-height: 192px; overflow-y: auto; padding: 4px 0;1225    scrollbar-width: none;1226  }1227  .identity-list::-webkit-scrollbar { display: none; }1228  .peach-identity-row {1229    display: flex; align-items: center; gap: 10px;1230    padding: 9px 12px; cursor: pointer; border-radius: 8px;1231    transition: background 100ms ease;1232  }1233  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1234  .peach-identity-value {1235    font-family: "IBM Plex Mono", monospace; font-size: 13px;1236    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1237  }1238  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1239  .identity-search-wrap {1240    display: flex; flex-direction: column; gap: 6px;1241  }1242  .identity-mode-toggle {1243    display: inline-flex; gap: 4px; flex-wrap: wrap;1244  }1245  .identity-mode-btn {1246    border: 1px solid var(--peach-input-border);1247    background: var(--peach-input-bg);1248    color: var(--peach-text-dim);1249    border-radius: 999px;1250    padding: 4px 9px;1251    cursor: pointer;1252    font-family: "IBM Plex Mono", monospace;1253    font-size: 9px;1254    letter-spacing: 0.03em;1255    transition: background 100ms ease, border-color 100ms ease, color 100ms ease, transform 80ms ease;1256  }1257  .identity-mode-btn:hover {1258    background: color-mix(in srgb, var(--peach-text) 6%, var(--peach-input-bg));1259    color: var(--peach-text);1260  }1261  .identity-mode-btn.is-active {1262    color: var(--peach-accent);1263    border-color: color-mix(in srgb, var(--peach-accent) 30%, var(--peach-input-border));1264    background: color-mix(in srgb, var(--peach-accent) 10%, var(--peach-input-bg));1265  }1266  .identity-mode-btn:active { transform: translateY(1px); }1267  .identity-custom-row {1268    display: flex; flex-direction: column; gap: 2px;1269    padding: 9px 12px; cursor: pointer; border-radius: 8px;1270    transition: background 100ms ease;1271  }1272  .identity-custom-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1273  .identity-custom-row-title {1274    color: var(--peach-text); font-size: 12px; font-family: Inter, sans-serif;1275  }1276  .identity-custom-row-sub {1277    color: var(--peach-text-muted); font-size: 10px; font-family: "IBM Plex Mono", monospace;1278  }1279  .identity-empty {1280    padding: 10px 12px 2px; color: var(--peach-text-dim);1281    font-size: 10px; font-family: "IBM Plex Mono", monospace;1282  }1283  .identity-alt-row {1284    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1285    border-radius: 8px; transition: background 100ms ease;1286    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1287  }1288  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1289  .identity-escape-row {1290    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1291    border-radius: 8px; transition: background 100ms ease; outline: none;1292    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1293    margin-top: 2px;1294  }1295  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1296  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1297  .identity-alt-input-wrap.open { display: flex; }1298  .identity-alt-input {1299    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1300    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1301    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1302    outline: none; transition: border-color 120ms;1303  }1304  .identity-alt-input:focus {1305    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1306    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1307  }1308  .identity-alt-confirm {1309    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1310    background: var(--peach-accent); color: #fff; font-size: 12px;1311    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1312  }1313  /* ── Generator view (after identity picked) ────────────────── */1314  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1315  .gen-confirmed {1316    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1317    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1318    border-radius: 8px;1319  }1320  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1321  .gen-confirmed-val {1322    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1323    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1324  }1325  .gen-label {1326    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1327    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1328  }1329  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1330  .gen-pw-val {1331    flex: 1; padding: 8px 10px; border-radius: 7px;1332    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1333    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1334    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1335  }1336  .gen-regen-btn {1337    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1338    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1339    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1340    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1341  }1342  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1343  .gen-fill-btn {1344    padding: 10px; border-radius: 8px; border: none;1345    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1346    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1347    transition: filter 120ms ease, transform 80ms ease;1348  }1349  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1350  .gen-fill-btn:active { transform: translateY(0); }13511352  /* ── Smart password generator (parity with main UI compact mode) ─── */1353  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1354  .pwgen-display-row {1355    display: flex; align-items: center; gap: 6px;1356    padding: 8px 10px; border-radius: 7px;1357    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1358  }1359  .pwgen-output {1360    flex: 1; min-width: 0; width: 0;1361    font-family: "IBM Plex Mono", monospace; font-size: 12px;1362    color: var(--peach-text);1363    background: transparent; border: none; outline: none; padding: 0;1364  }1365  .pwgen-icon-btn {1366    flex-shrink: 0;1367    width: 26px; height: 26px;1368    display: inline-flex; align-items: center; justify-content: center;1369    background: transparent; border: 1px solid var(--peach-input-border);1370    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1371    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1372  }1373  .pwgen-icon-btn:hover {1374    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1375    color: var(--peach-accent);1376    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1377  }1378  .pwgen-icon-btn.is-copied {1379    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1380    color: var(--peach-accent);1381    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1382  }1383  .pwgen-controls-row {1384    display: flex; align-items: center; gap: 8px;1385    flex-wrap: wrap;1386  }1387  .pwgen-slider {1388    flex: 1; min-width: 110px;1389    accent-color: var(--peach-accent);1390    cursor: pointer; height: 2px; background: transparent;1391  }1392  .pwgen-len-num {1393    font-family: "IBM Plex Mono", monospace; font-size: 11px;1394    color: var(--peach-accent); min-width: 22px; text-align: right;1395  }1396  .pwgen-amount-label {1397    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1398    font-size: 9px; min-width: 50px;1399  }1400  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1401  .pwgen-len-input {1402    font-family: "IBM Plex Mono", monospace; font-size: 11px;1403    color: var(--peach-accent); width: 28px; text-align: right;1404    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1405    outline: none; padding: 0; min-width: 22px;1406  }1407  @keyframes identity-suggest-in {1408    from { opacity: 0; transform: translateY(-4px); }1409    to   { opacity: 1; transform: none; }1410  }1411  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1412    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1413  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1414  .identity-collapse-btn {1415    margin-left: auto; background: transparent; border: none; cursor: pointer;1416    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1417    line-height: 0; border-radius: 3px;1418    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1419  }1420  .identity-collapse-btn:hover { color: var(--peach-text); }1421  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1422  .identity-rows { display: grid; grid-template-rows: 1fr;1423    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1424  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1425  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1426    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1427  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1428  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1429  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1430  .identity-filter-pill {1431    padding: 2px 7px; border-radius: 999px;1432    border: 1px solid var(--peach-input-border);1433    background: transparent; color: var(--peach-text-muted);1434    font-family: "IBM Plex Mono", monospace; font-size: 9px;1435    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1436  }1437  .identity-filter-pill.is-on {1438    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1439    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1440    color: var(--peach-accent);1441  }1442  .identity-suggest-row {1443    display: flex; align-items: center; gap: 5px;1444    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1445    background: transparent; cursor: pointer; text-align: left;1446    transition: background 80ms;1447  }1448  .identity-suggest-row:hover,1449  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1450  .identity-suggest-val {1451    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1452    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1453  }1454  .identity-suggest-type {1455    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1456    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1457  }1458  .identity-suggest-type--email {1459    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1460    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1461  }1462  .identity-suggest-type--username {1463    color: var(--peach-text-muted);1464    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1465  }1466  .identity-suggest-meta {1467    font-family: "IBM Plex Mono", monospace; font-size: 9px;1468    color: var(--peach-text-muted); flex-shrink: 0;1469  }1470  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1471  .pwgen-pill {1472    padding: 3px 8px; border-radius: 999px;1473    border: 1px solid var(--peach-input-border);1474    background: transparent; color: var(--peach-text-muted);1475    font-family: "IBM Plex Mono", monospace; font-size: 9px;1476    letter-spacing: 0.06em; cursor: pointer;1477    transition: all 130ms ease;1478  }1479  .pwgen-pill.is-on {1480    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1481    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1482    color: var(--peach-accent);1483  }1484  .pwgen-pill:not(.is-on):hover {1485    color: var(--peach-text-dim);1486    border-color: var(--peach-text-muted);1487  }1488  .pwgen-policy-hint {1489    font-size: 10px; color: var(--peach-text-muted);1490    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1491    line-height: 1.3;1492  }1493  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }14941495  /* ── Save offer (after password filled) ───────────────────── */1496  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1497  .save-offer-title {1498    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1499  }1500  .save-offer-row {1501    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1502    border-radius: 7px; background: var(--peach-input-bg);1503    border: 1px solid var(--peach-input-border);1504  }1505  .save-offer-lbl {1506    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1507    font-family: "IBM Plex Mono", monospace;1508  }1509  .save-offer-val {1510    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1511    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1512  }1513  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1514  .save-offer-save {1515    flex: 1; padding: 9px; border-radius: 8px; border: none;1516    background: var(--peach-accent); color: #fff; font-size: 13px;1517    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1518  }1519  .save-offer-save:hover { filter: brightness(1.08); }1520  .save-offer-skip {1521    flex: 1; padding: 9px; border-radius: 8px; border: none;1522    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1523    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1524    font-family: Inter, sans-serif; transition: background 100ms ease;1525  }1526  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1527`;15281529export function showAutofillSelector(1530  anchorEl: HTMLInputElement,1531  entries: SelectorEntry[],1532  onSelect: (id: string) => void,1533  options: SelectorOptions = {}1534): () => void {1535  const securityOrigin = getSecurityOriginDisplay(options.securityOrigin ?? location.origin);1536  const securityOriginLabel = detectHomograph(securityOrigin) ? `⚠ ${securityOrigin}` : securityOrigin;1537  const host = document.createElement("div");1538  // When anchorEl is inside a focus-trapping modal the modal's JS focus trap fires1539  // when Peach's internal inputs gain focus, immediately blurring them and closing1540  // the suggest list. Mounting the host INSIDE the modal makes the trap treat Peach1541  // as in-bounds (v3.6.131).1542  //1543  // We deliberately do NOT treat every <form> as a modal (the v3.6.132 broadening).1544  // A plain login page whose card uses transform/filter/backdrop-filter establishes1545  // a containing block for position:fixed, so a host mounted inside it lands offset1546  // and is clipped by the card's overflow. juniesdream.com/admin/login is the1547  // canonical case: section.admin-login has backdrop-filter:blur(14px), which pushed1548  // the popup ~400px off the field and clipped it behind overflow:clip — the user1549  // saw nothing. Real modals are detected by ARIA or a fixed-position overlay;1550  // everything else mounts at the document root, where fixed == viewport.1551  const modalAncestor = (1552    anchorEl.closest<HTMLElement>('dialog, [aria-modal="true"], [role="dialog"]') ??1553    (() => {1554      let cur: HTMLElement | null = anchorEl.parentElement;1555      while (cur && cur !== document.body) {1556        if (window.getComputedStyle(cur).position === 'fixed') return cur;1557        cur = cur.parentElement;1558      }1559      return null;1560    })()1561  );1562  host.style.cssText = `position: fixed; z-index: 2147483647;`;1563  host.style.setProperty("--peach-accent", accentHex);1564  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1565  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1566  // Hint the compositor that top/left animate during scroll repositioning so the1567  // popup stays on the GPU layer and doesn't flicker as observeAnchorPosition1568  // re-asserts its coordinates.1569  host.style.willChange = "top, left";1570  // delegatesFocus: focus on an internal input (search, inline unlock) makes the1571  // HOST appear focused to the outside DOM. Modal focus traps that monitor1572  // focusin then see the host (mounted inside the modal) as the focused element1573  // rather than an opaque closed-shadow node, so they don't fire their1574  // "focus escaped" handler and yank focus back. Harmless outside modals.1575  const shadow = host.attachShadow({ mode: "closed", delegatesFocus: true });15761577  const style = shadow.appendChild(document.createElement("style"));1578  style.textContent = SELECTOR_STYLES;15791580  const rect = anchorEl.getBoundingClientRect();1581  // Viewport-relative placeholder; updatePosition() re-asserts this after mount,1582  // applying containing-block compensation once host.parentElement is known.1583  host.style.top = `${rect.bottom + 5}px`;1584  host.style.left = `${rect.left}px`;1585  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1586  // wide single-input fields (e.g. centered email input on signup pages).1587  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1588  // expand the host after the initial measurement.1589  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1590  host.style.width = `${popupWidth}px`;15911592  const container = shadow.appendChild(document.createElement("div"));1593  container.className = "peach-inline-popup";1594  container.setAttribute("data-theme", popupTheme);15951596  // MV-2: the vault-wide list is loaded lazily on the first search gesture,1597  // never eagerly on passive popup open. Cached for the popup's lifetime.1598  let searchableEntries: SelectorEntry[] = options.searchableEntries ?? [];1599  let searchableLoading = false;1600  let searchableLoaded = !options.loadSearchableEntries;16011602  async function ensureSearchableLoaded(rerender: () => void): Promise<void> {1603    if (searchableLoaded || searchableLoading || !options.loadSearchableEntries) {1604      return;1605    }1606    searchableLoading = true;1607    try {1608      searchableEntries = await options.loadSearchableEntries();1609    } catch {1610      searchableEntries = [];1611    } finally {1612      searchableLoaded = true;1613      searchableLoading = false;1614      rerender();1615    }1616  }1617  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();16181619  let query = "";1620  let focusedIndex = -1;1621  let currentMode: "list" | "create" | "success" | "silver-platter" | "identity-helper" | "edit" = "list";1622  let searchInput: HTMLInputElement | null = null;1623  let identityMode: IdentityFilterMode = "both";1624  // Tracks the silver-platter entry the user pivoted away from, so the1625  // search/list header can offer a one-click way back to it. null when the1626  // popup never showed a single-match platter (e.g. multi-match list view).1627  let silverPlatterOrigin: SelectorEntry | null = null;1628  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1629  // setInterval. Add to this list — don't fan out the dismiss function.1630  const cleanupHooks: Array<() => void> = [];16311632  // Smooth height transitions whenever content changes height.1633  // ResizeObserver fires on natural height changes; we freeze the old height,1634  // then animate to the new one so the surface never jumps.1635  {1636    let prevH = 0;1637    let blocked = false;1638    const heightRo = new ResizeObserver(([entry]) => {1639      if (blocked) return;1640      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1641      if (prevH > 0 && Math.abs(h - prevH) > 1) {1642        blocked = true;1643        container.style.height = `${prevH}px`;1644        requestAnimationFrame(() => requestAnimationFrame(() => {1645          container.style.height = `${h}px`;1646          prevH = h;1647          const onEnd = (e: TransitionEvent) => {1648            if (e.propertyName !== "height") return;1649            container.style.height = "";1650            blocked = false;1651            container.removeEventListener("transitionend", onEnd);1652          };1653          container.addEventListener("transitionend", onEnd);1654        }));1655      } else {1656        prevH = h;1657      }1658    });1659    heightRo.observe(container);1660    cleanupHooks.push(() => heightRo.disconnect());1661  }16621663  // Pre-capture the anchor field value for username prefill1664  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1665  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1666  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";16671668  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1669    const seen = new Set<string>();1670    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1671  }16721673  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1674    const q = value.trim().toLowerCase();1675    const deduped = uniqueEntries(source);1676    if (!q) return deduped.slice(0, 8);1677    return deduped.filter(e =>1678      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1679    ).slice(0, 12);1680  }16811682  function activeEntries(): SelectorEntry[] {1683    // When user is typing a search, filter across all known entries (domain matches + vault)1684    if (query.trim()) {1685      const merged = uniqueEntries([...entries, ...searchableEntries]);1686      return filterEntries(merged, query);1687    }1688    // Default: show domain matches; fall back to vault search when no matches1689    if (entries.length > 0) return entries;1690    return filterEntries(searchableEntries, "").slice(0, 8);1691  }16921693  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1694    const icon = document.createElement("div");1695    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1696    if (isNew) {1697      icon.innerHTML = plusSvgStr();1698    } else {1699      // Use the generic key glyph for all entries in the page-injected selector.1700      // Avoids disclosing vault domains to any third party and avoids needing1701      // to expose the browser favicon API to page context via web_accessible_resources.1702      void url;1703      icon.innerHTML = keySvgStr();1704    }1705    return icon;1706  }17071708  function renderIdentityHelper() {1709    currentMode = "identity-helper";1710    container.innerHTML = "";1711    focusedIndex = -1;1712    searchInput = null;17131714    const fallbackKind: IdentityKind = options.identityKind ?? "username";1715    const identities = filterSavedIdentities(options.savedIdentities ?? [], query, identityMode);1716    const typedQuery = query.trim();1717    const customKind = resolveCustomIdentityKind(typedQuery, identityMode, fallbackKind);17181719    function applyIdentity(identity: string) {1720      if (options.hasEmailField) {1721        if (options.identityKind === "email") {1722          options.onFillFields?.("", "", identity);       // fill email field now1723          renderSecondaryIdentityStep("username", identity);1724        } else {1725          options.onFillFields?.(identity, "", "");       // fill username field now1726          renderSecondaryIdentityStep("email", identity);1727        }1728      } else {1729        options.onFillFields?.(identity, "");1730        renderGenerator(identity);1731      }1732    }17331734    function applyCustomIdentity(identity: string) {1735      const trimmed = identity.trim();1736      if (!trimmed) return;1737      applyIdentity(trimmed);1738    }17391740    // Header: "NEW ACCOUNT" + domain name1741    const hdr = container.appendChild(document.createElement("div"));1742    hdr.className = "domain-header";1743    const headText = hdr.appendChild(document.createElement("div"));1744    headText.className = "domain-header-text";1745    const eyebrow = headText.appendChild(document.createElement("div"));1746    eyebrow.className = "domain-eyebrow";1747    eyebrow.textContent = "NEW ACCOUNT";1748    const domName = headText.appendChild(document.createElement("div"));1749    domName.className = "domain-name";1750    domName.textContent = securityOriginLabel;17511752    const actions = hdr.appendChild(document.createElement("div"));1753    actions.className = "identity-mode-toggle";1754    for (const mode of ["both", "email", "username"] as const) {1755      const btn = actions.appendChild(document.createElement("button"));1756      btn.type = "button";1757      btn.className = `identity-mode-btn${identityMode === mode ? " is-active" : ""}`;1758      btn.textContent = identityFilterLabel(mode);1759      btn.setAttribute("aria-pressed", String(identityMode === mode));1760      btn.addEventListener("click", () => {1761        identityMode = mode;1762        renderIdentityHelper();1763      });1764    }17651766    const searchWrap = container.appendChild(document.createElement("div"));1767    searchWrap.className = "search-wrap identity-search-wrap";1768    const search = searchWrap.appendChild(document.createElement("input"));1769    search.className = "search";1770    search.placeholder = "search identities…";1771    search.value = query;1772    search.addEventListener("input", () => {1773      query = search.value;1774      renderIdentityHelper();1775      searchInput?.focus();1776      searchInput?.setSelectionRange(query.length, query.length);1777    });1778    search.addEventListener("keydown", (e) => {1779      if (e.key === "Escape") {1780        e.preventDefault();1781        dismiss(true);1782        return;1783      }1784      if (e.key !== "Enter") return;1785      const exact = identities.find((id) => id.value.toLowerCase() === typedQuery.toLowerCase());1786      if (exact) {1787        e.preventDefault();1788        applyIdentity(exact.value);1789        return;1790      }1791      if (!typedQuery || identities.length > 0) return;1792      e.preventDefault();1793      applyCustomIdentity(typedQuery);1794    });1795    const searchTools = searchWrap.appendChild(document.createElement("div"));1796    searchTools.className = "identity-mode-toggle";1797    const sortHint = searchTools.appendChild(document.createElement("div"));1798    sortHint.className = "identity-empty";1799    sortHint.style.padding = "0";1800    sortHint.textContent = "sorted by recent use";1801    searchInput = search;1802    const customLabel = identityMode === "both"1803      ? customKind1804      : identityMode;18051806    // Identity rows1807    const list = container.appendChild(document.createElement("div"));1808    list.className = "identity-list";1809    // Bottom fade only when the list overflows its max-height and isn't scrolled1810    // to the end. A short list (1-2 identities) shows no fade, so it never looks1811    // prematurely cut off; a long list gets the affordance, which clears on1812    // reaching the bottom.1813    const updateListFade = () => {1814      const overflowing = list.scrollHeight > list.clientHeight + 1;1815      const atBottom = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;1816      const mask = overflowing && !atBottom1817        ? "linear-gradient(to bottom, black calc(100% - 24px), transparent 100%)"1818        : "none";1819      list.style.setProperty("mask-image", mask);1820      list.style.setProperty("-webkit-mask-image", mask);1821    };1822    list.addEventListener("scroll", updateListFade);1823    if (typedQuery && identities.length === 0) {1824      const empty = list.appendChild(document.createElement("div"));1825      empty.className = "identity-empty";1826      empty.textContent = identityMode === "both"1827        ? `No match for “${typedQuery}”.`1828        : `No ${identityFilterLabel(identityMode).toLowerCase()} match for “${typedQuery}”.`;1829      const custom = list.appendChild(document.createElement("div"));1830      custom.className = "identity-custom-row";1831      const customTitle = custom.appendChild(document.createElement("div"));1832      customTitle.className = "identity-custom-row-title";1833      customTitle.textContent = `Use “${typedQuery}” as a new ${customLabel}`;1834      const customSub = custom.appendChild(document.createElement("div"));1835      customSub.className = "identity-custom-row-sub";1836      customSub.textContent = "Press Enter or click to continue.";1837      custom.addEventListener("click", () => applyCustomIdentity(typedQuery));1838    }1839    for (const id of identities) {1840      const row = list.appendChild(document.createElement("div"));1841      row.className = "peach-identity-row";1842      row.setAttribute("tabindex", "-1");1843      const val = row.appendChild(document.createElement("div"));1844      val.className = "peach-identity-value";1845      val.textContent = id.value;1846      const meta = row.appendChild(document.createElement("div"));1847      meta.className = "peach-identity-meta";1848      meta.textContent = `used ${id.useCount}×`;1849      row.addEventListener("click", () => {1850        applyIdentity(id.value);1851      });1852    }18531854    updateListFade();18551856    // Divider before "Use a different email…"1857    if (identities.length > 0) {1858      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1859    }18601861    // "Use a different email/username…" expandable row1862    const altRow = container.appendChild(document.createElement("div"));1863    altRow.className = "identity-alt-row";1864    altRow.textContent = `+ Use a different ${customLabel}…`;18651866    const altInputWrap = container.appendChild(document.createElement("div"));1867    altInputWrap.className = "identity-alt-input-wrap";1868    const altInput = altInputWrap.appendChild(document.createElement("input"));1869    altInput.className = "identity-alt-input";1870    altInput.type = "text";1871    altInput.placeholder = customLabel === "email" ? "[email protected]" : "your username";1872    altInput.setAttribute("autocomplete", "off");1873    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1874    altConfirm.className = "identity-alt-confirm";1875    altConfirm.type = "button";1876    altConfirm.textContent = "✓";18771878    function fillCustomIdentity() {1879      const v = altInput.value.trim();1880      if (!v) return;1881      applyCustomIdentity(v);1882    }18831884    altRow.addEventListener("click", () => {1885      altRow.style.display = "none";1886      altInputWrap.classList.add("open");1887      altInput.value = typedQuery || altInput.value;1888      altInput.focus();1889      altInput.setSelectionRange(altInput.value.length, altInput.value.length);1890    });1891    altConfirm.addEventListener("click", fillCustomIdentity);1892    altInput.addEventListener("keydown", (e) => {1893      if (e.key === "Enter") { e.preventDefault(); fillCustomIdentity(); }1894    });18951896    // Escape hatch: user already has a vault entry for this site but it1897    // wasn't detected (different domain, old entry, etc.). Tapping this1898    // switches to the full searchable list so they can find and fill it;1899    // selecting an entry there will trigger the remember-site toast if1900    // the domain isn't already associated.1901    // MV-2: with lazy loading we no longer know the vault-wide count up front,1902    // so offer the escape hatch whenever a loader (or an eager array) exists.1903    if (options.loadSearchableEntries || (options.searchableEntries?.length ?? 0) > 0) {1904      const escapeRow = container.appendChild(document.createElement("div"));1905      escapeRow.className = "identity-escape-row";1906      escapeRow.textContent = "I already have an account →";1907      escapeRow.setAttribute("tabindex", "0");1908      const toSearch = () => { void ensureSearchableLoaded(renderList); renderList(); };1909      escapeRow.addEventListener("click", toSearch);1910      escapeRow.addEventListener("keydown", (e) => {1911        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toSearch(); }1912      });1913    }19141915    requestAnimationFrame(() => {1916      search.focus();1917      search.setSelectionRange(query.length, query.length);1918    });1919  }19201921  /**1922   * Step 2 of the contextual signup wizard.1923   * `stepKind` is the identity type to collect in this step ("email" or "username").1924   * `firstValue` is what was picked in step 1 (the other type).1925   */1926  function renderSecondaryIdentityStep(stepKind: "email" | "username", firstValue: string) {1927    currentMode = "identity-helper";1928    container.innerHTML = "";19291930    const wrap = container.appendChild(document.createElement("div"));1931    wrap.className = "gen-view";19321933    // Header1934    const hdrRow = wrap.appendChild(document.createElement("div"));1935    hdrRow.className = "domain-header";1936    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1937    eyebrow2.className = "domain-eyebrow";1938    eyebrow2.textContent = "NEW ACCOUNT";1939    const domName2 = hdrRow.appendChild(document.createElement("div"));1940    domName2.className = "domain-name";1941    domName2.textContent = securityOriginLabel;19421943    // Confirmed first step1944    const conf = wrap.appendChild(document.createElement("div"));1945    conf.className = "gen-confirmed";1946    const confCheck = conf.appendChild(document.createElement("span"));1947    confCheck.className = "gen-confirmed-check";1948    confCheck.textContent = "✓";1949    const confVal = conf.appendChild(document.createElement("div"));1950    confVal.className = "gen-confirmed-val";1951    confVal.textContent = firstValue;19521953    const stepLbl = wrap.appendChild(document.createElement("div"));1954    stepLbl.className = "gen-label";1955    stepLbl.textContent = stepKind === "email" ? "Now choose your email" : "Now choose your username";19561957    // Filter saved identities to the correct type for this step1958    const identities = (options.savedIdentities ?? [])1959      .filter(s => s.type === stepKind)1960      .sort((a, b) => (b.lastUsed ?? 0) - (a.lastUsed ?? 0))1961      .slice(0, 6);19621963    const list = wrap.appendChild(document.createElement("div"));1964    list.className = "identity-list";1965    for (const id of identities) {1966      const row = list.appendChild(document.createElement("div"));1967      row.className = "peach-identity-row";1968      row.setAttribute("tabindex", "-1");1969      const val = row.appendChild(document.createElement("div"));1970      val.className = "peach-identity-value";1971      val.textContent = id.value;1972      const meta = row.appendChild(document.createElement("div"));1973      meta.className = "peach-identity-meta";1974      meta.textContent = `used ${id.useCount}×`;1975      row.addEventListener("click", () => applySecondIdentity(id.value));1976    }19771978    // Text input for a value not in the list1979    const altInputWrap = wrap.appendChild(document.createElement("div"));1980    altInputWrap.className = "identity-alt-input-wrap open";1981    const altInput = altInputWrap.appendChild(document.createElement("input"));1982    altInput.className = "identity-alt-input";1983    altInput.type = stepKind === "email" ? "email" : "text";1984    altInput.placeholder = stepKind === "email" ? "[email protected]" : "your username";1985    altInput.setAttribute("autocomplete", "off");1986    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1987    altConfirm.className = "identity-alt-confirm";1988    altConfirm.type = "button";1989    altConfirm.textContent = "→";19901991    function applySecondIdentity(value: string) {1992      const trimmed = value.trim();1993      if (!trimmed) return;1994      // Determine final email + username order before passing to the generator1995      const [email, username] = stepKind === "email"1996        ? [trimmed, firstValue]1997        : [firstValue, trimmed];1998      if (stepKind === "email") {1999        options.onFillFields?.("", "", trimmed); // fill email field2000      } else {2001        options.onFillFields?.(trimmed, "", ""); // fill username field2002      }2003      renderGenerator(email, username);2004    }20052006    altConfirm.addEventListener("click", () => applySecondIdentity(altInput.value));2007    altInput.addEventListener("keydown", (e) => {2008      if (e.key === "Enter") { e.preventDefault(); applySecondIdentity(altInput.value); }2009    });20102011    // Skip: proceed without this field2012    const skipRow = wrap.appendChild(document.createElement("div"));2013    skipRow.className = "identity-escape-row";2014    skipRow.textContent = `Skip ${stepKind} →`;2015    skipRow.setAttribute("tabindex", "0");2016    skipRow.addEventListener("click", () => {2017      const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];2018      renderGenerator(email, username);2019    });2020    skipRow.addEventListener("keydown", (e) => {2021      if (e.key === "Enter" || e.key === " ") {2022        e.preventDefault();2023        const [email, username] = stepKind === "email" ? ["", firstValue] : [firstValue, ""];2024        renderGenerator(email, username);2025      }2026    });20272028    requestAnimationFrame(() => { altInput.focus(); });2029  }20302031  function renderGenerator(filledEmail: string, filledUsername?: string) {2032    container.innerHTML = "";2033    const sitePolicy = detectPasswordPolicy();20342035    const wrap = container.appendChild(document.createElement("div"));2036    wrap.className = "gen-view";20372038    // Header: domain + NEW ACCOUNT2039    const hdrRow = wrap.appendChild(document.createElement("div"));2040    hdrRow.className = "domain-header";2041    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));2042    eyebrow2.className = "domain-eyebrow";2043    eyebrow2.textContent = "NEW ACCOUNT";2044    const domName2 = hdrRow.appendChild(document.createElement("div"));2045    domName2.className = "domain-name";2046    domName2.textContent = securityOriginLabel;20472048    // Confirmed identity rows — show both username and email when both were collected2049    function confirmedRow(value: string) {2050      const conf = wrap.appendChild(document.createElement("div"));2051      conf.className = "gen-confirmed";2052      const confCheck = conf.appendChild(document.createElement("span"));2053      confCheck.className = "gen-confirmed-check";2054      confCheck.textContent = "✓";2055      const confVal = conf.appendChild(document.createElement("div"));2056      confVal.className = "gen-confirmed-val";2057      confVal.textContent = value;2058    }2059    if (filledEmail) confirmedRow(filledEmail);2060    if (filledUsername && filledUsername !== filledEmail) confirmedRow(filledUsername);20612062    const lbl = wrap.appendChild(document.createElement("div"));2063    lbl.className = "gen-label";2064    lbl.textContent = "Generate a password";20652066    let currentPw = "";2067    const smartGen = createSmartGenerator({2068      policy: sitePolicy,2069      onChange: (pw) => { currentPw = pw; },2070    });2071    wrap.appendChild(smartGen.root);20722073    const fillBtn = wrap.appendChild(document.createElement("button"));2074    fillBtn.className = "gen-fill-btn";2075    fillBtn.type = "button";2076    fillBtn.textContent = "Copy & fill";2077    fillBtn.addEventListener("click", async () => {2078      if (!currentPw) return;2079      fillBtn.disabled = true;2080      fillBtn.textContent = "Saving…";2081      // Fill the page fields first — password lands immediately.2082      options.onFillFields?.("", currentPw, "");2083      // Auto-save to vault. Fall back to the save-offer form only if the save fails2084      // (vault locked, quota exceeded, etc.) so the user sees the error and can retry.2085      const saveUsername = filledUsername || filledEmail;2086      const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;2087      try {2088        const res = await chrome.runtime.sendMessage({2089          type: "ADD_ENTRY",2090          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: currentPw, type: "login" },2091        });2092        if ((res as { ok?: boolean }).ok) {2093          showSuccess(sTitle);2094        } else {2095          renderSaveOffer(filledEmail, currentPw, filledUsername);2096        }2097      } catch {2098        renderSaveOffer(filledEmail, currentPw, filledUsername);2099      }2100    });2101  }21022103  function renderSaveOffer(filledEmail: string, filledPassword: string, filledUsername?: string) {2104    container.innerHTML = "";2105    const domain = securityOriginLabel;21062107    const wrap = container.appendChild(document.createElement("div"));2108    wrap.className = "save-offer";21092110    const title = wrap.appendChild(document.createElement("div"));2111    title.className = "save-offer-title";2112    title.textContent = "Save this login to Peach?";21132114    function detailRow(label: string, value: string) {2115      const row = wrap.appendChild(document.createElement("div"));2116      row.className = "save-offer-row";2117      const lbl = row.appendChild(document.createElement("div"));2118      lbl.className = "save-offer-lbl";2119      lbl.textContent = label;2120      const val = row.appendChild(document.createElement("div"));2121      val.className = "save-offer-val";2122      val.textContent = value;2123    }21242125    detailRow("site", domain);2126    // When both username and email were collected, show both; otherwise show the identity as "email"2127    if (filledUsername) {2128      detailRow("username", filledUsername);2129      if (filledEmail) detailRow("email", filledEmail);2130    } else {2131      if (filledEmail) detailRow("email", filledEmail);2132    }2133    detailRow("password", "••••••••••••••••");21342135    const btns = wrap.appendChild(document.createElement("div"));2136    btns.className = "save-offer-btns";21372138    const saveBtn = btns.appendChild(document.createElement("button"));2139    saveBtn.className = "save-offer-save";2140    saveBtn.type = "button";2141    saveBtn.textContent = "Save";2142    saveBtn.addEventListener("click", async () => {2143      saveBtn.disabled = true;2144      saveBtn.textContent = "Saving…";2145      try {2146        // When both username and email were set, save them in the correct fields.2147        // Otherwise fall back to storing the identity as the username (current behaviour).2148        const saveUsername = filledUsername || filledEmail;2149        const saveEmail = filledUsername ? (filledEmail || undefined) : undefined;2150        const res = await chrome.runtime.sendMessage({2151          type: "ADD_ENTRY",2152          payload: { title: sTitle, url: sOrigin, username: saveUsername, email: saveEmail, password: filledPassword, type: "login" },2153        });2154        if ((res as { ok?: boolean }).ok) {2155          showSuccess(sTitle);2156        } else {2157          saveBtn.disabled = false;2158          saveBtn.textContent = "Save";2159        }2160      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }2161    });21622163    const skipBtn = btns.appendChild(document.createElement("button"));2164    skipBtn.className = "save-offer-skip";2165    skipBtn.type = "button";2166    skipBtn.textContent = "Not now";2167    skipBtn.addEventListener("click", () => { dismiss(true); });2168  }21692170  function renderList() {2171    container.innerHTML = "";2172    focusedIndex = -1;2173    searchInput = null;2174    currentMode = "list";21752176    const current = activeEntries();21772178    // Domain header (always show) — eyebrow + domain on the left,2179    // a "+" shortcut to the create form on the right so the user is never2180    // trapped in the search list when they want to make a new entry.2181    const domHdr = document.createElement("div");2182    domHdr.className = "domain-header";2183    const headText = document.createElement("div");2184    headText.className = "domain-header-text";2185    const eyebrow = document.createElement("div");2186    eyebrow.className = "domain-eyebrow";2187    eyebrow.textContent = options.isSignup2188      ? "Sign up as"2189      : entries.length > 0 ? "Saved for this site" : "No saved login";2190    const domName = document.createElement("div");2191    domName.className = "domain-name";2192    domName.textContent = securityOriginLabel;2193    headText.append(eyebrow, domName);2194    domHdr.appendChild(headText);21952196    if (!options.isSignup) {2197      const actions = document.createElement("div");2198      actions.className = "domain-header-actions";21992200      // Back arrow takes the place of the silver-platter's search icon when2201      // the user has pivoted away from a single-match platter — gives them2202      // a one-click way back to the original recommendation.2203      if (silverPlatterOrigin) {2204        const backBtn = document.createElement("button");2205        backBtn.className = "domain-search-btn";2206        backBtn.type = "button";2207        backBtn.setAttribute("aria-label", "Back to suggested entry");2208        backBtn.title = "Back to suggested entry";2209        backBtn.innerHTML = backSvgStr();2210        backBtn.addEventListener("click", (e) => {2211          e.stopPropagation();2212          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);2213        });2214        actions.appendChild(backBtn);2215      }22162217      const addBtn = document.createElement("button");2218      addBtn.className = "domain-add-btn";2219      addBtn.type = "button";2220      addBtn.setAttribute("aria-label", "Create new entry");2221      addBtn.title = "Create new entry";2222      addBtn.textContent = "+";2223      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2224      actions.appendChild(addBtn);22252226      domHdr.appendChild(actions);2227    }22282229    container.appendChild(domHdr);22302231    // Search — always show so user can find entries beyond the domain matches2232    const sw = document.createElement("div"); sw.className = "search-wrap";2233    searchInput = document.createElement("input");2234    searchInput.className = "search";2235    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";2236    searchInput.value = query;2237    searchInput.addEventListener("input", () => {2238      query = searchInput?.value ?? "";2239      // MV-2: typing in the search box is the explicit gesture that loads the2240      // vault-wide list (once, cached); it re-renders when it resolves.2241      void ensureSearchableLoaded(renderList);2242      renderList();2243      searchInput?.focus();2244      searchInput?.setSelectionRange(query.length, query.length);2245    });2246    sw.appendChild(searchInput);2247    // UI-2 / MV-2: show a brief loading hint while the vault-wide list loads2248    // on the first search gesture (cached afterwards, so only the first time).2249    if (searchableLoading) {2250      const loadingHint = document.createElement("span");2251      loadingHint.className = "search-loading";2252      loadingHint.textContent = "searching…";2253      sw.appendChild(loadingHint);2254    }2255    container.appendChild(sw);22562257    // Results2258    const results = document.createElement("div");2259    results.className = "results";2260    container.appendChild(results);22612262    if (current.length === 0 && entries.length > 0) {2263      // Show a hint but don't render empty entries2264    }22652266    for (let i = 0; i < current.length; i++) {2267      const e = current[i]!;2268      const entryEl = document.createElement("div");2269      entryEl.className = "entry";2270      entryEl.dataset.id = e.id;2271      entryEl.dataset.index = String(i);2272      entryEl.setAttribute("tabindex", "-1");22732274      entryEl.appendChild(makeEntryIcon(e.url));22752276      const info = document.createElement("div"); info.className = "entry-info";2277      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;2278      const subEl = document.createElement("div"); subEl.className = "entry-sub";2279      const domain = e.url ? getDomainFromUrl(e.url) : "";2280      subEl.textContent = domain || e.username || "";2281      info.append(titleEl, subEl);2282      entryEl.appendChild(info);22832284      if (e.hasTotp) {2285        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";2286        entryEl.appendChild(badge);2287      }2288      if (e.hasPasskey) {2289        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";2290        entryEl.appendChild(badge);2291      }22922293      entryEl.addEventListener("click", () => {2294        if (options.isSignup && options.onFillFields) {2295          // Fill username, email, and leave password for the user to confirm2296          options.onFillFields(e.username ?? "", "", e.email);2297          dismiss();2298        } else {2299          onSelect(e.id);2300          dismiss();2301        }2302      });2303      results.appendChild(entryEl);2304    }23052306    // Divider before "New entry"2307    if (current.length > 0) {2308      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));2309    }23102311    // "New entry" row — always present2312    const newEl = document.createElement("div");2313    newEl.className = "entry";2314    newEl.setAttribute("tabindex", "-1");2315    newEl.appendChild(makeEntryIcon(undefined, true));23162317    const newInfo = document.createElement("div"); newInfo.className = "entry-info";2318    const newTitle = document.createElement("div");2319    newTitle.className = "entry-title is-new";2320    newTitle.textContent = `New entry for ${sTitle}`;2321    const newSub = document.createElement("div");2322    newSub.className = "entry-sub";2323    newSub.textContent = sOrigin;2324    newInfo.append(newTitle, newSub);2325    newEl.appendChild(newInfo);2326    newEl.addEventListener("click", showCreateForm);2327    results.appendChild(newEl);23282329    // Focus search if present2330    if (searchInput) {2331      requestAnimationFrame(() => {2332        searchInput?.focus();2333        // Seed query (from type-to-search or domain-search-btn) lands at the2334        // end so the next keystroke extends it, not overwrites.2335        searchInput?.setSelectionRange(query.length, query.length);2336      });2337    }2338  }23392340  function setFocused(idx: number) {2341    const all = container.querySelectorAll<HTMLElement>(".entry");2342    all.forEach((el, i) => el.classList.toggle("focused", i === idx));2343    focusedIndex = idx;2344    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });2345  }23462347  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {2348    const typed = identities.filter(s => s.type === fieldType);2349    if (!typed.length) return;2350    let collapsed = false;2351    let suppressNextFocus = false;23522353    const list = g.appendChild(document.createElement("div"));2354    list.className = "identity-suggest-list";2355    list.style.display = "none";23562357    // Collapse toggle — sits alone now that filter pills are gone2358    const collapseRow = list.appendChild(document.createElement("div"));2359    collapseRow.className = "identity-filter-row";2360    collapseRow.style.justifyContent = "flex-end";2361    const collapseBtn = collapseRow.appendChild(document.createElement("button"));2362    collapseBtn.type = "button";2363    collapseBtn.className = "identity-collapse-btn";2364    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>`;2365    collapseBtn.addEventListener("mousedown", (e) => {2366      e.preventDefault();2367      collapsed = !collapsed;2368      collapseBtn.classList.toggle("is-collapsed", collapsed);2369      rowsWrapper.classList.toggle("is-collapsed", collapsed);2370    });23712372    const rowsWrapper = list.appendChild(document.createElement("div"));2373    rowsWrapper.className = "identity-rows";2374    const rows = rowsWrapper.appendChild(document.createElement("div"));2375    rows.className = "identity-rows-inner";23762377    // Bottom fade only when the list actually overflows and isn't scrolled to2378    // the end — a static mask-image fades the last row even on a 1-2 item list2379    // that fits entirely, making it look cut off. Driven off live scroll state.2380    const updateRowsFade = () => {2381      const overflowing = rows.scrollHeight > rows.clientHeight + 1;2382      const atBottom = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 2;2383      const mask = overflowing && !atBottom2384        ? "linear-gradient(to bottom, black calc(100% - 18px), transparent 100%)"2385        : "none";2386      rows.style.setProperty("mask-image", mask);2387      rows.style.setProperty("-webkit-mask-image", mask);2388    };2389    rows.addEventListener("scroll", updateRowsFade);23902391    // Hides the list and removes the document-level click watcher.2392    function hideList() {2393      list.style.display = "none";2394      document.removeEventListener("mousedown", onDocMousedown, { capture: true });2395    }23962397    // Dismiss list on any mousedown that originates outside the popup's shadow2398    // DOM. This is the ONLY close trigger for the list — blur is intentionally2399    // NOT used, because modal focus traps fire blur without a mousedown (they2400    // call element.focus() programmatically in response to focusin/focusout),2401    // which caused the list to vanish before the user could pick from it.2402    function onDocMousedown(e: MouseEvent) {2403      if (e.composedPath().includes(host)) return;2404      hideList();2405    }24062407    function pick(value: string) {2408      inp.value = value;2409      hideList();2410      suppressNextFocus = true;2411      inp.focus();2412      // If a focus trap intercepts inp.focus() and redirects to anchorEl before2413      // inp ever fires its focus event, suppressNextFocus would strand the user.2414      // Clear after a short window so subsequent clicks still work.2415      setTimeout(() => { suppressNextFocus = false; }, 120);2416    }24172418    function render() {2419      const q = inp.value.toLowerCase();2420      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);2421      rows.innerHTML = "";2422      if (!filtered.length) { hideList(); return; }2423      for (const s of filtered) {2424        const row = rows.appendChild(document.createElement("button"));2425        row.type = "button"; row.className = "identity-suggest-row";2426        const val = row.appendChild(document.createElement("span"));2427        val.className = "identity-suggest-val"; val.textContent = s.value;2428        const meta = row.appendChild(document.createElement("span"));2429        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;2430        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });2431        row.addEventListener("keydown", (e) => {2432          if (e.key === "ArrowDown") {2433            e.preventDefault();2434            (row.nextElementSibling as HTMLElement | null)?.focus();2435          } else if (e.key === "ArrowUp") {2436            e.preventDefault();2437            const prev = row.previousElementSibling as HTMLElement | null;2438            if (prev) prev.focus();2439            else inp.focus();2440          } else if (e.key === "Enter" || e.key === " ") {2441            e.preventDefault();2442            pick(s.value);2443          } else if (e.key === "Escape") {2444            e.preventDefault();2445            hideList();2446            suppressNextFocus = true;2447            inp.focus();2448          }2449        });2450        // Row blur only fires during keyboard navigation (arrow keys / Tab).2451        // Focus traps don't produce row blur events since rows aren't focused2452        // when the trap fires; this handler is therefore trap-safe.2453        row.addEventListener("blur", (e) => {2454          const rt = (e as FocusEvent).relatedTarget as Node | null;2455          if (rt && (rt === inp || list.contains(rt))) return;2456          setTimeout(() => { hideList(); }, 150);2457        });2458      }2459      list.style.display = "";2460      updateRowsFade();2461      // Register the close-on-outside-click watcher each time the list shows.2462      // addEventListener deduplicates identical (fn, options) pairs, so2463      // re-rendering on input events does not stack up listeners.2464      document.addEventListener("mousedown", onDocMousedown, { capture: true });2465    }24662467    inp.addEventListener("focus", () => {2468      if (suppressNextFocus) { suppressNextFocus = false; return; }2469      render();2470    });2471    inp.addEventListener("input", render);2472    inp.addEventListener("keydown", (e) => {2473      if (list.style.display === "none") return;2474      if (e.key === "ArrowDown" && !collapsed) {2475        e.preventDefault();2476        (rows.firstElementChild as HTMLElement | null)?.focus();2477      } else if (e.key === "Escape") {2478        e.preventDefault();2479        hideList();2480      } else if (e.key === "Tab") {2481        // Tab moves focus away intentionally — close the list.2482        hideList();2483      }2484    });2485    // No blur handler on inp. Blur fires for ANY focus movement including2486    // programmatic focus() calls from modal focus traps, which caused the list2487    // to close before the user could interact. The document mousedown listener2488    // (registered in render()) handles intentional click-outside dismissal,2489    // and the keydown handler above covers keyboard Tab/Escape.24902491    // Ensure the watcher is removed if the main popup is dismissed while the2492    // list is visible.2493    cleanupHooks.push(hideList);2494  }24952496  async function showCreateForm() {2497    currentMode = "create";2498    container.innerHTML = "";24992500    // Detect page password policy once for this form — reused on every2501    // regenerate click so the user always gets a compliant password.2502    const sitePolicy = detectPasswordPolicy();25032504    const formIdentities = options.savedIdentities ?? [];25052506    const wrap = document.createElement("div");2507    wrap.className = "create-form-wrap";25082509    // Header2510    const head = document.createElement("div"); head.className = "create-head";2511    const backBtn = document.createElement("button"); backBtn.className = "back-btn";2512    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>`;2513    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });2514    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";2515    head.append(backBtn, lbl);25162517    // Body2518    const body = document.createElement("div"); body.className = "create-body";25192520    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {2521      const g = document.createElement("div"); g.className = "f-group";2522      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;2523      const inp = document.createElement("input"); inp.className = "f-input";2524      g.append(l, inp); return { g, inp };2525    }25262527    // Title2528    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";2529    body.appendChild(tg.g);25302531    // URL2532    const ug = fGroup("website");2533    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";2534    if (loginSubdomain) {2535      const h = document.createElement("div"); h.className = "url-hint";2536      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);2537    }2538    body.appendChild(ug.g);25392540    // Username — pre-fill from anchor if it doesn't look like an email2541    const xg = fGroup("username");2542    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";2543    xg.inp.placeholder = "johndoe";2544    xg.inp.setAttribute("autocomplete", "off");2545    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");2546    body.appendChild(xg.g);25472548    // Email — pre-fill from anchor if it looks like an email2549    const eg = fGroup("email");2550    (eg.inp as HTMLInputElement).type = "email";2551    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";2552    eg.inp.placeholder = "[email protected]";2553    eg.inp.setAttribute("autocomplete", "off");2554    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");2555    body.appendChild(eg.g);25562557    // Password — full smart generator with charset pills + length slider +2558    // policy hint. Mirrors the main UI's compact generator so users get the2559    // same controls inline as in the popup.2560    const pg = fGroup("password");2561    pg.inp.remove(); // smartGen provides its own display — no separate input needed2562    let currentPassword = prePassword || "";2563    const smartGen = createSmartGenerator({2564      policy: sitePolicy,2565      initialPassword: prePassword || undefined,2566      onChange: (pw) => { currentPassword = pw; },2567    });2568    pg.g.appendChild(smartGen.root);2569    body.appendChild(pg.g);25702571    // Save2572    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";2573    saveBtn.textContent = "Save entry";2574    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";2575    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }2576    saveBtn.addEventListener("click", async () => {2577      const title = tg.inp.value.trim();2578      const pw = currentPassword.trim();2579      const username = xg.inp.value.trim();2580      const email = eg.inp.value.trim();2581      if (!title) {2582        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();2583        showFormError("Entry needs a title");2584        return;2585      }2586      if (!pw) {2587        showFormError("Entry needs a password — tap regen to make one");2588        return;2589      }2590      errEl.style.display = "none";2591      saveBtn.disabled = true; saveBtn.textContent = "Saving…";2592      try {2593        const res = await chrome.runtime.sendMessage({2594          type: "ADD_ENTRY",2595          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },2596        });2597        if ((res as { ok?: boolean }).ok) {2598          // Fill the detected form. onFillFields uses whichever identity the2599          // page anchored on — the vault captures both username and email.2600          options.onFillFields?.(username || email, pw);2601          showSuccess(title);2602        } else {2603          const err = (res as { error?: string })?.error;2604          const errMsg = err === "vault_locked"2605            ? "Vault locked — open Peach to save"2606            : err === "STORAGE_QUOTA_EXCEEDED"2607              ? "Out of storage — open Peach → Settings to free space"2608              : err2609                ? `Could not save: ${err}`2610                : "Could not save entry";2611          showFormError(errMsg);2612          saveBtn.disabled = false; saveBtn.textContent = "Save entry";2613        }2614      } catch (e) {2615        showFormError(e instanceof Error && e.message ? `Could not reach Peach: ${e.message}` : "Could not reach Peach");2616        saveBtn.disabled = false; saveBtn.textContent = "Save entry";2617      }2618    });2619    body.appendChild(saveBtn);2620    body.appendChild(errEl);26212622    wrap.append(head, body);2623    container.appendChild(wrap);2624    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });2625  }26262627  function showSuccess(title: string) {2628    currentMode = "success";2629    container.innerHTML = "";2630    const wrap = document.createElement("div"); wrap.className = "success-wrap";2631    const ring = document.createElement("div"); ring.className = "success-ring";2632    ring.innerHTML = checkSvgStr();2633    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;2634    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;2635    wrap.append(ring, t, s);2636    container.appendChild(wrap);2637    setTimeout(() => dismiss(), 1600);2638  }26392640  function flashActionBtn(btn: HTMLButtonElement) {2641    btn.classList.add("flashed");2642    setTimeout(() => btn.classList.remove("flashed"), 700);2643  }26442645  // M3/QUA-005: when both the direct clipboard write and the background COPY2646  // fallback fail, briefly show the user that the copy did not happen.2647  function flashCopyError(btn: HTMLButtonElement) {2648    const original = btn.textContent ?? "";2649    btn.textContent = "Blocked";2650    btn.classList.add("flashed");2651    setTimeout(() => {2652      btn.classList.remove("flashed");2653      if (btn.isConnected) btn.textContent = original;2654    }, 1200);2655  }26562657  function renderSilverPlatter(entry: SelectorEntry) {2658    container.innerHTML = "";2659    searchInput = null;2660    focusedIndex = -1;2661    currentMode = "silver-platter";2662    silverPlatterOrigin = entry;26632664    const domHdr = document.createElement("div");2665    domHdr.className = "domain-header";2666    const headText = document.createElement("div");2667    headText.className = "domain-header-text";2668    const eyebrow = document.createElement("div");2669    eyebrow.className = "domain-eyebrow";2670    eyebrow.textContent = "Saved for this site";2671    const domName = document.createElement("div");2672    domName.className = "domain-name";2673    domName.textContent = securityOriginLabel;2674    headText.append(eyebrow, domName);2675    domHdr.appendChild(headText);2676    if (!options.isSignup) {2677      const actions = document.createElement("div");2678      actions.className = "domain-header-actions";26792680      // Search shortcut — same idea as type-to-search below, but visible so2681      // the user can discover that another entry is reachable from a2682      // single-match platter. Sits to the left of the create button.2683      const searchBtn = document.createElement("button");2684      searchBtn.className = "domain-search-btn";2685      searchBtn.type = "button";2686      searchBtn.setAttribute("aria-label", "Search for a different entry");2687      searchBtn.title = "Search for a different entry";2688      searchBtn.innerHTML = searchSvgStr();2689      searchBtn.addEventListener("click", (e) => {2690        e.stopPropagation();2691        query = "";2692        renderList();2693      });2694      actions.appendChild(searchBtn);26952696      const addBtn = document.createElement("button");2697      addBtn.className = "domain-add-btn";2698      addBtn.type = "button";2699      addBtn.setAttribute("aria-label", "Create new entry");2700      addBtn.title = "Create new entry";2701      addBtn.textContent = "+";2702      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2703      actions.appendChild(addBtn);27042705      domHdr.appendChild(actions);2706    }2707    container.appendChild(domHdr);27082709    const platter = document.createElement("div");2710    platter.className = "silver-platter";2711    let capabilityActionClaimed = false;2712    const claimCapabilityAction = () => {2713      if (!options.capability) return true;2714      if (capabilityActionClaimed) return false;2715      capabilityActionClaimed = true;2716      return true;2717    };27182719    const titleEl = document.createElement("div");2720    titleEl.className = "sp-title";2721    titleEl.textContent = entry.title;2722    platter.appendChild(titleEl);27232724    if (entry.email) {2725      const emailEl = document.createElement("div");2726      emailEl.className = "sp-identity-row";2727      const emailLbl = document.createElement("span");2728      emailLbl.className = "sp-identity-label";2729      emailLbl.textContent = "email";2730      const emailVal = document.createElement("span");2731      emailVal.className = "sp-username";2732      emailVal.textContent = entry.email;2733      emailEl.append(emailLbl, emailVal);2734      platter.appendChild(emailEl);2735    }27362737    if (entry.username) {2738      const userEl = document.createElement("div");2739      userEl.className = "sp-identity-row";2740      const userLbl = document.createElement("span");2741      userLbl.className = "sp-identity-label";2742      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2743      const userVal = document.createElement("span");2744      userVal.className = "sp-username";2745      userVal.textContent = entry.username;2746      userEl.append(userLbl, userVal);2747      platter.appendChild(userEl);2748    }27492750    const fillBtn = document.createElement("button");2751    fillBtn.className = "sp-fill-btn";2752    fillBtn.type = "button";2753    fillBtn.textContent = "Fill credentials";2754    fillBtn.addEventListener("click", () => {2755      if (fillBtn.disabled || !claimCapabilityAction()) return;2756      fillBtn.disabled = true;2757      fillBtn.classList.add("filled");2758      fillBtn.innerHTML = checkSvgStr();2759      // Fire the fill, then exit via the standard exit animation. The fill2760      // itself is async (handled in index.ts) — by 400ms the form is filled2761      // and the popup begins its exit. Total dwell from click to host2762      // removal: 400ms + 130ms (exit animation) = 530ms.2763      onSelect(entry.id);2764      setTimeout(() => dismiss(), 400);2765    });2766    platter.appendChild(fillBtn);27672768    const actionsGroup = document.createElement("div");2769    actionsGroup.className = "sp-actions-group";2770    const actionsLabel = document.createElement("div");2771    actionsLabel.className = "sp-actions-label";2772    actionsLabel.textContent = "Copy";2773    actionsGroup.appendChild(actionsLabel);27742775    const actions = document.createElement("div");2776    actions.className = "sp-actions";2777    actionsGroup.appendChild(actions);27782779    if (entry.email) {2780      const copyEmail = document.createElement("button");2781      copyEmail.className = "sp-action-btn";2782      copyEmail.type = "button";2783      copyEmail.title = "Copy email";2784      copyEmail.textContent = "Email";2785      copyEmail.addEventListener("click", async (e) => {2786        e.stopPropagation();2787        let alreadyWritten = false;2788        try {2789          await navigator.clipboard.writeText(entry.email!);2790          alreadyWritten = true;2791        } catch (err) {2792          console.warn("[Peach] clipboard write denied:", err);2793        }2794        const resp = await chrome.runtime.sendMessage({2795          type: "COPY",2796          payload: { text: entry.email, label: "Email", alreadyWritten },2797        }).catch(() => null) as { ok?: boolean } | null;2798        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2799        else flashCopyError(copyEmail);2800      });2801      actions.appendChild(copyEmail);2802    }28032804    const copyU = document.createElement("button");2805    copyU.className = "sp-action-btn";2806    copyU.type = "button";2807    const usernameIsEmail = entry.username?.includes("@") ?? false;2808    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2809    copyU.textContent = usernameIsEmail ? "Email" : "Username";2810    copyU.disabled = !entry.username;2811    copyU.addEventListener("click", async (e) => {2812      e.stopPropagation();2813      if (!entry.username) return;2814      let alreadyWritten = false;2815      try {2816        await navigator.clipboard.writeText(entry.username);2817        alreadyWritten = true;2818      } catch (err) {2819        console.warn("[Peach] clipboard write denied:", err);2820      }2821      const resp = await chrome.runtime.sendMessage({2822        type: "COPY",2823        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2824      }).catch(() => null) as { ok?: boolean } | null;2825      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2826      else flashCopyError(copyU);2827    });2828    actions.appendChild(copyU);28292830    const copyP = document.createElement("button");2831    copyP.className = "sp-action-btn";2832    copyP.type = "button";2833    copyP.title = "Copy password";2834    copyP.textContent = "Password";2835    copyP.addEventListener("click", async (e) => {2836      e.stopPropagation();2837      if (!claimCapabilityAction()) return;2838      const resp = await chrome.runtime.sendMessage({2839        type: "GET_ENTRY_FOR_FILL",2840        payload: { id: entry.id, capability: options.capability },2841      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2842      if (!resp?.ok || !resp.data?.password) {2843        showEntryAccessError();2844        if (options.capability) dismiss();2845        return;2846      }2847      let alreadyWritten = false;2848      try {2849        await navigator.clipboard.writeText(resp.data.password);2850        alreadyWritten = true;2851      } catch (err) {2852        console.warn("[Peach] clipboard write denied:", err);2853      }2854      const copyResp = await chrome.runtime.sendMessage({2855        type: "COPY",2856        payload: { text: resp.data.password, label: "Password", alreadyWritten },2857      }).catch(() => null) as { ok?: boolean } | null;2858      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2859      else flashCopyError(copyP);2860      if (options.capability) dismiss();2861    });2862    actions.appendChild(copyP);28632864    let trayEl: HTMLDivElement | null = null;2865    let trayInterval: ReturnType<typeof setInterval> | null = null;28662867    function closeTray() {2868      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2869      trayEl?.remove();2870      trayEl = null;2871    }2872    // Register so dismiss() will close the tray and clear the interval2873    // even if the user dismisses without explicitly closing the tray.2874    cleanupHooks.push(closeTray);28752876    async function openTOTPTray() {2877      // Fetch the current TOTP code from the background. The raw base32 seed2878      // never enters the content script (SEV-3-C): we receive the live 6-digit2879      // code plus the seconds remaining, count down locally, and re-fetch a2880      // fresh code only when the 30s window rolls over.2881      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2882        const r = await chrome.runtime.sendMessage({2883          type: "GET_ENTRY_FOR_FILL",2884          payload: { id: entry.id, capability: options.capability },2885        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2886        if (!r?.ok || !r.data?.totpCode) { showEntryAccessError(); return null; }2887        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2888      }2889      let current = await fetchCode();2890      if (!current) return;28912892      trayEl = document.createElement("div");2893      trayEl.className = "sp-tray";28942895      const label = document.createElement("span");2896      label.className = "sp-tray-label";2897      label.textContent = "2FA";2898      trayEl.appendChild(label);28992900      const codeEl = document.createElement("div");2901      codeEl.className = "sp-totp-code";2902      trayEl.appendChild(codeEl);29032904      const ringNs = "http://www.w3.org/2000/svg";2905      const ring = document.createElementNS(ringNs, "svg");2906      ring.setAttribute("class", "sp-totp-ring");2907      ring.setAttribute("viewBox", "0 0 24 24");2908      const trackC = document.createElementNS(ringNs, "circle");2909      trackC.setAttribute("class", "ring-track");2910      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2911      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2912      const fillC = document.createElementNS(ringNs, "circle");2913      fillC.setAttribute("class", "ring-fill");2914      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2915      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2916      fillC.setAttribute("stroke-linecap", "round");2917      fillC.setAttribute("stroke-dasharray", "62.83");2918      ring.append(trackC, fillC);2919      trayEl.appendChild(ring);29202921      const copyBtn = document.createElement("button");2922      copyBtn.className = "sp-totp-copy";2923      copyBtn.type = "button";2924      copyBtn.textContent = "Copy";2925      trayEl.appendChild(copyBtn);29262927      function render() {2928        const { code, remaining } = current!;2929        // Group as "847 291" — easier to read than "847291"2930        codeEl.textContent = code.length === 62931          ? `${code.slice(0, 3)} ${code.slice(3)}`2932          : code;2933        // Ring fills counter-clockwise as time elapses: dashoffset goes from2934        // 0 (full ring) to 62.83 (empty) over the 30s window.2935        const fraction = (30 - remaining) / 30;2936        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2937      }2938      render();2939      trayInterval = setInterval(async () => {2940        if (!current) return;2941        current = { code: current.code, remaining: current.remaining - 1 };2942        // Window rolled over — pull a fresh code from the background.2943        if (current.remaining <= 0) {2944          const next = await fetchCode();2945          current = next ?? { code: current.code, remaining: 30 };2946        }2947        render();2948      }, 1000);29492950      copyBtn.addEventListener("click", async (e) => {2951        e.stopPropagation();2952        const code = current?.code;2953        if (!code) return;2954        let alreadyWritten = false;2955        try {2956          await navigator.clipboard.writeText(code);2957          alreadyWritten = true;2958        } catch (err) {2959          console.warn("[Peach] clipboard write denied:", err);2960        }2961        const resp = await chrome.runtime.sendMessage({2962          type: "COPY",2963          payload: { text: code, label: "TOTP", alreadyWritten },2964        }).catch(() => null) as { ok?: boolean } | null;2965        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2966        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2967      });29682969      platter.appendChild(trayEl);2970    }29712972    const editBtn = document.createElement("button");2973    editBtn.className = "sp-action-btn sp-action-edit";2974    editBtn.type = "button";2975    editBtn.title = "Edit entry";2976    editBtn.textContent = "Edit";2977    editBtn.addEventListener("click", (e) => {2978      e.stopPropagation();2979      closeTray();2980      void renderInlineEdit(entry);2981    });2982    actions.appendChild(editBtn);29832984    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2985    // "···" toggle was zero-savings (the toggle button took the same space2986    // the "2FA" label needed) and made the code one extra click away.2987    if (entry.hasTotp && !options.capability) void openTOTPTray();29882989    platter.appendChild(actionsGroup);2990    container.appendChild(platter);2991  }29922993  /** Raw TOTP seeds, password history, and passkeys stay inside extension-owned UI. */2994  async function renderInlineEdit(summary: SelectorEntry) {2995    currentMode = "edit";2996    container.innerHTML = "";29972998    const wrap = document.createElement("div");2999    wrap.className = "create-form-wrap";3000    const head = document.createElement("div");3001    head.className = "create-head";3002    const back = document.createElement("button");3003    back.className = "back-btn";3004    back.type = "button";3005    back.title = "Cancel";3006    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>`;3007    back.addEventListener("click", () => renderSilverPlatter(summary));3008    const label = document.createElement("div");3009    label.className = "create-label";3010    label.textContent = "Edit entry";3011    head.append(back, label);3012    wrap.appendChild(head);30133014    const body = document.createElement("div");3015    body.className = "create-body";3016    const loading = document.createElement("div");3017    loading.className = "empty-hint";3018    loading.textContent = "loading…";3019    body.appendChild(loading);3020    wrap.appendChild(body);3021    container.appendChild(wrap);30223023    const response = await chrome.runtime.sendMessage({3024      type: "GET_ENTRY_FOR_FILL",3025      payload: { id: summary.id, capability: options.capability },3026    }).catch(() => null) as {3027      ok?: boolean;3028      data?: {3029        title?: string;3030        username?: string;3031        email?: string;3032        password?: string;3033        url?: string;3034      };3035    } | null;3036    if (!response?.ok || !response.data) {3037      loading.textContent = "Could not access this entry. Open Peach to check it.";3038      return;3039    }3040    body.innerHTML = "";30413042    function field(labelText: string, value: string, type: "text" | "password" = "text") {3043      const group = document.createElement("div");3044      group.className = "f-group";3045      const fieldLabel = document.createElement("div");3046      fieldLabel.className = "f-label";3047      fieldLabel.textContent = labelText;3048      const input = document.createElement("input");3049      input.className = "f-input";3050      input.type = type;3051      input.value = value;3052      input.autocomplete = type === "password" ? "new-password" : "off";3053      group.append(fieldLabel, input);3054      body.appendChild(group);3055      return input;3056    }30573058    const entry = response.data;3059    const titleInput = field("title", entry.title ?? summary.title);3060    const originalUrl = (entry.url ?? summary.url ?? "").trim();3061    const urlInput = field("url", originalUrl);3062    const usernameInput = field("username", entry.username ?? summary.username ?? "");3063    const emailInput = field("email", entry.email ?? summary.email ?? "");3064    const passwordInput = field("password", entry.password ?? "", "password");30653066    const generator = createSmartGenerator({3067      policy: detectPasswordPolicy(),3068      initialPassword: entry.password,3069      onChange: (password) => { passwordInput.value = password; },3070    });3071    generator.root.hidden = true;3072    const generatorToggle = document.createElement("button");3073    generatorToggle.className = "gen-toggle-link";3074    generatorToggle.type = "button";3075    generatorToggle.textContent = "⚙ generate";3076    generatorToggle.addEventListener("click", () => {3077      generator.root.hidden = !generator.root.hidden;3078      generatorToggle.textContent = generator.root.hidden ? "⚙ generate" : "☰ hide generator";3079    });3080    body.append(generatorToggle, generator.root);30813082    const actions = document.createElement("div");3083    actions.className = "f-row";3084    const save = document.createElement("button");3085    save.className = "save-btn";3086    save.type = "button";3087    save.textContent = "Save changes";3088    save.style.flex = "1";3089    const cancel = document.createElement("button");3090    cancel.className = "gen-btn";3091    cancel.type = "button";3092    cancel.textContent = "cancel";3093    cancel.addEventListener("click", () => renderSilverPlatter(summary));3094    actions.append(save, cancel);3095    body.appendChild(actions);30963097    save.addEventListener("click", async () => {3098      save.disabled = true;3099      save.textContent = "Saving…";3100      const url = urlInput.value.trim();3101      const patch = {3102        title: titleInput.value.trim(),3103        ...(url !== originalUrl ? { url } : {}),3104        username: usernameInput.value.trim(),3105        email: emailInput.value.trim() || undefined,3106        password: passwordInput.value,3107      };3108      const update = await chrome.runtime.sendMessage({3109        type: "UPDATE_ENTRY",3110        payload: { id: summary.id, patch },3111      }).catch(() => null) as { ok?: boolean; error?: string } | null;3112      if (!update?.ok) {3113        save.disabled = false;3114        save.textContent = "Save changes";3115        const error = document.createElement("div");3116        error.className = "empty-hint";3117        error.textContent = update?.error ?? "couldn't save this entry";3118        body.appendChild(error);3119        setTimeout(() => error.remove(), 3000);3120        return;3121      }3122      renderSilverPlatter({3123        ...summary,3124        title: patch.title,3125        url,3126        username: patch.username,3127        email: patch.email,3128      });3129    });31303131    queueMicrotask(() => titleInput.focus());3132  }31333134  function renderLocked() {3135    container.innerHTML = "";31363137    // Domain header (same as list view)3138    const domHdr = document.createElement("div");3139    domHdr.className = "domain-header";3140    const eyebrow = document.createElement("div");3141    eyebrow.className = "domain-eyebrow";3142    eyebrow.textContent = "vault locked";3143    const domName = document.createElement("div");3144    domName.className = "domain-name";3145    domName.textContent = securityOriginLabel;3146    domHdr.append(eyebrow, domName);3147    container.appendChild(domHdr);31483149    const wrap = document.createElement("div");3150    wrap.className = "locked-wrap";31513152    // Icon + label row3153    const head = document.createElement("div"); head.className = "locked-head";3154    const icon = document.createElement("div"); icon.className = "locked-icon";3155    icon.innerHTML = keySvgStr();3156    const title = document.createElement("div"); title.className = "locked-title";3157    title.textContent = "unlock to autofill";3158    head.append(icon, title);31593160    // The master password is NEVER collected in page-hosted DOM. A malicious3161    // page can observe keystrokes on the shared DOM event stream (a capture-3162    // phase listener registered before Peach injects sees every key before any3163    // stopImmediatePropagation), which would leak the vault's root secret3164    // (audit HIGH). Instead, route unlocking to the trusted extension popup,3165    // where keystrokes are isolated from the page. After the user unlocks3166    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill3167    // automatically (see content/index.ts), so the flow resumes on its own.3168    const sub = document.createElement("div");3169    sub.className = "locked-sub";3170    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";31713172    const openBtn = document.createElement("button");3173    openBtn.className = "locked-btn";3174    openBtn.type = "button";3175    openBtn.textContent = "Open Peach to unlock";3176    openBtn.addEventListener("click", () => {3177      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});3178      openBtn.textContent = "opening Peach…";3179      openBtn.disabled = true;3180      // openPopup() can't always open programmatically (browser/version/gesture3181      // limits); reset so the user can retry or click the toolbar icon.3182      setTimeout(() => {3183        if (openBtn.isConnected) {3184          openBtn.textContent = "Open Peach to unlock";3185          openBtn.disabled = false;3186        }3187      }, 2500);3188    });31893190    wrap.append(head, sub, openBtn);3191    container.appendChild(wrap);3192  }31933194  function handleKeyDown(e: KeyboardEvent) {3195    // PCH-01-007: reject page-synthesised KeyboardEvents — only genuine3196    // keystrokes may drive selection/fill. A page hosting an open selector could3197    // otherwise dispatch ArrowDown/Enter at `document` to fill without user intent.3198    if (!e.isTrusted) return;3199    if (options.locked) {3200      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3201      return;3202    }3203    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter" || currentMode === "identity-helper" || currentMode === "edit") {3204      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3205      return;3206    }3207    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");3208    const count = allEntryEls.length;3209    const activeElement = shadow.activeElement ?? document.activeElement;3210    if (activeElement === searchInput) {3211      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }3212      if (count === 0) return;3213      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;3214    }3215    if (count === 0) return;3216    switch (e.key) {3217      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;3218      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;3219      case "Enter": {3220        if (focusedIndex >= 0) {3221          const el = allEntryEls[focusedIndex] as HTMLElement;3222          const id = el.dataset.id;3223          if (id) { onSelect(id); dismiss(); }3224          else if (el.classList.contains("is-new") || !id) {3225            // "New entry" row (last item, no data-id)3226            showCreateForm();3227          }3228        }3229        break;3230      }3231      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;3232    }3233  }32343235  document.addEventListener("keydown", handleKeyDown);32363237  // Type-to-search from the silver platter. A printable single-character3238  // keystroke (no modifier) seeds the search query and switches into the3239  // list view, so the user can pivot to a different entry without first3240  // clicking the search icon. Capture phase so the anchor input does not3241  // receive the character before we hijack it.3242  const silverPlatterTypeHandler = (e: KeyboardEvent) => {3243    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3244    if (currentMode !== "silver-platter") return;3245    if (e.ctrlKey || e.metaKey || e.altKey) return;3246    if (e.key.length !== 1) return;3247    e.preventDefault();3248    e.stopImmediatePropagation();3249    query = e.key;3250    // MV-2: type-to-search is an explicit gesture — load the vault-wide list.3251    void ensureSearchableLoaded(renderList);3252    renderList();3253  };3254  document.addEventListener("keydown", silverPlatterTypeHandler, true);3255  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));32563257  const identityHelperTypeHandler = (e: KeyboardEvent) => {3258    if (!e.isTrusted) return; // PCH-01-007: ignore page-synthesised keys3259    if (currentMode !== "identity-helper") return;3260    if (e.ctrlKey || e.metaKey || e.altKey) return;3261    const active = (shadow.activeElement ?? document.activeElement) as Element | null;3262    if (active === searchInput) return;3263    if (3264      active instanceof HTMLInputElement ||3265      active instanceof HTMLTextAreaElement ||3266      (active instanceof HTMLElement && active.isContentEditable)3267    ) {3268      return;3269    }3270    if (e.key.length !== 1) return;3271    e.preventDefault();3272    e.stopImmediatePropagation();3273    query = e.key;3274    renderIdentityHelper();3275  };3276  document.addEventListener("keydown", identityHelperTypeHandler, true);3277  cleanupHooks.push(() => document.removeEventListener("keydown", identityHelperTypeHandler, true));32783279  (modalAncestor ?? document.body).appendChild(host);32803281  // position:fixed normally resolves to the viewport, but an ancestor with3282  // transform / filter / backdrop-filter / perspective / contain / will-change3283  // establishes a containing block, so "fixed" then resolves to that ancestor's3284  // padding box instead. When the host is mounted inside such an ancestor (a3285  // modal) we subtract its border-box origin so the popup still lands at the3286  // field's true viewport position. At the document root there is no such3287  // ancestor and the offset is zero.3288  function establishesFixedContainingBlock(s: CSSStyleDeclaration): boolean {3289    const has = (p: string) => { const v = s.getPropertyValue(p); return v !== "" && v !== "none"; };3290    return (3291      has("transform") || has("perspective") || has("translate") ||3292      has("rotate") || has("scale") || has("filter") ||3293      has("backdrop-filter") || has("-webkit-backdrop-filter") ||3294      /\b(transform|perspective|filter)\b/.test(s.getPropertyValue("will-change")) ||3295      /\b(paint|layout|strict|content)\b/.test(s.getPropertyValue("contain"))3296    );3297  }3298  function containingBlockOffset(): { dx: number; dy: number } {3299    let el: HTMLElement | null = host.parentElement;3300    while (el && el !== document.documentElement) {3301      const s = getComputedStyle(el);3302      if (establishesFixedContainingBlock(s)) {3303        const r = el.getBoundingClientRect();3304        return {3305          dx: r.left + (parseFloat(s.borderLeftWidth) || 0),3306          dy: r.top + (parseFloat(s.borderTopWidth) || 0),3307        };3308      }3309      el = el.parentElement;3310    }3311    return { dx: 0, dy: 0 };3312  }33133314  function updatePosition() {3315    const r = anchorEl.getBoundingClientRect();3316    const { dx, dy } = containingBlockOffset();3317    host.style.top = `${r.bottom - dy + 5}px`;3318    host.style.left = `${r.left - dx}px`;3319    host.style.width = `${popupWidth}px`;3320  }3321  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);3322  updatePosition();33233324  // observeAnchorPosition listens on window scroll, but a modal with its own3325  // internal scroll container doesn't move the window — track the modal's scroll3326  // too so the popup follows the field inside it.3327  if (modalAncestor) {3328    modalAncestor.addEventListener("scroll", updatePosition, { passive: true });3329    cleanupHooks.push(() => modalAncestor.removeEventListener("scroll", updatePosition));3330  }33313332  // Dismiss when the anchor leaves the DOM. A modal closing (or an SPA route3333  // swap) removes the field without firing blur/click, so none of the normal3334  // dismiss triggers fire and the popup would otherwise linger over nothing.3335  const removalObserver = new MutationObserver(() => {3336    if (!document.contains(anchorEl)) dismiss();3337  });3338  removalObserver.observe(document.body, { childList: true, subtree: true });3339  cleanupHooks.push(() => removalObserver.disconnect());33403341  if (options.locked) {3342    renderLocked();3343  } else if (options.isSignup && options.savedIdentities) {3344    // State 10: identity helper — signup form detected, show derived3345    // identity list (emails then usernames) instead of vault entry list.3346    renderIdentityHelper();3347  } else if (entries.length === 1 && !options.isSignup) {3348    // Silver platter (State 1): single domain match → focused fill view.3349    // Multi-match goes through renderList instead.3350    renderSilverPlatter(entries[0]!);3351  } else {3352    renderList();3353  }33543355  let exitScheduled = false;3356  function dismiss(userAction = false) {3357    // Idempotent: dismiss() can be called from multiple paths (Escape,3358    // outside click, entry select, fill success, host page nav). The exit3359    // animation must only play once and host.remove() must run exactly once.3360    if (exitScheduled) return;3361    exitScheduled = true;3362    // Detach listeners synchronously so nothing can re-trigger during the3363    // 130ms exit window (a focusin firing here would race against the3364    // dismiss-lock work in Pass 2).3365    stopObserving();3366    document.removeEventListener("click", outsideClick, { capture: true });3367    document.removeEventListener("keydown", handleKeyDown);3368    for (const cleanup of cleanupHooks) {3369      try { cleanup(); } catch { /* defensive — one hook must not block others */ }3370    }3371    if (userAction) options.onDismiss?.();3372    container.classList.add("is-exiting");3373    setTimeout(() => host.remove(), 130);3374  }33753376  function outsideClick(ev: MouseEvent) {3377    const path = ev.composedPath();3378    // Never dismiss when clicking the anchor field itself — that click is3379    // what triggered the selector to open, and the user may click the field3380    // again to re-focus it without intending to close the selector.3381    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3382  }3383  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler3384  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33853386  return dismiss;3387}33883389export function showTOTPSelector(3390  anchorEl: HTMLInputElement,3391  entries: SelectorEntry[],3392  onFill: (id: string) => void,3393  options: { domain?: string; onDismiss?: () => void } = {}3394): () => void {3395  const host = document.createElement("div");3396  host.style.cssText = "position: absolute; z-index: 2147483647;";3397  host.style.setProperty("--peach-accent", accentHex);3398  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3399  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3400  const shadow = host.attachShadow({ mode: "closed" });34013402  const style = shadow.appendChild(document.createElement("style"));3403  style.textContent = SELECTOR_STYLES;34043405  const rect = anchorEl.getBoundingClientRect();3406  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3407  host.style.left = `${rect.left + window.scrollX}px`;3408  const popupWidth = Math.min(Math.max(rect.width, 300), 360);3409  host.style.width = `${popupWidth}px`;34103411  const container = shadow.appendChild(document.createElement("div"));3412  container.className = "peach-inline-popup";3413  container.setAttribute("data-theme", popupTheme);34143415  const domain = options.domain ?? location.hostname.replace(/^www\./, "");3416  const current = entries.filter((entry) => entry.hasTotp);3417  let focusedIndex = current.length === 1 ? 0 : -1;34183419  function updatePosition() {3420    const r = anchorEl.getBoundingClientRect();3421    host.style.top = `${r.bottom + window.scrollY + 5}px`;3422    host.style.left = `${r.left + window.scrollX}px`;3423    host.style.width = `${popupWidth}px`;3424  }34253426  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);34273428  function choose(entry: SelectorEntry) {3429    onFill(entry.id);3430    dismiss();3431  }34323433  function render() {3434    container.innerHTML = "";34353436    const domHdr = document.createElement("div");3437    domHdr.className = "domain-header";3438    const headText = document.createElement("div");3439    headText.className = "domain-header-text";3440    const eyebrow = document.createElement("div");3441    eyebrow.className = "domain-eyebrow";3442    eyebrow.textContent = "2FA code";3443    const domName = document.createElement("div");3444    domName.className = "domain-name";3445    domName.textContent = domain;3446    headText.append(eyebrow, domName);3447    domHdr.appendChild(headText);3448    container.appendChild(domHdr);34493450    if (current.length === 1) {3451      const entry = current[0]!;3452      const platter = document.createElement("div");3453      platter.className = "silver-platter";34543455      const title = document.createElement("div");3456      title.className = "sp-title";3457      title.textContent = entry.title;3458      platter.appendChild(title);34593460      const sub = document.createElement("div");3461      sub.className = "sp-username";3462      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3463      platter.appendChild(sub);34643465      const fill = document.createElement("button");3466      fill.className = "sp-fill-btn";3467      fill.type = "button";3468      fill.textContent = "Fill 2FA code";3469      fill.addEventListener("click", () => choose(entry));3470      platter.appendChild(fill);34713472      container.appendChild(platter);3473      requestAnimationFrame(() => fill.focus({ preventScroll: true }));3474      return;3475    }34763477    const results = document.createElement("div");3478    results.className = "results";3479    container.appendChild(results);34803481    for (let i = 0; i < current.length; i++) {3482      const entry = current[i]!;3483      const row = document.createElement("div");3484      row.className = `entry${i === focusedIndex ? " focused" : ""}`;3485      row.dataset.index = String(i);3486      row.setAttribute("tabindex", "-1");34873488      const icon = document.createElement("div");3489      icon.className = "entry-icon";3490      icon.innerHTML = keySvgStr();3491      row.appendChild(icon);3492      const info = document.createElement("div");3493      info.className = "entry-info";3494      const title = document.createElement("div");3495      title.className = "entry-title";3496      title.textContent = entry.title;3497      const sub = document.createElement("div");3498      sub.className = "entry-sub";3499      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";3500      info.append(title, sub);3501      row.appendChild(info);35023503      const badge = document.createElement("span");3504      badge.className = "totp-badge";3505      badge.textContent = "Fill";3506      row.appendChild(badge);3507      row.addEventListener("click", () => choose(entry));3508      results.appendChild(row);3509    }3510  }35113512  function setFocused(index: number) {3513    focusedIndex = index;3514    container.querySelectorAll(".entry").forEach((el, i) => {3515      el.classList.toggle("focused", i === focusedIndex);3516      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });3517    });3518  }35193520  function handleKeyDown(e: KeyboardEvent) {3521    if (e.key === "Escape" || e.key === "Tab") {3522      e.preventDefault();3523      dismiss(true);3524      return;3525    }3526    if (current.length === 0) return;3527    if (e.key === "Enter") {3528      e.preventDefault();3529      choose(current[Math.max(0, focusedIndex)]!);3530      return;3531    }3532    if (current.length === 1) return;3533    if (e.key === "ArrowDown") {3534      e.preventDefault();3535      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);3536    } else if (e.key === "ArrowUp") {3537      e.preventDefault();3538      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);3539    }3540  }35413542  let exitScheduled = false;3543  function dismiss(userAction = false) {3544    if (exitScheduled) return;3545    exitScheduled = true;3546    stopObserving();3547    document.removeEventListener("click", outsideClick, { capture: true });3548    document.removeEventListener("keydown", handleKeyDown);3549    if (userAction) options.onDismiss?.();3550    container.classList.add("is-exiting");3551    setTimeout(() => host.remove(), 130);3552  }35533554  function outsideClick(ev: MouseEvent) {3555    const path = ev.composedPath();3556    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3557  }35583559  document.addEventListener("keydown", handleKeyDown);3560  document.body.appendChild(host);3561  render();3562  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);35633564  return dismiss;3565}35663567export interface CardSelectorEntry {3568  id: string;3569  title: string;3570  cardholderName?: string;3571  last4?: string;3572  expMonth?: string;3573  expYear?: string;3574  network?: import("../shared/types").CardNetwork;3575}35763577interface CardSelectorOptions {3578  domain?: string;3579  capability?: string;3580  /** Caller-provided fill — receives the full card payload from the SW. */3581  onFill: (entry: import("../shared/types").VaultEntry) => void;3582  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */3583  onDismiss?: () => void;3584}35853586/**3587 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn3588 * passkey create or get. Renders as a fixed-position floating popup (no3589 * field anchor needed — passkeys don't require a focused input). Uses the3590 * same theme tokens and entrance animation as all other inline popup states.3591 */3592export function showPasskeyProGate(): void {3593  const domain = location.hostname.replace(/^www\./, "");35943595  const host = document.createElement("div");3596  host.setAttribute("data-peach-passkey-gate", "1");3597  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";3598  const shadow = host.attachShadow({ mode: "closed" });35993600  const style = document.createElement("style");3601  style.textContent = `3602    :host { all: initial; }3603    .gate-wrap {3604      position: fixed;3605      top: 50%;3606      left: 50%;3607      transform: translate(-50%, -50%);3608      width: 280px;3609      pointer-events: auto;3610      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;3611    }3612    @keyframes g-in {3613      from { opacity:0; transform: translate(-50%,-52%); }3614      to   { opacity:1; transform: translate(-50%,-50%); }3615    }3616    .gate-wrap.is-exiting {3617      animation: g-out 130ms ease-in forwards;3618    }3619    @keyframes g-out {3620      to { opacity:0; transform: translate(-50%,-52%); }3621    }3622    .gate {3623      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3624      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3625      border-radius: 12px;3626      box-shadow: 0 12px 48px rgba(0,0,0,0.75);3627      padding: 16px;3628      font-family: Inter, sans-serif;3629    }3630    .gate-header {3631      display: flex;3632      align-items: center;3633      gap: 7px;3634      margin-bottom: 12px;3635      padding-bottom: 10px;3636      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3637    }3638    .gate-domain {3639      font-size: 12px;3640      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3641      font-family: "IBM Plex Mono", monospace;3642      overflow: hidden;3643      text-overflow: ellipsis;3644      white-space: nowrap;3645    }3646    .gate-title {3647      font-size: 14px;3648      font-weight: 500;3649      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3650      margin-bottom: 6px;3651    }3652    .gate-subtitle {3653      font-size: 12px;3654      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3655      line-height: 1.5;3656      margin-bottom: 14px;3657    }3658    .gate-btn {3659      display: block;3660      width: 100%;3661      padding: 9px 0;3662      border-radius: 8px;3663      border: none;3664      cursor: pointer;3665      font-size: 13px;3666      font-family: Inter, sans-serif;3667      font-weight: 500;3668      transition: opacity 100ms;3669      margin-bottom: 7px;3670      text-align: center;3671    }3672    .gate-btn:last-child { margin-bottom: 0; }3673    .gate-btn--accent {3674      background: ${accentHex};3675      color: #fff;3676    }3677    .gate-btn--accent:hover { opacity: 0.88; }3678    .gate-btn--ghost {3679      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3680      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3681    }3682    .gate-btn--ghost:hover { opacity: 0.75; }3683    .backdrop {3684      position: fixed;3685      inset: 0;3686      pointer-events: auto;3687    }3688  `;3689  shadow.appendChild(style);36903691  const backdrop = document.createElement("div");3692  backdrop.className = "backdrop";3693  shadow.appendChild(backdrop);36943695  const wrap = document.createElement("div");3696  wrap.className = "gate-wrap";3697  shadow.appendChild(wrap);36983699  const gate = document.createElement("div");3700  gate.className = "gate";3701  wrap.appendChild(gate);37023703  // Header: peach icon + domain3704  const header = document.createElement("div");3705  header.className = "gate-header";3706  const icon = document.createElement("span");3707  icon.innerHTML = peachIconSvg();3708  const domainEl = document.createElement("span");3709  domainEl.className = "gate-domain";3710  domainEl.textContent = domain;3711  header.append(icon, domainEl);3712  gate.appendChild(header);37133714  const title = document.createElement("div");3715  title.className = "gate-title";3716  title.textContent = "Passkeys are part of Peach Pro.";3717  gate.appendChild(title);37183719  const subtitle = document.createElement("div");3720  subtitle.className = "gate-subtitle";3721  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3722  gate.appendChild(subtitle);37233724  const upgradeBtn = document.createElement("button");3725  upgradeBtn.className = "gate-btn gate-btn--accent";3726  upgradeBtn.type = "button";3727  upgradeBtn.textContent = "Upgrade to Pro";3728  gate.appendChild(upgradeBtn);37293730  const laterBtn = document.createElement("button");3731  laterBtn.className = "gate-btn gate-btn--ghost";3732  laterBtn.type = "button";3733  laterBtn.textContent = "Not right now";3734  gate.appendChild(laterBtn);37353736  function dismiss() {3737    wrap.classList.add("is-exiting");3738    setTimeout(() => host.remove(), 130);3739  }37403741  upgradeBtn.addEventListener("click", () => {3742    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3743    dismiss();3744  });3745  laterBtn.addEventListener("click", dismiss);3746  backdrop.addEventListener("click", dismiss);37473748  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3749    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3750  });37513752  document.body.appendChild(host);3753}37543755/**3756 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3757 * detector sees the page invoke navigator.credentials.create(); content/index.ts3758 * checks vault + decline state then calls this. "Save passkey to Peach"3759 * initiates the popup-context credential flow; "Not now" records a 30-day3760 * decline for the domain so we don't re-show on every page reload.3761 */3762export function showPasskeyRegistrationOffer(args: {3763  rpId: string;3764  rpName?: string;3765  userName?: string;3766  userDisplayName?: string;3767}): void {3768  const domain = location.hostname.replace(/^www\./, "");3769  const displayName = args.rpName || domain;37703771  const host = document.createElement("div");3772  host.setAttribute("data-peach-passkey-offer", "1");3773  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3774  const shadow = host.attachShadow({ mode: "closed" });37753776  const style = document.createElement("style");3777  style.textContent = `3778    :host { all: initial; }3779    .offer-wrap {3780      position: fixed;3781      top: 16px;3782      right: 16px;3783      width: 320px;3784      pointer-events: auto;3785      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3786    }3787    @keyframes o-in {3788      from { opacity: 0; transform: translateY(-6px); }3789      to   { opacity: 1; transform: translateY(0); }3790    }3791    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3792    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3793    .offer {3794      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3795      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3796      border-radius: 12px;3797      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3798      padding: 14px 14px 12px;3799      font-family: Inter, sans-serif;3800      position: relative;3801    }3802    .offer-close {3803      position: absolute;3804      top: 8px;3805      right: 8px;3806      width: 18px;3807      height: 18px;3808      border: none;3809      background: transparent;3810      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3811      cursor: pointer;3812      font-size: 14px;3813      line-height: 1;3814      padding: 0;3815    }3816    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3817    .offer-header {3818      display: flex;3819      align-items: center;3820      gap: 7px;3821      margin-bottom: 8px;3822      padding-bottom: 8px;3823      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3824    }3825    .offer-domain {3826      font-size: 12px;3827      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3828      font-family: "IBM Plex Mono", monospace;3829      overflow: hidden;3830      text-overflow: ellipsis;3831      white-space: nowrap;3832    }3833    .offer-title {3834      font-size: 13px;3835      font-weight: 500;3836      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3837      margin-bottom: 4px;3838    }3839    .offer-subtitle {3840      font-size: 11px;3841      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3842      line-height: 1.45;3843      margin-bottom: 12px;3844    }3845    .offer-btn {3846      display: block;3847      width: 100%;3848      padding: 8px 0;3849      border-radius: 7px;3850      border: none;3851      cursor: pointer;3852      font-size: 12px;3853      font-family: Inter, sans-serif;3854      font-weight: 500;3855      transition: opacity 100ms;3856      margin-bottom: 6px;3857      text-align: center;3858    }3859    .offer-btn:last-child { margin-bottom: 0; }3860    .offer-btn--accent { background: ${accentHex}; color: #fff; }3861    .offer-btn--accent:hover { opacity: 0.88; }3862    .offer-btn--ghost {3863      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3864      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3865    }3866    .offer-btn--ghost:hover { opacity: 0.75; }3867  `;3868  shadow.appendChild(style);38693870  const wrap = document.createElement("div");3871  wrap.className = "offer-wrap";3872  shadow.appendChild(wrap);38733874  const offer = document.createElement("div");3875  offer.className = "offer";3876  wrap.appendChild(offer);38773878  const closeBtn = document.createElement("button");3879  closeBtn.className = "offer-close";3880  closeBtn.type = "button";3881  closeBtn.setAttribute("aria-label", "Dismiss");3882  closeBtn.textContent = "✕";3883  offer.appendChild(closeBtn);38843885  const header = document.createElement("div");3886  header.className = "offer-header";3887  const icon = document.createElement("span");3888  icon.innerHTML = peachIconSvg();3889  const domainEl = document.createElement("span");3890  domainEl.className = "offer-domain";3891  domainEl.textContent = domain;3892  header.append(icon, domainEl);3893  offer.appendChild(header);38943895  const title = document.createElement("div");3896  title.className = "offer-title";3897  title.textContent = "This site supports passkeys.";3898  offer.appendChild(title);38993900  const subtitle = document.createElement("div");3901  subtitle.className = "offer-subtitle";3902  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3903  offer.appendChild(subtitle);39043905  const saveBtn = document.createElement("button");3906  saveBtn.className = "offer-btn offer-btn--accent";3907  saveBtn.type = "button";3908  saveBtn.textContent = "Save passkey to Peach";3909  offer.appendChild(saveBtn);39103911  const laterBtn = document.createElement("button");3912  laterBtn.className = "offer-btn offer-btn--ghost";3913  laterBtn.type = "button";3914  laterBtn.textContent = "Not now";3915  offer.appendChild(laterBtn);39163917  function dismiss(decline: boolean) {3918    if (decline) {3919      chrome.runtime.sendMessage({3920        type: "PASSKEY_OFFER_DECLINE",3921        payload: { domain },3922      }).catch(() => {});3923    }3924    wrap.classList.add("is-exiting");3925    setTimeout(() => host.remove(), 130);3926  }39273928  saveBtn.addEventListener("click", () => {3929    chrome.runtime.sendMessage({3930      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3931      payload: {3932        rpId: args.rpId,3933        rpName: args.rpName ?? displayName,3934        userName: args.userName ?? "user",3935        userDisplayName: args.userDisplayName,3936      },3937    }).catch(() => {});3938    dismiss(false);3939  });3940  laterBtn.addEventListener("click", () => dismiss(true));3941  closeBtn.addEventListener("click", () => dismiss(true));39423943  document.body.appendChild(host);3944}39453946/**3947 * State 11 — passkey available indicator. Shown when the user lands on a3948 * domain for which they already have a stored passkey. Tells them where to3949 * find it (the entry already shows in the vault list); the "Sign in with3950 * passkey" button opens the popup so they can use the platform authenticator3951 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3952 * the actual sign-in transparently, so this banner is informational only.3953 */3954export function showPasskeyAvailable(args: {3955  rpId: string;3956  userName: string;3957  fromBrowser?: "chrome" | "firefox";3958  currentBrowser?: "chrome" | "firefox" | "unknown";3959}): void {3960  const domain = location.hostname.replace(/^www\./, "");3961  const crossBrowser =3962    args.fromBrowser &&3963    args.currentBrowser &&3964    args.currentBrowser !== "unknown" &&3965    args.fromBrowser !== args.currentBrowser;39663967  const host = document.createElement("div");3968  host.setAttribute("data-peach-passkey-available", "1");3969  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3970  const shadow = host.attachShadow({ mode: "closed" });39713972  const style = document.createElement("style");3973  style.textContent = `3974    :host { all: initial; }3975    .avail-wrap {3976      position: fixed;3977      top: 16px;3978      right: 16px;3979      width: 320px;3980      pointer-events: auto;3981      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3982    }3983    @keyframes a-in {3984      from { opacity: 0; transform: translateY(-6px); }3985      to   { opacity: 1; transform: translateY(0); }3986    }3987    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3988    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3989    .avail {3990      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3991      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3992      border-radius: 12px;3993      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3994      padding: 14px 14px 12px;3995      font-family: Inter, sans-serif;3996      position: relative;3997    }3998    .avail-close {3999      position: absolute;4000      top: 8px;4001      right: 8px;4002      width: 18px;4003      height: 18px;4004      border: none;4005      background: transparent;4006      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};4007      cursor: pointer;4008      font-size: 14px;4009      line-height: 1;4010      padding: 0;4011    }4012    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }4013    .avail-header {4014      display: flex;4015      align-items: center;4016      gap: 7px;4017      margin-bottom: 8px;4018      padding-bottom: 8px;4019      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};4020    }4021    .avail-domain {4022      font-size: 12px;4023      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};4024      font-family: "IBM Plex Mono", monospace;4025    }4026    .avail-label {4027      font-size: 9px;4028      letter-spacing: 0.16em;4029      text-transform: uppercase;4030      color: ${accentHex};4031      margin-bottom: 4px;4032    }4033    .avail-user {4034      font-size: 13px;4035      font-weight: 500;4036      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};4037      margin-bottom: 12px;4038      overflow: hidden;4039      text-overflow: ellipsis;4040      white-space: nowrap;4041    }4042    .avail-cross {4043      font-size: 11px;4044      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};4045      line-height: 1.45;4046      margin-bottom: 12px;4047      padding: 8px;4048      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};4049      border-radius: 6px;4050    }4051    .avail-btn {4052      display: block;4053      width: 100%;4054      padding: 8px 0;4055      border-radius: 7px;4056      border: none;4057      cursor: pointer;4058      font-size: 12px;4059      font-family: Inter, sans-serif;4060      font-weight: 500;4061      transition: opacity 100ms;4062      margin-bottom: 6px;4063      text-align: center;4064    }4065    .avail-btn:last-child { margin-bottom: 0; }4066    .avail-btn--accent { background: ${accentHex}; color: #fff; }4067    .avail-btn--accent:hover { opacity: 0.88; }4068    .avail-btn--ghost {4069      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};4070      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};4071    }4072    .avail-btn--ghost:hover { opacity: 0.75; }4073  `;4074  shadow.appendChild(style);40754076  const wrap = document.createElement("div");4077  wrap.className = "avail-wrap";4078  shadow.appendChild(wrap);40794080  const avail = document.createElement("div");4081  avail.className = "avail";4082  wrap.appendChild(avail);40834084  const closeBtn = document.createElement("button");4085  closeBtn.className = "avail-close";4086  closeBtn.type = "button";4087  closeBtn.setAttribute("aria-label", "Dismiss");4088  closeBtn.textContent = "✕";4089  avail.appendChild(closeBtn);40904091  const header = document.createElement("div");4092  header.className = "avail-header";4093  const icon = document.createElement("span");4094  icon.innerHTML = peachIconSvg();4095  const domainEl = document.createElement("span");4096  domainEl.className = "avail-domain";4097  domainEl.textContent = domain;4098  header.append(icon, domainEl);4099  avail.appendChild(header);41004101  const label = document.createElement("div");4102  label.className = "avail-label";4103  label.textContent = "PASSKEY";4104  avail.appendChild(label);41054106  const user = document.createElement("div");4107  user.className = "avail-user";4108  user.textContent = args.userName;4109  avail.appendChild(user);41104111  if (crossBrowser) {4112    const cross = document.createElement("div");4113    cross.className = "avail-cross";4114    cross.textContent =4115      args.fromBrowser === "chrome"4116        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."4117        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";4118    avail.appendChild(cross);4119  }41204121  const signInBtn = document.createElement("button");4122  signInBtn.className = "avail-btn avail-btn--accent";4123  signInBtn.type = "button";4124  signInBtn.textContent = "Sign in with passkey";4125  avail.appendChild(signInBtn);41264127  const passwordBtn = document.createElement("button");4128  passwordBtn.className = "avail-btn avail-btn--ghost";4129  passwordBtn.type = "button";4130  passwordBtn.textContent = "Use password instead";4131  avail.appendChild(passwordBtn);41324133  function dismiss() {4134    wrap.classList.add("is-exiting");4135    setTimeout(() => host.remove(), 130);4136  }41374138  signInBtn.addEventListener("click", () => {4139    // On Chrome: the user clicking the page's own Sign-in button is what4140    //   triggers webAuthenticationProxy → existing background flow handles it.4141    //   Our button just dismisses since the page itself drives auth.4142    // On Firefox: cross-browser passkeys can't be used, so we just dismiss4143    //   and surface the entry for manual reference (popup view).4144    dismiss();4145    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});4146  });4147  passwordBtn.addEventListener("click", dismiss);4148  closeBtn.addEventListener("click", dismiss);41494150  document.body.appendChild(host);4151}41524153/**4154 * State 7 — card silver platter. Single-card focused fill view rendered4155 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the4156 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes4157 * so card and login flows render identically. Multi-card list view is a4158 * follow-up; today this picks the first card.4159 */4160export function showCardSelector(4161  anchorEl: HTMLInputElement,4162  cards: CardSelectorEntry[],4163  options: CardSelectorOptions4164): () => void {4165  if (cards.length === 0) return () => {};4166  const card = cards[0]!;4167  let capabilityActionClaimed = false;4168  const claimCapabilityAction = () => {4169    if (!options.capability) return true;4170    if (capabilityActionClaimed) return false;4171    capabilityActionClaimed = true;4172    return true;4173  };41744175  const host = document.createElement("div");4176  host.style.cssText = "position: absolute; z-index: 2147483647;";4177  host.style.setProperty("--peach-accent", accentHex);4178  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));4179  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));4180  const shadow = host.attachShadow({ mode: "closed" });41814182  const style = shadow.appendChild(document.createElement("style"));4183  style.textContent = SELECTOR_STYLES;41844185  const rect = anchorEl.getBoundingClientRect();4186  host.style.top = `${rect.bottom + window.scrollY + 5}px`;4187  host.style.left = `${rect.left + window.scrollX}px`;4188  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;41894190  const container = shadow.appendChild(document.createElement("div"));4191  container.className = "peach-inline-popup";4192  container.setAttribute("data-theme", popupTheme);41934194  // Domain header — eyebrow communicates the card context, not the site4195  const domHdr = document.createElement("div");4196  domHdr.className = "domain-header";4197  const eyebrow = document.createElement("div");4198  eyebrow.className = "domain-eyebrow";4199  eyebrow.textContent = "Pay with Peach";4200  const domName = document.createElement("div");4201  domName.className = "domain-name";4202  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");4203  domHdr.append(eyebrow, domName);4204  container.appendChild(domHdr);42054206  const platter = document.createElement("div");4207  platter.className = "card-platter";42084209  if (card.network && card.network !== "unknown") {4210    const net = document.createElement("div");4211    net.className = "cp-network";4212    net.textContent = card.network;4213    platter.appendChild(net);4214  }42154216  const nick = document.createElement("div");4217  nick.className = "cp-nickname";4218  nick.textContent = card.title;4219  platter.appendChild(nick);42204221  if (card.last4) {4222    const l4 = document.createElement("div");4223    l4.className = "cp-last4";4224    l4.textContent = `•••• ${card.last4}`;4225    platter.appendChild(l4);4226  }42274228  const meta = document.createElement("div");4229  meta.className = "cp-meta";4230  if (card.cardholderName) {4231    const name = document.createElement("span");4232    name.textContent = card.cardholderName;4233    meta.appendChild(name);4234  }4235  if (card.expMonth && card.expYear) {4236    if (card.cardholderName) {4237      const sep = document.createElement("span");4238      sep.className = "cp-meta-sep";4239      sep.textContent = "·";4240      meta.appendChild(sep);4241    }4242    const exp = document.createElement("span");4243    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;4244    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;4245    meta.appendChild(exp);4246  }4247  if (meta.childElementCount > 0) platter.appendChild(meta);42484249  const fillWrap = document.createElement("div");4250  fillWrap.className = "cp-fill-wrap";4251  const fillBtn = document.createElement("button");4252  fillBtn.className = "sp-fill-btn";4253  fillBtn.type = "button";4254  fillBtn.textContent = "Fill card details";4255  fillBtn.addEventListener("click", async () => {4256    if (fillBtn.disabled || !claimCapabilityAction()) return;4257    fillBtn.disabled = true;4258    fillBtn.classList.add("filled");4259    fillBtn.innerHTML = checkSvgStr();4260    const resp = await chrome.runtime.sendMessage({4261      type: "GET_ENTRY_FOR_FILL",4262      // MV-1: explicit user click to fill this card's details.4263      payload: { id: card.id, capability: options.capability },4264    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4265    if (resp?.ok && resp.data) options.onFill(resp.data);4266    setTimeout(() => dismiss(), 400);4267  });4268  fillWrap.appendChild(fillBtn);4269  platter.appendChild(fillWrap);42704271  // Secondary actions — copy number, copy CVC, dismiss4272  const actions = document.createElement("div");4273  actions.className = "sp-actions";42744275  function flashBtn(b: HTMLButtonElement) {4276    b.classList.add("flashed");4277    setTimeout(() => b.classList.remove("flashed"), 700);4278  }42794280  // M3/QUA-005: clipboard + background COPY both failed — show user.4281  function flashCopyError(b: HTMLButtonElement) {4282    const original = b.textContent ?? "";4283    b.textContent = "Blocked";4284    b.classList.add("flashed");4285    setTimeout(() => {4286      b.classList.remove("flashed");4287      if (b.isConnected) b.textContent = original;4288    }, 1200);4289  }42904291  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {4292    if (!claimCapabilityAction()) return null;4293    const resp = await chrome.runtime.sendMessage({4294      type: "GET_ENTRY_FOR_FILL",4295      // MV-1: explicit user action on a card the user opened in Peach's UI.4296      payload: { id: card.id, capability: options.capability },4297    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;4298    const full = resp?.ok && resp.data ? resp.data : null;4299    if (options.capability) dismiss();4300    return full;4301  }43024303  const copyNum = document.createElement("button");4304  copyNum.className = "sp-action-btn";4305  copyNum.type = "button";4306  copyNum.title = "Copy card number";4307  copyNum.textContent = "Copy number";4308  copyNum.addEventListener("click", async (e) => {4309    e.stopPropagation();4310    const full = await fetchFullCard();4311    if (!full?.cardNumber) return;4312    let alreadyWritten = false;4313    try {4314      await navigator.clipboard.writeText(full.cardNumber);4315      alreadyWritten = true;4316    } catch (err) {4317      console.warn("[Peach] clipboard write denied:", err);4318    }4319    const resp = await chrome.runtime.sendMessage({4320      type: "COPY",4321      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },4322    }).catch(() => null) as { ok?: boolean } | null;4323    if (alreadyWritten || resp?.ok) flashBtn(copyNum);4324    else flashCopyError(copyNum);4325  });4326  actions.appendChild(copyNum);43274328  const copyCvc = document.createElement("button");4329  copyCvc.className = "sp-action-btn";4330  copyCvc.type = "button";4331  copyCvc.title = "Copy CVC";4332  copyCvc.textContent = "Copy CVC";4333  copyCvc.addEventListener("click", async (e) => {4334    e.stopPropagation();4335    const full = await fetchFullCard();4336    if (!full?.cvc) return;4337    let alreadyWritten = false;4338    try {4339      await navigator.clipboard.writeText(full.cvc);4340      alreadyWritten = true;4341    } catch (err) {4342      console.warn("[Peach] clipboard write denied:", err);4343    }4344    const resp = await chrome.runtime.sendMessage({4345      type: "COPY",4346      payload: { text: full.cvc, label: "CVC", alreadyWritten },4347    }).catch(() => null) as { ok?: boolean } | null;4348    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);4349    else flashCopyError(copyCvc);4350  });4351  actions.appendChild(copyCvc);43524353  const closeBtn = document.createElement("button");4354  closeBtn.className = "sp-action-btn";4355  closeBtn.type = "button";4356  closeBtn.title = "Dismiss";4357  closeBtn.textContent = "✕";4358  closeBtn.addEventListener("click", (e) => {4359    e.stopPropagation();4360    dismiss(true);4361  });4362  actions.appendChild(closeBtn);43634364  platter.appendChild(actions);4365  container.appendChild(platter);43664367  document.body.appendChild(host);4368  function updatePosition() {4369    const r = anchorEl.getBoundingClientRect();4370    host.style.top = `${r.bottom + window.scrollY + 5}px`;4371    host.style.left = `${r.left + window.scrollX}px`;4372  }4373  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);43744375  function onKeyDown(e: KeyboardEvent) {4376    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }4377  }4378  document.addEventListener("keydown", onKeyDown);43794380  let exitScheduled = false;4381  function dismiss(userAction = false) {4382    if (exitScheduled) return;4383    exitScheduled = true;4384    stopObserving();4385    document.removeEventListener("click", outsideClick, { capture: true });4386    document.removeEventListener("keydown", onKeyDown);4387    if (userAction) options.onDismiss?.();4388    container.classList.add("is-exiting");4389    setTimeout(() => host.remove(), 130);4390  }43914392  function outsideClick(ev: MouseEvent) {4393    const path = ev.composedPath();4394    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);4395  }4396  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);43974398  return dismiss;4399}