inject.ts

148.2 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { generatePassword } from "../shared/generate";14import { generateTOTP } from "../crypto/totp";15import { detectPasswordPolicy } from "./policy";1617let accentHex = "#E8956D";18let popupTheme: "dark" | "light" = "dark";19chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {20  const data = resp?.data;21  const name = data?.accentColor ?? "peach";22  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";23  popupTheme = data?.theme === "light" ? "light" : "dark";24});2526// 8-digit hex alpha helpers for the accent-derived shadow tokens.27// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing28// two hex digits as the alpha channel.29function withAlpha(hex: string, alpha: string): string {30  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS31  // always exposes 6-digit hex, so this is a guard against future changes32  // shipping shorthand colors that would silently break the var injection.33  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;34}3536export interface SelectorEntry {37  id: string;38  title: string;39  username?: string;40  email?: string;41  url?: string;42  hasTotp?: boolean;43  /** True when the entry also has a passkey credential attached. */44  hasPasskey?: boolean;45}4647interface SelectorOptions {48  domain?: string;49  searchableEntries?: SelectorEntry[];50  /** True when shown on a signup form — changes header label and entry-click behaviour */51  isSignup?: boolean;52  /**53   * Derived identity list (emails then usernames) for signup mode (State 10).54   * When present, renderIdentityHelper() is used instead of renderList().55   */56  savedIdentities?: SavedIdentity[];57  /**58   * Called after the user picks a saved identity (signup mode only) or59   * after successfully saving a new entry on a signup form.60   * Lets the caller fill the visible username + password fields.61   */62  onFillFields?: (username: string, password: string) => void;63  /**64   * When true, show an inline unlock form instead of the entries list.65   * Used when the vault is locked so the user can unlock without opening66   * the popup.67   */68  locked?: boolean;69  /**70   * Called after a successful inline unlock — the caller should re-query71   * entries and re-open the selector with real data.72   */73  onUnlocked?: () => void;74  /**75   * Called when the user explicitly dismisses the selector (Escape, Tab, or76   * click outside) — NOT when an entry is selected or on auto-close.77   * Used by the caller to suppress spurious reopens on the same field.78   */79  onDismiss?: () => void;80}8182function getDomainFromUrl(url: string): string {83  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }84}8586function keySvgStr(): string {87  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>`;88}8990function plusSvgStr(): string {91  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>`;92}9394function searchSvgStr(): string {95  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>`;96}9798function backSvgStr(): string {99  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>`;100}101102function peachIconSvg(): string {103  // Peach body stays brand-peach regardless of `accentHex` — a sage or104  // sky accent must not turn the autofill icon green or blue. Accent105  // color still tints surrounding glow/hover halos below.106  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>`;107}108109function checkSvgStr(): string {110  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>`;111}112113function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {114  const { hostname, origin } = location;115  const parts = hostname.split(".");116  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",117    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",118    "oidc", "federation", "saml", "cas", "ldap"];119  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());120  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;121  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);122  return { origin, title, loginSubdomain };123}124125/**126 * Shows a bottom-of-page toast after filling credentials when the entry has127 * never matched the current site — offering to add the current origin to the128 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.129 */130export function showRememberSiteToast(131  pageDomain: string,132  entryId: string,133): void {134  const host = document.createElement("div");135  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";136  host.style.setProperty("--peach-accent", accentHex);137  const shadow = host.attachShadow({ mode: "closed" });138139  const style = document.createElement("style");140  style.textContent = `141    .bar {142      display:flex;align-items:center;gap:10px;padding:10px 14px;143      background:#131109;border:1px solid rgba(240,232,216,0.09);144      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);145      font-family:Inter,sans-serif;white-space:nowrap;146      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;147    }148    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }149    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }150    .yes {151      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;152      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;153    }154    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }155    .no {156      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;157      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;158    }159  `;160  shadow.appendChild(style);161162  const bar = document.createElement("div"); bar.className = "bar";163  const txt = document.createElement("span"); txt.className = "txt";164  txt.textContent = `Remember ${pageDomain} for this entry?`;165  const yesBtn = document.createElement("button"); yesBtn.className = "yes";166  yesBtn.textContent = "Remember";167  yesBtn.addEventListener("click", async () => {168    await chrome.runtime.sendMessage({169      type: "ADD_ADDITIONAL_URL",170      payload: { id: entryId, url: location.origin },171    });172    host.remove();173  });174  const noBtn = document.createElement("button"); noBtn.className = "no";175  noBtn.textContent = "Not now";176  noBtn.addEventListener("click", () => host.remove());177  bar.append(txt, yesBtn, noBtn);178  shadow.appendChild(bar);179  document.body.appendChild(host);180  setTimeout(() => host.remove(), 9000);181}182183interface SmartGenerator {184  root: HTMLElement;185  getPassword: () => string;186  /** Copy the current password to the clipboard with the standard pulse UX. */187  copy: () => Promise<void>;188}189190interface SmartGeneratorOptions {191  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */192  policy: PasswordPolicy;193  /**194   * Seed value: used as the displayed password without regenerating, e.g. the195   * password the user already typed into the page. The generator still196   * regenerates the moment any control changes.197   */198  initialPassword?: string;199  /** Fires every time the password regenerates (initial + on changes). */200  onChange?: (pw: string) => void;201}202203/**204 * Build the inline-popup smart-password generator. Mirrors the main popup's205 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset206 * pills + a policy hint that names the constraints Peach detected on the207 * page. Writing this in pure DOM rather than reusing the Solid component208 * keeps the content-script bundle small.209 */210function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {211  const policy = opts.policy ?? {};212213  // Start at site max (strongest password the site accepts), fall back to 64214  let length = policy.maxLength ?? 64;215  if (policy.minLength) length = Math.max(length, policy.minLength);216  if (length < 8) length = 8;217  if (length > 128) length = 128;218219  let upper = true;220  let lower = true;221  let numbers = true;222  let symbols = !policy.forbidsSymbols;223  if (policy.requiresSymbols) symbols = true;224  const forbiddenChars = policy.forbiddenChars ?? "";225226  let password = "";227228  const root = document.createElement("div");229  root.className = "pwgen-block";230231  const displayRow = root.appendChild(document.createElement("div"));232  displayRow.className = "pwgen-display-row";233  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;234  output.type = "text";235  output.className = "pwgen-output";236  output.setAttribute("autocomplete", "off");237  output.setAttribute("spellcheck", "false");238  output.setAttribute("autocorrect", "off");239  output.setAttribute("autocapitalize", "off");240241  const regenBtn = displayRow.appendChild(document.createElement("button"));242  regenBtn.className = "pwgen-icon-btn";243  regenBtn.type = "button";244  regenBtn.setAttribute("aria-label", "Regenerate password");245  regenBtn.title = "Regenerate";246  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>`;247248  const copyBtn = displayRow.appendChild(document.createElement("button"));249  copyBtn.className = "pwgen-icon-btn";250  copyBtn.type = "button";251  copyBtn.setAttribute("aria-label", "Copy password");252  copyBtn.title = "Copy";253  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>`;254255  const controls = root.appendChild(document.createElement("div"));256  controls.className = "pwgen-controls-row";257  const slider = controls.appendChild(document.createElement("input"));258  slider.type = "range";259  slider.className = "pwgen-slider";260  slider.min = "8";261  slider.max = "128";262  slider.value = String(length);263  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));264  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));265  const lenNum = controls.appendChild(document.createElement("span"));266  lenNum.className = "pwgen-len-num pwgen-len-num--edit";267  lenNum.textContent = String(length);268  lenNum.addEventListener("click", () => {269    const li = document.createElement("input");270    li.type = "text"; li.inputMode = "numeric";271    li.className = "pwgen-len-input"; li.value = String(length);272    lenNum.replaceWith(li);273    requestAnimationFrame(() => li.select());274    function commitLenEdit() {275      const n = parseInt(li.value, 10);276      if (!isNaN(n)) {277        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));278        slider.value = String(length);279        regenerate();280      }281      lenNum.textContent = String(length);282      li.replaceWith(lenNum);283    }284    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });285    li.addEventListener("blur", commitLenEdit);286  });287288  const pills = root.appendChild(document.createElement("div"));289  pills.className = "pwgen-pills";290291  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {292    const b = document.createElement("button");293    b.type = "button";294    b.className = `pwgen-pill ${on ? "is-on" : ""}`;295    b.textContent = label;296    b.addEventListener("click", () => {297      const next = !b.classList.contains("is-on");298      b.classList.toggle("is-on", next);299      onToggle(next);300    });301    return b;302  }303  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));304  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));305  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));306  pills.appendChild(makePill("!@#", symbols, (next) => {307    // The site forbids symbols — UI lets the user override but still warn.308    symbols = next;309    regenerate();310  }));311312  // Policy hint — surfaces what Peach read off the site so the user knows the313  // generator is already tuned to it. Only shows when something interesting314  // was detected.315  const hintParts: string[] = [];316  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);317  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);318  if (policy.requiresSymbols) hintParts.push("requires symbols");319  if (policy.forbidsSymbols) hintParts.push("no symbols");320  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);321  if (hintParts.length > 0) {322    const hint = root.appendChild(document.createElement("div"));323    hint.className = "pwgen-policy-hint";324    const accent = document.createElement("span");325    accent.className = "pwgen-hint-accent";326    accent.textContent = "site rules · ";327    const text = document.createTextNode(hintParts.join(" · "));328    hint.appendChild(accent);329    hint.appendChild(text);330  }331332  function regenerate() {333    // Falls back gracefully when the user toggles every charset off — the334    // shared generator forces lowercase in that case rather than throwing.335    password = generatePassword({336      length,337      includeUppercase: upper,338      includeLowercase: lower,339      includeNumbers: numbers,340      includeSymbols: symbols,341      forbiddenChars,342    });343    output.value = password;344    opts.onChange?.(password);345  }346347  output.addEventListener("input", () => {348    password = output.value;349    length = password.length;350    slider.value = String(Math.max(8, Math.min(128, length)));351    lenNum.textContent = String(length);352    opts.onChange?.(password);353  });354355  slider.addEventListener("input", () => {356    length = parseInt(slider.value, 10);357    lenNum.textContent = String(length);358    regenerate();359  });360  regenBtn.addEventListener("click", regenerate);361362  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;363  async function copy(): Promise<void> {364    try {365      await navigator.clipboard.writeText(password);366      copyBtn.classList.add("is-copied");367      if (copyResetTimer) clearTimeout(copyResetTimer);368      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);369    } catch {370      // Clipboard API may be denied — silently no-op; user still has regen UI.371    }372  }373  copyBtn.addEventListener("click", () => { void copy(); });374375  if (opts.initialPassword) {376    password = opts.initialPassword;377    output.value = password;378    opts.onChange?.(password);379  } else {380    regenerate();381  }382383  return {384    root,385    getPassword: () => password,386    copy,387  };388}389390export function observeAnchorPosition(391  anchorEl: HTMLElement,392  onUpdate: () => void393): () => void {394  let rafId = 0;395  let burstUntil = 0;396397  const runUpdate = () => {398    rafId = 0;399    onUpdate();400    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);401  };402  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };403  const scheduleBurst = (ms = 220) => {404    burstUntil = Math.max(burstUntil, performance.now() + ms);405    scheduleUpdate();406  };407408  const resizeObserver = new ResizeObserver(() => scheduleBurst());409  resizeObserver.observe(anchorEl);410  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);411412  const mutationObserver = new MutationObserver(() => scheduleBurst());413  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });414  if (anchorEl.parentElement) {415    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });416  }417418  const onScroll = () => scheduleUpdate();419  window.addEventListener("scroll", onScroll, true);420  window.addEventListener("resize", onScroll);421  window.visualViewport?.addEventListener("resize", onScroll);422  window.visualViewport?.addEventListener("scroll", onScroll);423  anchorEl.addEventListener("focus", () => scheduleBurst());424  anchorEl.addEventListener("input", () => scheduleBurst());425426  scheduleBurst(260);427428  return () => {429    if (rafId) cancelAnimationFrame(rafId);430    resizeObserver.disconnect();431    mutationObserver.disconnect();432    window.removeEventListener("scroll", onScroll, true);433    window.removeEventListener("resize", onScroll);434    window.visualViewport?.removeEventListener("resize", onScroll);435    window.visualViewport?.removeEventListener("scroll", onScroll);436  };437}438439export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {440  const button = document.createElement("button");441  button.type = "button";442  button.setAttribute("aria-label", "Peach autofill");443  button.title = "Fill with Peach";444  button.innerHTML = peachIconSvg();445  // position: fixed is load-bearing — not absolute. Absolute positioning446  // inherits the nearest positioned ancestor's box, which on sites with447  // overflow:hidden or sticky parents clips or offsets the icon. Fixed448  // anchors to the viewport and escapes all parent layout.449  button.style.cssText = `450    position: fixed; z-index: 2147483646;451    width: 26px; height: 26px; cursor: pointer;452    pointer-events: auto; border: none; padding: 3px;453    display: inline-flex; align-items: center; justify-content: center;454    background: transparent; border-radius: 999px;455    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;456    opacity: 0;457  `;458  button.addEventListener("mouseenter", () => {459    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;460    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;461    button.style.transform = "scale(1.08)";462  });463  button.addEventListener("mouseleave", () => {464    button.style.background = "transparent";465    button.style.boxShadow = "none";466    button.style.transform = "none";467  });468  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });469  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });470471  document.body.appendChild(button);472473  function updatePosition() {474    const rect = field.getBoundingClientRect();475    if (rect.width === 0 || rect.height === 0) {476      button.style.opacity = "0"; button.style.pointerEvents = "none";477      return;478    }479    const sz = 26;480    const inset = Math.max(5, Math.min(10, rect.height * 0.22));481    const top = rect.top + rect.height / 2 - sz / 2;482    // Clamp left so the icon stays fully inside the field's right edge, never483    // spilling onto an adjacent sibling button.484    const minLeft = rect.left + 4;485    const left = Math.max(minLeft, rect.right - sz - inset);486    // Hide if the field is too narrow to fit the icon cleanly (< 40px)487    if (rect.width < 40) {488      button.style.opacity = "0"; button.style.pointerEvents = "none";489      return;490    }491    button.style.top = `${top}px`;492    button.style.left = `${left}px`;493    button.style.opacity = "1"; button.style.pointerEvents = "auto";494  }495  updatePosition();496  requestAnimationFrame(() => { button.style.opacity = "1"; });497  const stopObserving = observeAnchorPosition(field, updatePosition);498  return () => { stopObserving(); button.remove(); };499}500501// All theme-dependent values resolve through tokens scoped to502// .peach-inline-popup[data-theme="dark|light"]. Accent variables503// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)504// are identical in both themes — only surface tokens differ. See505// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the506// theme switch — only literal brand-peach in peachIconSvg may stay raw.507const SELECTOR_STYLES = `508  :host { all: initial; }509  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }510511  .peach-inline-popup[data-theme="dark"] {512    --peach-bg:           #1a1410;513    --peach-bg-card:      #221c16;514    --peach-text:         #f5f0ea;515    --peach-text-dim:     #8a7a6a;516    --peach-text-muted:   #4a3a2a;517    --peach-border:       rgba(255,255,255,0.07);518    --peach-input-bg:     rgba(255,255,255,0.05);519    --peach-input-border: rgba(255,255,255,0.08);520  }521  .peach-inline-popup[data-theme="light"] {522    --peach-bg:           #fdf8f4;523    --peach-bg-card:      #f5ede4;524    --peach-text:         #1c1310;525    --peach-text-dim:     #6b5a4a;526    --peach-text-muted:   #a89080;527    --peach-border:       rgba(0,0,0,0.08);528    --peach-input-bg:     rgba(0,0,0,0.04);529    --peach-input-border: rgba(0,0,0,0.10);530  }531532  .peach-inline-popup {533    background: var(--peach-bg);534    border: 1px solid var(--peach-border-accent, var(--peach-border));535    border-radius: 14px;536    overflow: hidden;537    box-shadow:538      0 8px 40px var(--peach-glow, transparent),539      0 2px 12px rgba(0,0,0,0.5);540    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;541    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;542    transition: height 220ms cubic-bezier(0.16,1,0.3,1);543  }544  /* Light theme: shadow against a light page is too strong otherwise — drop both545     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */546  .peach-inline-popup[data-theme="light"] {547    box-shadow:548      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),549      0 2px 12px rgba(0,0,0,0.12);550  }551  .peach-inline-popup.is-exiting {552    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;553    pointer-events: none;554  }555556  @keyframes peach-enter {557    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }558    65%  { opacity: 1; filter: blur(0); }559    100% { opacity: 1; transform: translateY(0) scale(1); }560  }561  @keyframes peach-exit {562    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }563    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }564  }565  @keyframes peach-slide-in {566    from { opacity: 0; transform: translateX(12px); }567    to   { opacity: 1; transform: translateX(0); }568  }569  @keyframes peach-slide-back {570    from { opacity: 0; transform: translateX(-12px); }571    to   { opacity: 1; transform: translateX(0); }572  }573  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }574  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }575576  /* Domain header */577  .domain-header {578    padding: 9px 13px 7px;579    border-bottom: 1px solid var(--peach-border);580    display: flex; align-items: center; justify-content: space-between;581    gap: 8px;582  }583  .domain-header-text {584    display: flex; flex-direction: column; gap: 2px;585    min-width: 0; flex: 1;586  }587  .domain-eyebrow {588    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;589    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;590  }591  .domain-name {592    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);593    font-family: "IBM Plex Mono", monospace;594    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;595  }596  .domain-header-actions {597    display: inline-flex; align-items: center; gap: 5px;598    flex-shrink: 0;599  }600  .domain-add-btn,601  .domain-search-btn {602    flex-shrink: 0;603    width: 22px; height: 22px;604    display: inline-flex; align-items: center; justify-content: center;605    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);606    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);607    border-radius: 6px;608    color: var(--peach-accent);609    cursor: pointer; padding: 0;610    transition: background 120ms, border-color 120ms, transform 80ms;611    font-family: "IBM Plex Mono", monospace;612    font-size: 14px; line-height: 1;613  }614  .domain-add-btn:hover,615  .domain-search-btn:hover {616    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);617    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);618    transform: scale(1.06);619  }620  .domain-add-btn:active,621  .domain-search-btn:active { transform: scale(0.96); }622623  /* Search */624  .search-wrap {625    padding: 9px 12px 7px;626    border-bottom: 1px solid var(--peach-border);627  }628  .search {629    width: 100%; background: var(--peach-input-bg);630    border: 1px solid var(--peach-input-border);631    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;632    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;633    transition: border-color 120ms, box-shadow 120ms;634  }635  .search:focus {636    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);637    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);638  }639  .search::placeholder { color: var(--peach-text-muted); }640641  /* Results */642  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }643  .results::-webkit-scrollbar { display: none; }644645  /* Entry rows */646  .entry {647    display: flex; align-items: center; padding: 8px 12px;648    cursor: pointer; border-bottom: 1px solid var(--peach-border);649    transition: background 70ms; position: relative; outline: none;650  }651  .entry:last-child { border-bottom: none; }652  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }653  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }654  .entry.focused::before {655    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;656    width: 2px; border-radius: 2px;657    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);658  }659660  .entry-icon {661    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;662    background: var(--peach-input-bg); border: 1px solid var(--peach-border);663    display: flex; align-items: center; justify-content: center;664    overflow: hidden; margin-right: 10px;665  }666  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }667  .entry-icon.is-new {668    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);669    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);670    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);671  }672673  .entry-info { flex: 1; min-width: 0; }674  .entry-title {675    font-size: 12.5px; color: var(--peach-text);676    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;677    line-height: 1.3;678  }679  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }680  .entry-sub {681    font-size: 10px; color: var(--peach-text-dim);682    font-family: "IBM Plex Mono", monospace;683    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;684    margin-top: 1px;685  }686687  .totp-badge {688    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;689    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);690    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);691    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;692  }693  .passkey-badge {694    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;695    border-radius: 4px;696    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);697    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);698    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);699    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;700  }701702  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }703704  .empty-hint {705    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);706    font-family: "IBM Plex Mono", monospace;707  }708709  /* Create form */710  .create-form-wrap {711    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;712  }713  .create-head {714    display: flex; align-items: center; gap: 8px;715    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);716  }717  .back-btn {718    background: transparent; border: none; cursor: pointer;719    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;720    display: flex; align-items: center; line-height: 0;721    transition: color 100ms, background 100ms;722  }723  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }724  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }725  /* minmax(0, 1fr) caps the grid track at the popup width — without it,726     long monospace content (e.g. a 60-char generated password) would727     auto-size the track wider than the popup and overflow the right edge. */728  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }729  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }730  .f-label {731    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;732    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;733  }734  .f-input {735    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);736    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;737    font-size: 11px; font-family: "IBM Plex Mono", monospace;738    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;739  }740  .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); }741  .f-input::placeholder { color: var(--peach-text-muted); }742  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }743  .f-row { display: flex; gap: 6px; }744  .f-row .f-input { flex: 1; min-width: 0; }745  .gen-btn {746    padding: 0 10px; border-radius: 7px; border: none;747    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);748    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);749    font-size: 10px; font-family: "IBM Plex Mono", monospace;750    cursor: pointer; white-space: nowrap; flex-shrink: 0;751    display: flex; align-items: center; gap: 4px;752    transition: background 100ms;753  }754  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }755  .gen-toggle-link {756    background: none; border: none; padding: 2px 0;757    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);758    font-size: 10px; font-family: "IBM Plex Mono", monospace;759    cursor: pointer; text-align: left; transition: color 100ms;760  }761  .gen-toggle-link:hover { color: var(--peach-accent); }762  .save-btn {763    width: 100%; padding: 8px; border-radius: 8px; border: none;764    background: var(--peach-accent); color: #fff; font-size: 12px;765    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;766    transition: background 120ms, box-shadow 120ms, transform 80ms;767    letter-spacing: 0.01em;768  }769  .save-btn:hover {770    background: color-mix(in srgb, var(--peach-accent) 82%, #000);771    box-shadow: 0 4px 20px var(--peach-glow, transparent);772  }773  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }774  .url-hint {775    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);776    font-family: "IBM Plex Mono", monospace; font-style: italic;777  }778779  /* Success */780  .success-wrap {781    display: flex; flex-direction: column; align-items: center;782    padding: 24px 16px 20px; gap: 8px;783    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;784  }785  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }786  .success-ring {787    width: 40px; height: 40px; border-radius: 50%;788    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);789    display: flex; align-items: center; justify-content: center;790  }791  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }792  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }793794  /* Silver platter (State 1 — single match) */795  .silver-platter {796    padding: 14px 14px 12px;797    display: flex; flex-direction: column; gap: 6px;798  }799  .sp-title {800    font-size: 14px; font-weight: 500; color: var(--peach-text);801    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;802    line-height: 1.25;803  }804  .sp-identity-row {805    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;806  }807  .sp-identity-label {808    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;809    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;810  }811  .sp-username {812    font-size: 12px; color: var(--peach-text-dim);813    font-family: "IBM Plex Mono", monospace;814    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;815    margin-bottom: 0;816  }817  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }818  .sp-fill-btn {819    width: 100%; padding: 11px; border-radius: 9px; border: none;820    background: var(--peach-accent); color: #fff;821    font-size: 13px; font-weight: 500; cursor: pointer;822    font-family: Inter, sans-serif; letter-spacing: 0.01em;823    display: flex; align-items: center; justify-content: center; min-height: 38px;824    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;825  }826  .sp-fill-btn:hover {827    filter: brightness(1.1);828    box-shadow: 0 4px 20px var(--peach-glow, transparent);829    transform: translateY(-1px);830  }831  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }832  .sp-fill-btn.filled {833    background: #16a34a; transform: none; filter: none;834    box-shadow: 0 4px 16px rgba(22,163,74,0.35);835    cursor: default;836  }837  .sp-fill-btn:disabled { cursor: default; }838  .sp-actions-group {839    margin-top: 6px;840    display: flex; flex-direction: column; gap: 4px;841  }842  .sp-actions-label {843    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;844    color: var(--peach-text-muted);845    font-family: "IBM Plex Mono", monospace;846    text-align: center;847  }848  .sp-actions {849    display: flex; gap: 4px; justify-content: space-between; align-items: center;850  }851  .sp-action-btn {852    flex: 1; height: 28px; border: none; border-radius: 6px;853    background: transparent; color: var(--peach-text-dim);854    font-size: 12px; cursor: pointer;855    transition: background 120ms ease, color 120ms ease;856    font-family: Inter, sans-serif; letter-spacing: 0.04em;857    display: inline-flex; align-items: center; justify-content: center; gap: 4px;858    white-space: nowrap; overflow: hidden;859  }860  .sp-action-btn:hover:not(:disabled) {861    background: color-mix(in srgb, var(--peach-text) 5%, transparent);862    color: var(--peach-text);863  }864  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }865  .sp-action-btn.flashed {866    color: var(--peach-accent);867    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);868  }869870  /* TOTP tray — shown below the silver-platter secondary actions */871  .sp-tray {872    margin-top: 8px;873    padding: 10px 12px;874    border-radius: 9px;875    background: var(--peach-input-bg);876    border: 1px solid var(--peach-input-border);877    display: flex; align-items: center; gap: 12px;878    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;879  }880  .sp-tray-label {881    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;882    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;883    flex-shrink: 0;884  }885  .sp-totp-code {886    font-size: 18px; font-weight: 500;887    color: var(--peach-text);888    font-family: "IBM Plex Mono", monospace;889    letter-spacing: 0.12em;890    flex: 1;891    text-align: center;892  }893  .sp-totp-ring {894    width: 22px; height: 22px; flex-shrink: 0;895  }896  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }897  .sp-totp-ring .ring-fill {898    stroke: var(--peach-accent);899    transition: stroke-dashoffset 1s linear;900    transform: rotate(-90deg);901    transform-origin: center;902  }903  .sp-totp-copy {904    background: transparent; border: none; cursor: pointer;905    padding: 4px 8px; border-radius: 5px;906    color: var(--peach-text-dim); font-size: 11px;907    font-family: Inter, sans-serif;908    transition: background 120ms, color 120ms;909  }910  .sp-totp-copy:hover {911    background: color-mix(in srgb, var(--peach-text) 5%, transparent);912    color: var(--peach-text);913  }914915  /* Card silver platter (State 7) — reuses .sp-* primary action classes */916  .card-platter {917    padding: 12px 14px 10px;918    display: flex; flex-direction: column; gap: 4px;919  }920  .cp-network {921    font-size: 10px; font-weight: 600;922    color: var(--peach-accent);923    letter-spacing: 0.08em; text-transform: uppercase;924    font-family: Inter, sans-serif;925  }926  .cp-nickname {927    font-size: 14px; font-weight: 500; color: var(--peach-text);928    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;929    line-height: 1.2;930  }931  .cp-last4 {932    font-size: 12px; color: var(--peach-text-dim);933    font-family: "IBM Plex Mono", monospace;934    letter-spacing: 0.04em;935    margin-top: 2px;936  }937  .cp-meta {938    font-size: 11px; color: var(--peach-text-dim);939    font-family: "IBM Plex Mono", monospace;940    margin-top: 2px;941    display: flex; gap: 10px; align-items: center;942  }943  .cp-meta-sep { opacity: 0.5; }944  .cp-fill-wrap { margin-top: 10px; }945946  /* Locked state */947  .locked-wrap {948    display: flex; flex-direction: column; align-items: stretch;949    padding: 14px 13px 13px; gap: 9px;950  }951  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }952  .locked-icon {953    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;954    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);955    display: flex; align-items: center; justify-content: center;956  }957  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }958  .locked-input {959    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);960    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;961    font-size: 11px; font-family: "IBM Plex Mono", monospace;962    outline: none; transition: border-color 120ms, box-shadow 120ms;963  }964  .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); }965  .locked-input::placeholder { color: var(--peach-text-muted); }966  .locked-btn {967    width: 100%; padding: 8px; border-radius: 8px; border: none;968    background: var(--peach-accent); color: #fff; font-size: 12px;969    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;970    transition: background 120ms;971    letter-spacing: 0.01em;972    box-shadow: 0 2px 16px var(--peach-glow, transparent);973    animation: peach-pulse-glow 2.4s ease-in-out infinite;974  }975  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }976  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }977  .locked-error {978    font-size: 10px; color: rgba(220,80,60,0.85);979    font-family: "IBM Plex Mono", monospace;980  }981982  @keyframes peach-pulse-glow {983    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }984    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),985                            0 0 48px var(--peach-glow, transparent); }986  }987988  /* ── State 10: identity helper ─────────────────────────────── */989  .identity-list {990    max-height: 192px; overflow-y: auto; padding: 4px 0;991    scrollbar-width: none;992  }993  .identity-list::-webkit-scrollbar { display: none; }994  .peach-identity-row {995    display: flex; align-items: center; gap: 10px;996    padding: 9px 12px; cursor: pointer; border-radius: 8px;997    transition: background 100ms ease;998  }999  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1000  .peach-identity-value {1001    font-family: "IBM Plex Mono", monospace; font-size: 13px;1002    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1003  }1004  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1005  .identity-alt-row {1006    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1007    border-radius: 8px; transition: background 100ms ease;1008    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1009  }1010  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1011  .identity-escape-row {1012    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1013    border-radius: 8px; transition: background 100ms ease; outline: none;1014    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1015    margin-top: 2px;1016  }1017  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1018  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1019  .identity-alt-input-wrap.open { display: flex; }1020  .identity-alt-input {1021    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1022    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1023    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1024    outline: none; transition: border-color 120ms;1025  }1026  .identity-alt-input:focus {1027    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1028    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1029  }1030  .identity-alt-confirm {1031    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1032    background: var(--peach-accent); color: #fff; font-size: 12px;1033    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1034  }1035  /* ── Generator view (after identity picked) ────────────────── */1036  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1037  .gen-confirmed {1038    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1039    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1040    border-radius: 8px;1041  }1042  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1043  .gen-confirmed-val {1044    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1045    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1046  }1047  .gen-label {1048    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1049    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1050  }1051  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1052  .gen-pw-val {1053    flex: 1; padding: 8px 10px; border-radius: 7px;1054    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1055    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1056    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1057  }1058  .gen-regen-btn {1059    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1060    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1061    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1062    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1063  }1064  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1065  .gen-fill-btn {1066    padding: 10px; border-radius: 8px; border: none;1067    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1068    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1069    transition: filter 120ms ease, transform 80ms ease;1070  }1071  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1072  .gen-fill-btn:active { transform: translateY(0); }10731074  /* ── Smart password generator (parity with main UI compact mode) ─── */1075  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1076  .pwgen-display-row {1077    display: flex; align-items: center; gap: 6px;1078    padding: 8px 10px; border-radius: 7px;1079    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1080  }1081  .pwgen-output {1082    flex: 1; min-width: 0; width: 0;1083    font-family: "IBM Plex Mono", monospace; font-size: 12px;1084    color: var(--peach-text);1085    background: transparent; border: none; outline: none; padding: 0;1086  }1087  .pwgen-icon-btn {1088    flex-shrink: 0;1089    width: 26px; height: 26px;1090    display: inline-flex; align-items: center; justify-content: center;1091    background: transparent; border: 1px solid var(--peach-input-border);1092    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1093    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1094  }1095  .pwgen-icon-btn:hover {1096    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1097    color: var(--peach-accent);1098    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1099  }1100  .pwgen-icon-btn.is-copied {1101    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1102    color: var(--peach-accent);1103    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1104  }1105  .pwgen-controls-row {1106    display: flex; align-items: center; gap: 8px;1107    flex-wrap: wrap;1108  }1109  .pwgen-slider {1110    flex: 1; min-width: 110px;1111    accent-color: var(--peach-accent);1112    cursor: pointer; height: 2px; background: transparent;1113  }1114  .pwgen-len-num {1115    font-family: "IBM Plex Mono", monospace; font-size: 11px;1116    color: var(--peach-accent); min-width: 22px; text-align: right;1117  }1118  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1119  .pwgen-len-input {1120    font-family: "IBM Plex Mono", monospace; font-size: 11px;1121    color: var(--peach-accent); width: 28px; text-align: right;1122    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1123    outline: none; padding: 0; min-width: 22px;1124  }1125  @keyframes identity-suggest-in {1126    from { opacity: 0; transform: translateY(-4px); }1127    to   { opacity: 1; transform: none; }1128  }1129  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1130    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1131  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1132  .identity-collapse-btn {1133    margin-left: auto; background: transparent; border: none; cursor: pointer;1134    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1135    line-height: 0; border-radius: 3px;1136    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1137  }1138  .identity-collapse-btn:hover { color: var(--peach-text); }1139  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1140  .identity-rows { display: grid; grid-template-rows: 1fr;1141    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1142  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1143  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1144    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1145    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1146    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1147  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1148  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1149  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1150  .identity-filter-pill {1151    padding: 2px 7px; border-radius: 999px;1152    border: 1px solid var(--peach-input-border);1153    background: transparent; color: var(--peach-text-muted);1154    font-family: "IBM Plex Mono", monospace; font-size: 9px;1155    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1156  }1157  .identity-filter-pill.is-on {1158    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1159    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1160    color: var(--peach-accent);1161  }1162  .identity-suggest-row {1163    display: flex; align-items: center; gap: 5px;1164    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1165    background: transparent; cursor: pointer; text-align: left;1166    transition: background 80ms;1167  }1168  .identity-suggest-row:hover,1169  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1170  .identity-suggest-val {1171    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1172    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1173  }1174  .identity-suggest-type {1175    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1176    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1177  }1178  .identity-suggest-type--email {1179    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1180    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1181  }1182  .identity-suggest-type--username {1183    color: var(--peach-text-muted);1184    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1185  }1186  .identity-suggest-meta {1187    font-family: "IBM Plex Mono", monospace; font-size: 9px;1188    color: var(--peach-text-muted); flex-shrink: 0;1189  }1190  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1191  .pwgen-pill {1192    padding: 3px 8px; border-radius: 999px;1193    border: 1px solid var(--peach-input-border);1194    background: transparent; color: var(--peach-text-muted);1195    font-family: "IBM Plex Mono", monospace; font-size: 9px;1196    letter-spacing: 0.06em; cursor: pointer;1197    transition: all 130ms ease;1198  }1199  .pwgen-pill.is-on {1200    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1201    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1202    color: var(--peach-accent);1203  }1204  .pwgen-pill:not(.is-on):hover {1205    color: var(--peach-text-dim);1206    border-color: var(--peach-text-muted);1207  }1208  .pwgen-policy-hint {1209    font-size: 10px; color: var(--peach-text-muted);1210    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1211    line-height: 1.3;1212  }1213  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }12141215  /* ── Save offer (after password filled) ───────────────────── */1216  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1217  .save-offer-title {1218    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1219  }1220  .save-offer-row {1221    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1222    border-radius: 7px; background: var(--peach-input-bg);1223    border: 1px solid var(--peach-input-border);1224  }1225  .save-offer-lbl {1226    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1227    font-family: "IBM Plex Mono", monospace;1228  }1229  .save-offer-val {1230    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1231    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1232  }1233  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1234  .save-offer-save {1235    flex: 1; padding: 9px; border-radius: 8px; border: none;1236    background: var(--peach-accent); color: #fff; font-size: 13px;1237    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1238  }1239  .save-offer-save:hover { filter: brightness(1.08); }1240  .save-offer-skip {1241    flex: 1; padding: 9px; border-radius: 8px; border: none;1242    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1243    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1244    font-family: Inter, sans-serif; transition: background 100ms ease;1245  }1246  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1247`;12481249export function showAutofillSelector(1250  anchorEl: HTMLInputElement,1251  entries: SelectorEntry[],1252  onSelect: (id: string) => void,1253  options: SelectorOptions = {}1254): () => void {1255  const host = document.createElement("div");1256  host.style.cssText = "position: absolute; z-index: 2147483647;";1257  host.style.setProperty("--peach-accent", accentHex);1258  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1259  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1260  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1261  const shadow = host.attachShadow({ mode: "closed" });12621263  const style = shadow.appendChild(document.createElement("style"));1264  style.textContent = SELECTOR_STYLES;12651266  const rect = anchorEl.getBoundingClientRect();1267  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1268  host.style.left = `${rect.left + window.scrollX}px`;1269  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1270  // wide single-input fields (e.g. centered email input on signup pages).1271  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1272  // expand the host after the initial measurement.1273  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1274  host.style.width = `${popupWidth}px`;12751276  const container = shadow.appendChild(document.createElement("div"));1277  container.className = "peach-inline-popup";1278  container.setAttribute("data-theme", popupTheme);12791280  const searchableEntries = options.searchableEntries ?? [];1281  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12821283  let query = "";1284  let focusedIndex = -1;1285  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1286  let searchInput: HTMLInputElement | null = null;1287  // Tracks the silver-platter entry the user pivoted away from, so the1288  // search/list header can offer a one-click way back to it. null when the1289  // popup never showed a single-match platter (e.g. multi-match list view).1290  let silverPlatterOrigin: SelectorEntry | null = null;1291  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1292  // setInterval. Add to this list — don't fan out the dismiss function.1293  const cleanupHooks: Array<() => void> = [];12941295  // Smooth height transitions whenever content changes height.1296  // ResizeObserver fires on natural height changes; we freeze the old height,1297  // then animate to the new one so the surface never jumps.1298  {1299    let prevH = 0;1300    let blocked = false;1301    const heightRo = new ResizeObserver(([entry]) => {1302      if (blocked) return;1303      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1304      if (prevH > 0 && Math.abs(h - prevH) > 1) {1305        blocked = true;1306        container.style.height = `${prevH}px`;1307        requestAnimationFrame(() => requestAnimationFrame(() => {1308          container.style.height = `${h}px`;1309          prevH = h;1310          const onEnd = (e: TransitionEvent) => {1311            if (e.propertyName !== "height") return;1312            container.style.height = "";1313            blocked = false;1314            container.removeEventListener("transitionend", onEnd);1315          };1316          container.addEventListener("transitionend", onEnd);1317        }));1318      } else {1319        prevH = h;1320      }1321    });1322    heightRo.observe(container);1323    cleanupHooks.push(() => heightRo.disconnect());1324  }13251326  // Pre-capture the anchor field value for username prefill1327  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1328  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1329  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13301331  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1332    const seen = new Set<string>();1333    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1334  }13351336  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1337    const q = value.trim().toLowerCase();1338    const deduped = uniqueEntries(source);1339    if (!q) return deduped.slice(0, 8);1340    return deduped.filter(e =>1341      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1342    ).slice(0, 12);1343  }13441345  function activeEntries(): SelectorEntry[] {1346    // When user is typing a search, filter across all known entries (domain matches + vault)1347    if (query.trim()) {1348      const merged = uniqueEntries([...entries, ...searchableEntries]);1349      return filterEntries(merged, query);1350    }1351    // Default: show domain matches; fall back to vault search when no matches1352    if (entries.length > 0) return entries;1353    return filterEntries(searchableEntries, "").slice(0, 8);1354  }13551356  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1357    const icon = document.createElement("div");1358    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1359    if (isNew) {1360      icon.innerHTML = plusSvgStr();1361    } else {1362      // Use the generic key glyph for all entries in the page-injected selector.1363      // Avoids disclosing vault domains to any third party and avoids needing1364      // to expose the browser favicon API to page context via web_accessible_resources.1365      void url;1366      icon.innerHTML = keySvgStr();1367    }1368    return icon;1369  }13701371  function renderIdentityHelper() {1372    container.innerHTML = "";1373    const identities = options.savedIdentities ?? [];13741375    // Header: "NEW ACCOUNT" + domain name1376    const hdr = container.appendChild(document.createElement("div"));1377    hdr.className = "domain-header";1378    const eyebrow = hdr.appendChild(document.createElement("div"));1379    eyebrow.className = "domain-eyebrow";1380    eyebrow.textContent = "NEW ACCOUNT";1381    const domName = hdr.appendChild(document.createElement("div"));1382    domName.className = "domain-name";1383    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13841385    // Identity rows1386    const list = container.appendChild(document.createElement("div"));1387    list.className = "identity-list";1388    for (const id of identities) {1389      const row = list.appendChild(document.createElement("div"));1390      row.className = "peach-identity-row";1391      row.setAttribute("tabindex", "-1");1392      const val = row.appendChild(document.createElement("div"));1393      val.className = "peach-identity-value";1394      val.textContent = id.value;1395      const meta = row.appendChild(document.createElement("div"));1396      meta.className = "peach-identity-meta";1397      meta.textContent = `used ${id.useCount}×`;1398      row.addEventListener("click", () => {1399        options.onFillFields?.(id.value, "");1400        renderGenerator(id.value);1401      });1402    }14031404    // Divider before "Use a different email…"1405    if (identities.length > 0) {1406      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1407    }14081409    // "Use a different email…" expandable row1410    const altRow = container.appendChild(document.createElement("div"));1411    altRow.className = "identity-alt-row";1412    altRow.textContent = "+ Use a different email…";14131414    const altInputWrap = container.appendChild(document.createElement("div"));1415    altInputWrap.className = "identity-alt-input-wrap";1416    const altInput = altInputWrap.appendChild(document.createElement("input"));1417    altInput.className = "identity-alt-input";1418    altInput.type = "email";1419    altInput.placeholder = "[email protected]";1420    altInput.setAttribute("autocomplete", "off");1421    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1422    altConfirm.className = "identity-alt-confirm";1423    altConfirm.type = "button";1424    altConfirm.textContent = "✓";14251426    function fillCustomEmail() {1427      const v = altInput.value.trim();1428      if (!v) return;1429      options.onFillFields?.(v, "");1430      renderGenerator(v);1431    }14321433    altRow.addEventListener("click", () => {1434      altRow.style.display = "none";1435      altInputWrap.classList.add("open");1436      altInput.focus();1437    });1438    altConfirm.addEventListener("click", fillCustomEmail);1439    altInput.addEventListener("keydown", (e) => {1440      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1441    });14421443    // Escape hatch: user already has a vault entry for this site but it1444    // wasn't detected (different domain, old entry, etc.). Tapping this1445    // switches to the full searchable list so they can find and fill it;1446    // selecting an entry there will trigger the remember-site toast if1447    // the domain isn't already associated.1448    if ((options.searchableEntries?.length ?? 0) > 0) {1449      const escapeRow = container.appendChild(document.createElement("div"));1450      escapeRow.className = "identity-escape-row";1451      escapeRow.textContent = "I already have an account →";1452      escapeRow.setAttribute("tabindex", "0");1453      escapeRow.addEventListener("click", () => renderList());1454      escapeRow.addEventListener("keydown", (e) => {1455        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1456      });1457    }1458  }14591460  function renderGenerator(filledEmail: string) {1461    container.innerHTML = "";1462    const sitePolicy = detectPasswordPolicy();14631464    const wrap = container.appendChild(document.createElement("div"));1465    wrap.className = "gen-view";14661467    // Header: domain + NEW ACCOUNT1468    const hdrRow = wrap.appendChild(document.createElement("div"));1469    hdrRow.className = "domain-header";1470    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1471    eyebrow2.className = "domain-eyebrow";1472    eyebrow2.textContent = "NEW ACCOUNT";1473    const domName2 = hdrRow.appendChild(document.createElement("div"));1474    domName2.className = "domain-name";1475    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14761477    // Confirmed email row1478    const conf = wrap.appendChild(document.createElement("div"));1479    conf.className = "gen-confirmed";1480    const confCheck = conf.appendChild(document.createElement("span"));1481    confCheck.className = "gen-confirmed-check";1482    confCheck.textContent = "✓";1483    const confVal = conf.appendChild(document.createElement("div"));1484    confVal.className = "gen-confirmed-val";1485    confVal.textContent = filledEmail;14861487    const lbl = wrap.appendChild(document.createElement("div"));1488    lbl.className = "gen-label";1489    lbl.textContent = "Generate a password";14901491    let currentPw = "";1492    const smartGen = createSmartGenerator({1493      policy: sitePolicy,1494      onChange: (pw) => { currentPw = pw; },1495    });1496    wrap.appendChild(smartGen.root);14971498    const fillBtn = wrap.appendChild(document.createElement("button"));1499    fillBtn.className = "gen-fill-btn";1500    fillBtn.type = "button";1501    fillBtn.textContent = "Copy & fill";1502    fillBtn.addEventListener("click", () => {1503      if (!currentPw) return;1504      options.onFillFields?.("", currentPw);1505      renderSaveOffer(filledEmail, currentPw);1506    });1507  }15081509  function renderSaveOffer(filledEmail: string, filledPassword: string) {1510    container.innerHTML = "";1511    const domain = options.domain ?? location.hostname.replace(/^www\./, "");15121513    const wrap = container.appendChild(document.createElement("div"));1514    wrap.className = "save-offer";15151516    const title = wrap.appendChild(document.createElement("div"));1517    title.className = "save-offer-title";1518    title.textContent = "Save this login to Peach?";15191520    function detailRow(label: string, value: string) {1521      const row = wrap.appendChild(document.createElement("div"));1522      row.className = "save-offer-row";1523      const lbl = row.appendChild(document.createElement("div"));1524      lbl.className = "save-offer-lbl";1525      lbl.textContent = label;1526      const val = row.appendChild(document.createElement("div"));1527      val.className = "save-offer-val";1528      val.textContent = value;1529    }15301531    detailRow("site", domain);1532    detailRow("email", filledEmail);1533    detailRow("password", "••••••••••••••••");15341535    const btns = wrap.appendChild(document.createElement("div"));1536    btns.className = "save-offer-btns";15371538    const saveBtn = btns.appendChild(document.createElement("button"));1539    saveBtn.className = "save-offer-save";1540    saveBtn.type = "button";1541    saveBtn.textContent = "Save";1542    saveBtn.addEventListener("click", async () => {1543      saveBtn.disabled = true;1544      saveBtn.textContent = "Saving…";1545      try {1546        const res = await chrome.runtime.sendMessage({1547          type: "ADD_ENTRY",1548          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1549        });1550        if ((res as { ok?: boolean }).ok) {1551          showSuccess(sTitle);1552        } else {1553          saveBtn.disabled = false;1554          saveBtn.textContent = "Save";1555        }1556      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1557    });15581559    const skipBtn = btns.appendChild(document.createElement("button"));1560    skipBtn.className = "save-offer-skip";1561    skipBtn.type = "button";1562    skipBtn.textContent = "Not now";1563    skipBtn.addEventListener("click", () => { dismiss(true); });1564  }15651566  function renderList() {1567    container.innerHTML = "";1568    focusedIndex = -1;1569    searchInput = null;1570    currentMode = "list";15711572    const current = activeEntries();15731574    // Domain header (always show) — eyebrow + domain on the left,1575    // a "+" shortcut to the create form on the right so the user is never1576    // trapped in the search list when they want to make a new entry.1577    const domHdr = document.createElement("div");1578    domHdr.className = "domain-header";1579    const headText = document.createElement("div");1580    headText.className = "domain-header-text";1581    const eyebrow = document.createElement("div");1582    eyebrow.className = "domain-eyebrow";1583    eyebrow.textContent = options.isSignup1584      ? "Sign up as"1585      : entries.length > 0 ? "Saved for this site" : "No saved login";1586    const domName = document.createElement("div");1587    domName.className = "domain-name";1588    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1589    headText.append(eyebrow, domName);1590    domHdr.appendChild(headText);15911592    if (!options.isSignup) {1593      const actions = document.createElement("div");1594      actions.className = "domain-header-actions";15951596      // Back arrow takes the place of the silver-platter's search icon when1597      // the user has pivoted away from a single-match platter — gives them1598      // a one-click way back to the original recommendation.1599      if (silverPlatterOrigin) {1600        const backBtn = document.createElement("button");1601        backBtn.className = "domain-search-btn";1602        backBtn.type = "button";1603        backBtn.setAttribute("aria-label", "Back to suggested entry");1604        backBtn.title = "Back to suggested entry";1605        backBtn.innerHTML = backSvgStr();1606        backBtn.addEventListener("click", (e) => {1607          e.stopPropagation();1608          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);1609        });1610        actions.appendChild(backBtn);1611      }16121613      const addBtn = document.createElement("button");1614      addBtn.className = "domain-add-btn";1615      addBtn.type = "button";1616      addBtn.setAttribute("aria-label", "Create new entry");1617      addBtn.title = "Create new entry";1618      addBtn.textContent = "+";1619      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1620      actions.appendChild(addBtn);16211622      domHdr.appendChild(actions);1623    }16241625    container.appendChild(domHdr);16261627    // Search — always show so user can find entries beyond the domain matches1628    const sw = document.createElement("div"); sw.className = "search-wrap";1629    searchInput = document.createElement("input");1630    searchInput.className = "search";1631    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1632    searchInput.value = query;1633    searchInput.addEventListener("input", () => {1634      query = searchInput?.value ?? "";1635      renderList();1636      searchInput?.focus();1637      searchInput?.setSelectionRange(query.length, query.length);1638    });1639    sw.appendChild(searchInput);1640    container.appendChild(sw);16411642    // Results1643    const results = document.createElement("div");1644    results.className = "results";1645    container.appendChild(results);16461647    if (current.length === 0 && entries.length > 0) {1648      // Show a hint but don't render empty entries1649    }16501651    for (let i = 0; i < current.length; i++) {1652      const e = current[i]!;1653      const entryEl = document.createElement("div");1654      entryEl.className = "entry";1655      entryEl.dataset.id = e.id;1656      entryEl.dataset.index = String(i);1657      entryEl.setAttribute("tabindex", "-1");16581659      entryEl.appendChild(makeEntryIcon(e.url));16601661      const info = document.createElement("div"); info.className = "entry-info";1662      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1663      const subEl = document.createElement("div"); subEl.className = "entry-sub";1664      const domain = e.url ? getDomainFromUrl(e.url) : "";1665      subEl.textContent = domain || e.username || "";1666      info.append(titleEl, subEl);1667      entryEl.appendChild(info);16681669      if (e.hasTotp) {1670        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1671        entryEl.appendChild(badge);1672      }1673      if (e.hasPasskey) {1674        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1675        entryEl.appendChild(badge);1676      }16771678      entryEl.addEventListener("click", () => {1679        if (options.isSignup && options.onFillFields) {1680          // Signup mode: clicking a saved identity fills the username field1681          options.onFillFields(e.username ?? "", "");1682          dismiss();1683        } else {1684          onSelect(e.id);1685          dismiss();1686        }1687      });1688      results.appendChild(entryEl);1689    }16901691    // Divider before "New entry"1692    if (current.length > 0) {1693      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1694    }16951696    // "New entry" row — always present1697    const newEl = document.createElement("div");1698    newEl.className = "entry";1699    newEl.setAttribute("tabindex", "-1");1700    newEl.appendChild(makeEntryIcon(undefined, true));17011702    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1703    const newTitle = document.createElement("div");1704    newTitle.className = "entry-title is-new";1705    newTitle.textContent = `New entry for ${sTitle}`;1706    const newSub = document.createElement("div");1707    newSub.className = "entry-sub";1708    newSub.textContent = sOrigin;1709    newInfo.append(newTitle, newSub);1710    newEl.appendChild(newInfo);1711    newEl.addEventListener("click", showCreateForm);1712    results.appendChild(newEl);17131714    // Focus search if present1715    if (searchInput) {1716      requestAnimationFrame(() => {1717        searchInput?.focus();1718        // Seed query (from type-to-search or domain-search-btn) lands at the1719        // end so the next keystroke extends it, not overwrites.1720        searchInput?.setSelectionRange(query.length, query.length);1721      });1722    }1723  }17241725  function setFocused(idx: number) {1726    const all = container.querySelectorAll<HTMLElement>(".entry");1727    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1728    focusedIndex = idx;1729    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1730  }17311732  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1733    const typed = identities.filter(s => s.type === fieldType);1734    if (!typed.length) return;1735    let collapsed = false;1736    let suppressNextFocus = false;17371738    const list = g.appendChild(document.createElement("div"));1739    list.className = "identity-suggest-list";1740    list.style.display = "none";17411742    // Collapse toggle — sits alone now that filter pills are gone1743    const collapseRow = list.appendChild(document.createElement("div"));1744    collapseRow.className = "identity-filter-row";1745    collapseRow.style.justifyContent = "flex-end";1746    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1747    collapseBtn.type = "button";1748    collapseBtn.className = "identity-collapse-btn";1749    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>`;1750    collapseBtn.addEventListener("mousedown", (e) => {1751      e.preventDefault();1752      collapsed = !collapsed;1753      collapseBtn.classList.toggle("is-collapsed", collapsed);1754      rowsWrapper.classList.toggle("is-collapsed", collapsed);1755    });17561757    const rowsWrapper = list.appendChild(document.createElement("div"));1758    rowsWrapper.className = "identity-rows";1759    const rows = rowsWrapper.appendChild(document.createElement("div"));1760    rows.className = "identity-rows-inner";17611762    function pick(value: string) {1763      inp.value = value;1764      list.style.display = "none";1765      suppressNextFocus = true;1766      inp.focus();1767    }17681769    function render() {1770      const q = inp.value.toLowerCase();1771      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1772      rows.innerHTML = "";1773      if (!filtered.length) { list.style.display = "none"; return; }1774      for (const s of filtered) {1775        const row = rows.appendChild(document.createElement("button"));1776        row.type = "button"; row.className = "identity-suggest-row";1777        const val = row.appendChild(document.createElement("span"));1778        val.className = "identity-suggest-val"; val.textContent = s.value;1779        const meta = row.appendChild(document.createElement("span"));1780        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1781        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1782        row.addEventListener("keydown", (e) => {1783          if (e.key === "ArrowDown") {1784            e.preventDefault();1785            (row.nextElementSibling as HTMLElement | null)?.focus();1786          } else if (e.key === "ArrowUp") {1787            e.preventDefault();1788            const prev = row.previousElementSibling as HTMLElement | null;1789            if (prev) prev.focus();1790            else inp.focus();1791          } else if (e.key === "Enter" || e.key === " ") {1792            e.preventDefault();1793            pick(s.value);1794          } else if (e.key === "Escape") {1795            e.preventDefault();1796            list.style.display = "none";1797            suppressNextFocus = true;1798            inp.focus();1799          }1800        });1801        row.addEventListener("blur", (e) => {1802          const rt = (e as FocusEvent).relatedTarget as Node | null;1803          if (rt && (rt === inp || list.contains(rt))) return;1804          setTimeout(() => { list.style.display = "none"; }, 150);1805        });1806      }1807      list.style.display = "";1808    }18091810    inp.addEventListener("focus", () => {1811      if (suppressNextFocus) { suppressNextFocus = false; return; }1812      render();1813    });1814    inp.addEventListener("input", render);1815    inp.addEventListener("keydown", (e) => {1816      if (list.style.display === "none") return;1817      if (e.key === "ArrowDown" && !collapsed) {1818        e.preventDefault();1819        (rows.firstElementChild as HTMLElement | null)?.focus();1820      } else if (e.key === "Escape") {1821        e.preventDefault();1822        list.style.display = "none";1823      }1824    });1825    inp.addEventListener("blur", (e) => {1826      const rt = (e as FocusEvent).relatedTarget as Node | null;1827      if (rt && list.contains(rt)) return;1828      setTimeout(() => { list.style.display = "none"; }, 150);1829    });1830  }18311832  async function showCreateForm() {1833    currentMode = "create";1834    container.innerHTML = "";18351836    // Guard: the service worker may lock the vault between when the selector1837    // opens and when the user clicks "New entry". Show the inline unlock form1838    // instead of silently failing on save.1839    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1840    if (!statusRes?.unlocked) {1841      renderLocked();1842      return;1843    }18441845    // Detect page password policy once for this form — reused on every1846    // regenerate click so the user always gets a compliant password.1847    const sitePolicy = detectPasswordPolicy();18481849    // Fetch identities on-demand — they're passed in signup context but not1850    // in login/search context where the user still clicks "New entry".1851    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1852    if (!formIdentities.length) {1853      try {1854        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1855        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1856      } catch { /* silent fallback */ }1857    }18581859    const wrap = document.createElement("div");1860    wrap.className = "create-form-wrap";18611862    // Header1863    const head = document.createElement("div"); head.className = "create-head";1864    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1865    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>`;1866    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1867    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1868    head.append(backBtn, lbl);18691870    // Body1871    const body = document.createElement("div"); body.className = "create-body";18721873    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1874      const g = document.createElement("div"); g.className = "f-group";1875      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1876      const inp = document.createElement("input"); inp.className = "f-input";1877      g.append(l, inp); return { g, inp };1878    }18791880    // Title1881    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1882    body.appendChild(tg.g);18831884    // URL1885    const ug = fGroup("website");1886    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1887    if (loginSubdomain) {1888      const h = document.createElement("div"); h.className = "url-hint";1889      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1890    }1891    body.appendChild(ug.g);18921893    // Username — pre-fill from anchor if it doesn't look like an email1894    const xg = fGroup("username");1895    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1896    xg.inp.placeholder = "johndoe";1897    xg.inp.setAttribute("autocomplete", "off");1898    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1899    body.appendChild(xg.g);19001901    // Email — pre-fill from anchor if it looks like an email1902    const eg = fGroup("email");1903    (eg.inp as HTMLInputElement).type = "email";1904    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1905    eg.inp.placeholder = "[email protected]";1906    eg.inp.setAttribute("autocomplete", "off");1907    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1908    body.appendChild(eg.g);19091910    // Password — full smart generator with charset pills + length slider +1911    // policy hint. Mirrors the main UI's compact generator so users get the1912    // same controls inline as in the popup.1913    const pg = fGroup("password");1914    pg.inp.remove(); // smartGen provides its own display — no separate input needed1915    let currentPassword = prePassword || "";1916    const smartGen = createSmartGenerator({1917      policy: sitePolicy,1918      initialPassword: prePassword || undefined,1919      onChange: (pw) => { currentPassword = pw; },1920    });1921    pg.g.appendChild(smartGen.root);1922    body.appendChild(pg.g);19231924    // Save1925    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1926    saveBtn.textContent = "Save entry";1927    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1928    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1929    saveBtn.addEventListener("click", async () => {1930      const title = tg.inp.value.trim();1931      const pw = currentPassword.trim();1932      const username = xg.inp.value.trim();1933      const email = eg.inp.value.trim();1934      if (!title) {1935        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1936        showFormError("Entry needs a title");1937        return;1938      }1939      if (!pw) {1940        showFormError("Entry needs a password — tap regen to make one");1941        return;1942      }1943      errEl.style.display = "none";1944      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1945      try {1946        const res = await chrome.runtime.sendMessage({1947          type: "ADD_ENTRY",1948          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1949        });1950        if ((res as { ok?: boolean }).ok) {1951          // Fill the detected form. onFillFields uses whichever identity the1952          // page anchored on — the vault captures both username and email.1953          options.onFillFields?.(username || email, pw);1954          showSuccess(title);1955        } else {1956          const errMsg = (res as { error?: string }).error === "vault locked"1957            ? "Vault locked — open Peach to save"1958            : "Could not save entry";1959          showFormError(errMsg);1960          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1961        }1962      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1963    });1964    body.appendChild(saveBtn);1965    body.appendChild(errEl);19661967    wrap.append(head, body);1968    container.appendChild(wrap);1969    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1970  }19711972  function showSuccess(title: string) {1973    currentMode = "success";1974    container.innerHTML = "";1975    const wrap = document.createElement("div"); wrap.className = "success-wrap";1976    const ring = document.createElement("div"); ring.className = "success-ring";1977    ring.innerHTML = checkSvgStr();1978    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1979    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1980    wrap.append(ring, t, s);1981    container.appendChild(wrap);1982    setTimeout(() => dismiss(), 1600);1983  }19841985  function flashActionBtn(btn: HTMLButtonElement) {1986    btn.classList.add("flashed");1987    setTimeout(() => btn.classList.remove("flashed"), 700);1988  }19891990  // M3/QUA-005: when both the direct clipboard write and the background COPY1991  // fallback fail, briefly show the user that the copy did not happen.1992  function flashCopyError(btn: HTMLButtonElement) {1993    const original = btn.textContent ?? "";1994    btn.textContent = "Blocked";1995    btn.classList.add("flashed");1996    setTimeout(() => {1997      btn.classList.remove("flashed");1998      if (btn.isConnected) btn.textContent = original;1999    }, 1200);2000  }20012002  function renderSilverPlatter(entry: SelectorEntry) {2003    container.innerHTML = "";2004    searchInput = null;2005    focusedIndex = -1;2006    currentMode = "silver-platter";2007    silverPlatterOrigin = entry;20082009    const domHdr = document.createElement("div");2010    domHdr.className = "domain-header";2011    const headText = document.createElement("div");2012    headText.className = "domain-header-text";2013    const eyebrow = document.createElement("div");2014    eyebrow.className = "domain-eyebrow";2015    eyebrow.textContent = "Saved for this site";2016    const domName = document.createElement("div");2017    domName.className = "domain-name";2018    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2019    headText.append(eyebrow, domName);2020    domHdr.appendChild(headText);2021    if (!options.isSignup) {2022      const actions = document.createElement("div");2023      actions.className = "domain-header-actions";20242025      // Search shortcut — same idea as type-to-search below, but visible so2026      // the user can discover that another entry is reachable from a2027      // single-match platter. Sits to the left of the create button.2028      const searchBtn = document.createElement("button");2029      searchBtn.className = "domain-search-btn";2030      searchBtn.type = "button";2031      searchBtn.setAttribute("aria-label", "Search for a different entry");2032      searchBtn.title = "Search for a different entry";2033      searchBtn.innerHTML = searchSvgStr();2034      searchBtn.addEventListener("click", (e) => {2035        e.stopPropagation();2036        query = "";2037        renderList();2038      });2039      actions.appendChild(searchBtn);20402041      const addBtn = document.createElement("button");2042      addBtn.className = "domain-add-btn";2043      addBtn.type = "button";2044      addBtn.setAttribute("aria-label", "Create new entry");2045      addBtn.title = "Create new entry";2046      addBtn.textContent = "+";2047      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2048      actions.appendChild(addBtn);20492050      domHdr.appendChild(actions);2051    }2052    container.appendChild(domHdr);20532054    const platter = document.createElement("div");2055    platter.className = "silver-platter";20562057    const titleEl = document.createElement("div");2058    titleEl.className = "sp-title";2059    titleEl.textContent = entry.title;2060    platter.appendChild(titleEl);20612062    if (entry.email) {2063      const emailEl = document.createElement("div");2064      emailEl.className = "sp-identity-row";2065      const emailLbl = document.createElement("span");2066      emailLbl.className = "sp-identity-label";2067      emailLbl.textContent = "email";2068      const emailVal = document.createElement("span");2069      emailVal.className = "sp-username";2070      emailVal.textContent = entry.email;2071      emailEl.append(emailLbl, emailVal);2072      platter.appendChild(emailEl);2073    }20742075    if (entry.username) {2076      const userEl = document.createElement("div");2077      userEl.className = "sp-identity-row";2078      const userLbl = document.createElement("span");2079      userLbl.className = "sp-identity-label";2080      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2081      const userVal = document.createElement("span");2082      userVal.className = "sp-username";2083      userVal.textContent = entry.username;2084      userEl.append(userLbl, userVal);2085      platter.appendChild(userEl);2086    }20872088    const fillBtn = document.createElement("button");2089    fillBtn.className = "sp-fill-btn";2090    fillBtn.type = "button";2091    fillBtn.textContent = "Fill credentials";2092    fillBtn.addEventListener("click", () => {2093      if (fillBtn.disabled) return;2094      fillBtn.disabled = true;2095      fillBtn.classList.add("filled");2096      fillBtn.innerHTML = checkSvgStr();2097      // Fire the fill, then exit via the standard exit animation. The fill2098      // itself is async (handled in index.ts) — by 400ms the form is filled2099      // and the popup begins its exit. Total dwell from click to host2100      // removal: 400ms + 130ms (exit animation) = 530ms.2101      onSelect(entry.id);2102      setTimeout(() => dismiss(), 400);2103    });2104    platter.appendChild(fillBtn);21052106    const actionsGroup = document.createElement("div");2107    actionsGroup.className = "sp-actions-group";2108    const actionsLabel = document.createElement("div");2109    actionsLabel.className = "sp-actions-label";2110    actionsLabel.textContent = "Copy";2111    actionsGroup.appendChild(actionsLabel);21122113    const actions = document.createElement("div");2114    actions.className = "sp-actions";2115    actionsGroup.appendChild(actions);21162117    if (entry.email) {2118      const copyEmail = document.createElement("button");2119      copyEmail.className = "sp-action-btn";2120      copyEmail.type = "button";2121      copyEmail.title = "Copy email";2122      copyEmail.textContent = "Email";2123      copyEmail.addEventListener("click", async (e) => {2124        e.stopPropagation();2125        let alreadyWritten = false;2126        try {2127          await navigator.clipboard.writeText(entry.email!);2128          alreadyWritten = true;2129        } catch (err) {2130          console.warn("[Peach] clipboard write denied:", err);2131        }2132        const resp = await chrome.runtime.sendMessage({2133          type: "COPY",2134          payload: { text: entry.email, label: "Email", alreadyWritten },2135        }).catch(() => null) as { ok?: boolean } | null;2136        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2137        else flashCopyError(copyEmail);2138      });2139      actions.appendChild(copyEmail);2140    }21412142    const copyU = document.createElement("button");2143    copyU.className = "sp-action-btn";2144    copyU.type = "button";2145    const usernameIsEmail = entry.username?.includes("@") ?? false;2146    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2147    copyU.textContent = usernameIsEmail ? "Email" : "Username";2148    copyU.disabled = !entry.username;2149    copyU.addEventListener("click", async (e) => {2150      e.stopPropagation();2151      if (!entry.username) return;2152      let alreadyWritten = false;2153      try {2154        await navigator.clipboard.writeText(entry.username);2155        alreadyWritten = true;2156      } catch (err) {2157        console.warn("[Peach] clipboard write denied:", err);2158      }2159      const resp = await chrome.runtime.sendMessage({2160        type: "COPY",2161        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2162      }).catch(() => null) as { ok?: boolean } | null;2163      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2164      else flashCopyError(copyU);2165    });2166    actions.appendChild(copyU);21672168    const copyP = document.createElement("button");2169    copyP.className = "sp-action-btn";2170    copyP.type = "button";2171    copyP.title = "Copy password";2172    copyP.textContent = "Password";2173    copyP.addEventListener("click", async (e) => {2174      e.stopPropagation();2175      const resp = await chrome.runtime.sendMessage({2176        type: "GET_ENTRY_FOR_FILL",2177        payload: { id: entry.id },2178      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2179      if (!resp?.ok || !resp.data?.password) return;2180      let alreadyWritten = false;2181      try {2182        await navigator.clipboard.writeText(resp.data.password);2183        alreadyWritten = true;2184      } catch (err) {2185        console.warn("[Peach] clipboard write denied:", err);2186      }2187      const copyResp = await chrome.runtime.sendMessage({2188        type: "COPY",2189        payload: { text: resp.data.password, label: "Password", alreadyWritten },2190      }).catch(() => null) as { ok?: boolean } | null;2191      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2192      else flashCopyError(copyP);2193    });2194    actions.appendChild(copyP);21952196    let trayEl: HTMLDivElement | null = null;2197    let trayInterval: ReturnType<typeof setInterval> | null = null;21982199    function closeTray() {2200      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2201      trayEl?.remove();2202      trayEl = null;2203    }2204    // Register so dismiss() will close the tray and clear the interval2205    // even if the user dismisses without explicitly closing the tray.2206    cleanupHooks.push(closeTray);22072208    async function openTOTPTray() {2209      // Fetch the entry to get the TOTP secret. The selector summary doesn't2210      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2211      // the message-passing surface minimal per Projects.md §5.2).2212      const resp = await chrome.runtime.sendMessage({2213        type: "GET_ENTRY_FOR_FILL",2214        payload: { id: entry.id },2215      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2216      const secret = resp?.ok ? resp.data?.totp : undefined;2217      if (!secret) return;22182219      trayEl = document.createElement("div");2220      trayEl.className = "sp-tray";22212222      const label = document.createElement("span");2223      label.className = "sp-tray-label";2224      label.textContent = "2FA";2225      trayEl.appendChild(label);22262227      const codeEl = document.createElement("div");2228      codeEl.className = "sp-totp-code";2229      trayEl.appendChild(codeEl);22302231      const ringNs = "http://www.w3.org/2000/svg";2232      const ring = document.createElementNS(ringNs, "svg");2233      ring.setAttribute("class", "sp-totp-ring");2234      ring.setAttribute("viewBox", "0 0 24 24");2235      const trackC = document.createElementNS(ringNs, "circle");2236      trackC.setAttribute("class", "ring-track");2237      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2238      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2239      const fillC = document.createElementNS(ringNs, "circle");2240      fillC.setAttribute("class", "ring-fill");2241      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2242      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2243      fillC.setAttribute("stroke-linecap", "round");2244      fillC.setAttribute("stroke-dasharray", "62.83");2245      ring.append(trackC, fillC);2246      trayEl.appendChild(ring);22472248      const copyBtn = document.createElement("button");2249      copyBtn.className = "sp-totp-copy";2250      copyBtn.type = "button";2251      copyBtn.textContent = "Copy";2252      trayEl.appendChild(copyBtn);22532254      function refresh() {2255        const { code, remaining } = generateTOTP(secret!);2256        // Group as "847 291" — easier to read than "847291"2257        codeEl.textContent = code.length === 62258          ? `${code.slice(0, 3)} ${code.slice(3)}`2259          : code;2260        // Ring fills counter-clockwise as time elapses: dashoffset goes from2261        // 0 (full ring) to 62.83 (empty) over the 30s window.2262        const fraction = (30 - remaining) / 30;2263        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2264      }2265      refresh();2266      trayInterval = setInterval(refresh, 1000);22672268      copyBtn.addEventListener("click", async (e) => {2269        e.stopPropagation();2270        const { code } = generateTOTP(secret!);2271        let alreadyWritten = false;2272        try {2273          await navigator.clipboard.writeText(code);2274          alreadyWritten = true;2275        } catch (err) {2276          console.warn("[Peach] clipboard write denied:", err);2277        }2278        const resp = await chrome.runtime.sendMessage({2279          type: "COPY",2280          payload: { text: code, label: "TOTP", alreadyWritten },2281        }).catch(() => null) as { ok?: boolean } | null;2282        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2283        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2284      });22852286      platter.appendChild(trayEl);2287    }22882289    const editBtn = document.createElement("button");2290    editBtn.className = "sp-action-btn sp-action-edit";2291    editBtn.type = "button";2292    editBtn.title = "Edit entry";2293    editBtn.textContent = "Edit";2294    editBtn.addEventListener("click", (e) => {2295      e.stopPropagation();2296      closeTray();2297      void renderInlineEdit(entry);2298    });2299    actions.appendChild(editBtn);23002301    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2302    // "···" toggle was zero-savings (the toggle button took the same space2303    // the "2FA" label needed) and made the code one extra click away.2304    if (entry.hasTotp) void openTOTPTray();23052306    platter.appendChild(actionsGroup);2307    container.appendChild(platter);2308  }23092310  /**2311   * Inline-popup edit mode. Swaps the silver platter for an editable form2312   * over the same shadow-DOM surface so the user never leaves the page.2313   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2314   * with the new fields. Cancel returns without writing.2315   */2316  async function renderInlineEdit(summary: SelectorEntry) {2317    container.innerHTML = "";2318    const wrap = document.createElement("div");2319    wrap.className = "create-form-wrap";23202321    const head = document.createElement("div");2322    head.className = "create-head";2323    const back = document.createElement("button");2324    back.className = "back-btn";2325    back.type = "button";2326    back.title = "Cancel";2327    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>`;2328    back.addEventListener("click", () => renderSilverPlatter(summary));2329    head.appendChild(back);2330    const headLbl = document.createElement("div");2331    headLbl.className = "create-label";2332    headLbl.textContent = "Edit entry";2333    head.appendChild(headLbl);2334    wrap.appendChild(head);23352336    const body = document.createElement("div");2337    body.className = "create-body";23382339    // Loading shimmer while we fetch the full entry2340    const loading = document.createElement("div");2341    loading.className = "empty-hint";2342    loading.textContent = "loading…";2343    body.appendChild(loading);2344    wrap.appendChild(body);2345    container.appendChild(wrap);23462347    const [res, idRes] = await Promise.all([2348      chrome.runtime.sendMessage({2349        type: "GET_ENTRY_FOR_FILL",2350        payload: { id: summary.id },2351      }).catch(() => null),2352      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2353    ]);2354    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2355    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];23562357    if (!entryRes || !entryRes.ok || !entryRes.data) {2358      loading.textContent = "couldn't load this entry. try again from the popup.";2359      return;2360    }2361    body.innerHTML = "";23622363    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2364      const group = document.createElement("div");2365      group.className = "f-group";2366      const lbl = document.createElement("div");2367      lbl.className = "f-label";2368      lbl.textContent = label;2369      const input = document.createElement("input");2370      input.className = "f-input";2371      input.type = type;2372      input.value = value;2373      input.autocomplete = "off";2374      group.append(lbl, input);2375      body.appendChild(group);2376      return { g: group, inp: input };2377    }23782379    const titleInput = field("title", entryRes.data.title ?? "").inp;2380    const urlInput = field("url", entryRes.data.url ?? "").inp;2381    urlInput.classList.add("url-f");2382    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2383    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2384    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2385    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2386    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");23872388    // Password row with reveal toggle + generator2389    const pwGroup = document.createElement("div");2390    pwGroup.className = "f-group";2391    const pwLbl = document.createElement("div");2392    pwLbl.className = "f-label";2393    pwLbl.textContent = "password";2394    const pwRow = document.createElement("div");2395    pwRow.className = "f-row";2396    const pwInput = document.createElement("input");2397    pwInput.className = "f-input";2398    pwInput.type = "password";2399    pwInput.value = entryRes.data.password ?? "";2400    pwInput.autocomplete = "new-password";2401    const revealBtn = document.createElement("button");2402    revealBtn.className = "gen-btn";2403    revealBtn.type = "button";2404    revealBtn.textContent = "show";2405    revealBtn.addEventListener("click", () => {2406      const reveal = pwInput.type === "password";2407      pwInput.type = reveal ? "text" : "password";2408      revealBtn.textContent = reveal ? "hide" : "show";2409    });2410    pwRow.append(pwInput, revealBtn);2411    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2412    editSmartGen.root.style.display = "none";2413    let editGenVisible = false;2414    const genToggleBtn = document.createElement("button");2415    genToggleBtn.className = "gen-toggle-link";2416    genToggleBtn.type = "button";2417    genToggleBtn.textContent = "⚙ generate";2418    genToggleBtn.addEventListener("click", () => {2419      editGenVisible = !editGenVisible;2420      pwRow.style.display = editGenVisible ? "none" : "";2421      editSmartGen.root.style.display = editGenVisible ? "" : "none";2422      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2423    });2424    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2425    body.appendChild(pwGroup);24262427    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;24282429    // Notes2430    const notesGroup = document.createElement("div");2431    notesGroup.className = "f-group";2432    const notesLbl = document.createElement("div");2433    notesLbl.className = "f-label";2434    notesLbl.textContent = "notes";2435    const notesInput = document.createElement("textarea");2436    notesInput.className = "f-input";2437    notesInput.rows = 3;2438    notesInput.value = entryRes.data.notes ?? "";2439    notesInput.style.fontFamily = "Inter, sans-serif";2440    notesInput.style.resize = "vertical";2441    notesGroup.append(notesLbl, notesInput);2442    body.appendChild(notesGroup);24432444    // Save / Cancel row2445    const actionsRow = document.createElement("div");2446    actionsRow.className = "f-row";2447    const saveBtn = document.createElement("button");2448    saveBtn.className = "save-btn";2449    saveBtn.type = "button";2450    saveBtn.textContent = "Save changes";2451    saveBtn.style.flex = "1";2452    const cancelBtn = document.createElement("button");2453    cancelBtn.className = "gen-btn";2454    cancelBtn.type = "button";2455    cancelBtn.textContent = "cancel";2456    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2457    actionsRow.append(saveBtn, cancelBtn);2458    body.appendChild(actionsRow);24592460    saveBtn.addEventListener("click", async () => {2461      saveBtn.disabled = true;2462      const originalLabel = saveBtn.textContent;2463      saveBtn.textContent = "Saving…";2464      const patch: Record<string, unknown> = {2465        title: titleInput.value.trim(),2466        url: urlInput.value.trim(),2467        username: usernameInput.value.trim(),2468        email: emailInput.value.trim() || undefined,2469        password: pwInput.value,2470        totp: totpInput.value.trim(),2471        notes: notesInput.value,2472      };2473      const updateRes = (await chrome.runtime.sendMessage({2474        type: "UPDATE_ENTRY",2475        payload: { id: summary.id, patch },2476      }).catch(() => null)) as { ok: boolean; error?: string } | null;2477      if (!updateRes?.ok) {2478        saveBtn.disabled = false;2479        saveBtn.textContent = originalLabel;2480        const err = document.createElement("div");2481        err.className = "empty-hint";2482        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2483        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2484        body.appendChild(err);2485        setTimeout(() => err.remove(), 3000);2486        return;2487      }2488      // Refresh the platter with updated summary fields2489      const refreshed: SelectorEntry = {2490        id: summary.id,2491        title: patch.title as string,2492        username: patch.username as string,2493        email: patch.email as string | undefined,2494        url: patch.url as string,2495        hasTotp: Boolean(patch.totp),2496        hasPasskey: summary.hasPasskey,2497      };2498      renderSilverPlatter(refreshed);2499    });25002501    queueMicrotask(() => titleInput.focus());2502  }25032504  function renderLocked() {2505    container.innerHTML = "";25062507    // Domain header (same as list view)2508    const domHdr = document.createElement("div");2509    domHdr.className = "domain-header";2510    const eyebrow = document.createElement("div");2511    eyebrow.className = "domain-eyebrow";2512    eyebrow.textContent = "vault locked";2513    const domName = document.createElement("div");2514    domName.className = "domain-name";2515    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2516    domHdr.append(eyebrow, domName);2517    container.appendChild(domHdr);25182519    const wrap = document.createElement("div");2520    wrap.className = "locked-wrap";25212522    // Icon + label row2523    const head = document.createElement("div"); head.className = "locked-head";2524    const icon = document.createElement("div"); icon.className = "locked-icon";2525    icon.innerHTML = keySvgStr();2526    const title = document.createElement("div"); title.className = "locked-title";2527    title.textContent = "unlock to autofill";2528    head.append(icon, title);25292530    // Password input2531    const pwInp = document.createElement("input");2532    pwInp.className = "locked-input";2533    pwInp.type = "password";2534    pwInp.placeholder = "master password";2535    pwInp.setAttribute("autocomplete", "current-password");25362537    // Error line (hidden initially)2538    const errEl = document.createElement("div");2539    errEl.className = "locked-error";2540    errEl.style.display = "none";25412542    // Unlock button2543    const unlockBtn = document.createElement("button");2544    unlockBtn.className = "locked-btn";2545    unlockBtn.type = "button";2546    unlockBtn.textContent = "unlock";25472548    async function tryUnlock() {2549      const pw = pwInp.value.trim();2550      if (!pw) { pwInp.focus(); return; }2551      unlockBtn.disabled = true;2552      unlockBtn.textContent = "unlocking…";2553      errEl.style.display = "none";2554      try {2555        const res = await chrome.runtime.sendMessage({2556          type: "UNLOCK",2557          payload: { password: pw },2558        });2559        if ((res as { ok?: boolean }).ok) {2560          dismiss();2561          options.onUnlocked?.();2562        } else {2563          errEl.textContent = "incorrect password";2564          errEl.style.display = "block";2565          pwInp.value = "";2566          pwInp.focus();2567          unlockBtn.disabled = false;2568          unlockBtn.textContent = "unlock";2569        }2570      } catch {2571        errEl.textContent = "could not reach Peach";2572        errEl.style.display = "block";2573        unlockBtn.disabled = false;2574        unlockBtn.textContent = "unlock";2575      }2576    }25772578    pwInp.addEventListener("keydown", (e) => {2579      e.stopPropagation();2580      if (e.key === "Enter") void tryUnlock();2581    });2582    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2583    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2584    unlockBtn.addEventListener("click", () => void tryUnlock());25852586    wrap.append(head, pwInp, errEl, unlockBtn);2587    container.appendChild(wrap);25882589    // Keep the MV3 service worker alive while the locked popup is visible.2590    // Without this, the SW goes idle (~30 s) while the user types their2591    // password, and the UNLOCK message pays a 100-300 ms wakeup penalty2592    // before the crypto even starts — perceptible as a delay vs the always-2593    // live extension popup page.2594    const keepaliveId = setInterval(() => {2595      chrome.runtime.sendMessage({ type: "TOUCH_AUTO_LOCK" }).catch(() => {});2596    }, 20_000);2597    cleanupHooks.push(() => clearInterval(keepaliveId));25982599    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2600    // the page reclaims focus from our Shadow DOM input before the user can2601    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2602    // Instead: intercept keystrokes at the document capture phase — this runs2603    // before any page handler regardless of which element technically has2604    // OS focus — and route them into our input.2605    const captureKeydown = (e: KeyboardEvent) => {2606      if (!host.isConnected) {2607        document.removeEventListener("keydown", captureKeydown, true);2608        return;2609      }2610      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2611      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2612      // Intercept before page handlers and give our input focus.2613      e.stopImmediatePropagation();2614      if (e.key === "Escape") { dismiss(true); return; }2615      if (e.key === "Enter") { void tryUnlock(); return; }2616      // For all other printable/editing keys, ensure our input has focus so2617      // the browser delivers the keystroke there naturally.2618      if (document.activeElement !== host) {2619        pwInp.focus({ preventScroll: true });2620      }2621    };2622    captureKeydownRef = captureKeydown;2623    document.addEventListener("keydown", captureKeydown, true);26242625    // Best-effort focus on open — may be overridden by page focus trap,2626    // but the capture listener above handles typing regardless.2627    pwInp.focus({ preventScroll: true });2628    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2629  }26302631  function handleKeyDown(e: KeyboardEvent) {2632    if (options.locked) {2633      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2634      return;2635    }2636    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2637      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2638      return;2639    }2640    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2641    const count = allEntryEls.length;2642    if (document.activeElement === searchInput) {2643      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2644      if (count === 0) return;2645      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2646    }2647    if (count === 0) return;2648    switch (e.key) {2649      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2650      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2651      case "Enter": {2652        if (focusedIndex >= 0) {2653          const el = allEntryEls[focusedIndex] as HTMLElement;2654          const id = el.dataset.id;2655          if (id) { onSelect(id); dismiss(); }2656          else if (el.classList.contains("is-new") || !id) {2657            // "New entry" row (last item, no data-id)2658            showCreateForm();2659          }2660        }2661        break;2662      }2663      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2664    }2665  }26662667  document.addEventListener("keydown", handleKeyDown);26682669  // Type-to-search from the silver platter. A printable single-character2670  // keystroke (no modifier) seeds the search query and switches into the2671  // list view, so the user can pivot to a different entry without first2672  // clicking the search icon. Capture phase so the anchor input does not2673  // receive the character before we hijack it.2674  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2675    if (currentMode !== "silver-platter") return;2676    if (e.ctrlKey || e.metaKey || e.altKey) return;2677    if (e.key.length !== 1) return;2678    e.preventDefault();2679    e.stopImmediatePropagation();2680    query = e.key;2681    renderList();2682  };2683  document.addEventListener("keydown", silverPlatterTypeHandler, true);2684  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));26852686  document.body.appendChild(host);26872688  function updatePosition() {2689    const r = anchorEl.getBoundingClientRect();2690    host.style.top = `${r.bottom + window.scrollY + 5}px`;2691    host.style.left = `${r.left + window.scrollX}px`;2692    host.style.width = `${popupWidth}px`;2693  }2694  // These bindings are referenced from renderLocked()/dismiss() — they MUST2695  // be initialized before renderLocked() runs, or the synchronous assignment2696  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2697  // and throws ReferenceError. The throw lands after the popup is rendered2698  // but before showAutofillSelector returns its dismiss handle, leaving an2699  // orphan host in the DOM (which is what caused the locked-popup stacking2700  // and missing autofocus on every click).2701  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2702  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27032704  if (options.locked) {2705    renderLocked();2706  } else if (options.isSignup && options.savedIdentities) {2707    // State 10: identity helper — signup form detected, show derived2708    // identity list (emails then usernames) instead of vault entry list.2709    renderIdentityHelper();2710  } else if (entries.length === 1 && !options.isSignup) {2711    // Silver platter (State 1): single domain match → focused fill view.2712    // Multi-match goes through renderList instead.2713    renderSilverPlatter(entries[0]!);2714  } else {2715    renderList();2716  }27172718  let exitScheduled = false;2719  function dismiss(userAction = false) {2720    // Idempotent: dismiss() can be called from multiple paths (Escape,2721    // outside click, entry select, fill success, host page nav). The exit2722    // animation must only play once and host.remove() must run exactly once.2723    if (exitScheduled) return;2724    exitScheduled = true;2725    // Detach listeners synchronously so nothing can re-trigger during the2726    // 130ms exit window (a focusin firing here would race against the2727    // dismiss-lock work in Pass 2).2728    stopObserving();2729    document.removeEventListener("click", outsideClick, { capture: true });2730    document.removeEventListener("keydown", handleKeyDown);2731    if (captureKeydownRef) {2732      document.removeEventListener("keydown", captureKeydownRef, true);2733      captureKeydownRef = null;2734    }2735    for (const cleanup of cleanupHooks) {2736      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2737    }2738    if (userAction) options.onDismiss?.();2739    container.classList.add("is-exiting");2740    setTimeout(() => host.remove(), 130);2741  }27422743  function outsideClick(ev: MouseEvent) {2744    const path = ev.composedPath();2745    // Never dismiss when clicking the anchor field itself — that click is2746    // what triggered the selector to open, and the user may click the field2747    // again to re-focus it without intending to close the selector.2748    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2749  }2750  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2751  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);27522753  return dismiss;2754}27552756export function showTOTPSelector(2757  anchorEl: HTMLInputElement,2758  entries: SelectorEntry[],2759  onFill: (id: string) => void,2760  options: { domain?: string; onDismiss?: () => void } = {}2761): () => void {2762  const host = document.createElement("div");2763  host.style.cssText = "position: absolute; z-index: 2147483647;";2764  host.style.setProperty("--peach-accent", accentHex);2765  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2766  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2767  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2768  const shadow = host.attachShadow({ mode: "closed" });27692770  const style = shadow.appendChild(document.createElement("style"));2771  style.textContent = SELECTOR_STYLES;27722773  const rect = anchorEl.getBoundingClientRect();2774  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2775  host.style.left = `${rect.left + window.scrollX}px`;2776  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2777  host.style.width = `${popupWidth}px`;27782779  const container = shadow.appendChild(document.createElement("div"));2780  container.className = "peach-inline-popup";2781  container.setAttribute("data-theme", popupTheme);27822783  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2784  const current = entries.filter((entry) => entry.hasTotp);2785  let focusedIndex = current.length === 1 ? 0 : -1;27862787  function updatePosition() {2788    const r = anchorEl.getBoundingClientRect();2789    host.style.top = `${r.bottom + window.scrollY + 5}px`;2790    host.style.left = `${r.left + window.scrollX}px`;2791    host.style.width = `${popupWidth}px`;2792  }27932794  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27952796  function choose(entry: SelectorEntry) {2797    onFill(entry.id);2798    dismiss();2799  }28002801  function render() {2802    container.innerHTML = "";28032804    const domHdr = document.createElement("div");2805    domHdr.className = "domain-header";2806    const headText = document.createElement("div");2807    headText.className = "domain-header-text";2808    const eyebrow = document.createElement("div");2809    eyebrow.className = "domain-eyebrow";2810    eyebrow.textContent = "2FA code";2811    const domName = document.createElement("div");2812    domName.className = "domain-name";2813    domName.textContent = domain;2814    headText.append(eyebrow, domName);2815    domHdr.appendChild(headText);2816    container.appendChild(domHdr);28172818    if (current.length === 1) {2819      const entry = current[0]!;2820      const platter = document.createElement("div");2821      platter.className = "silver-platter";28222823      const title = document.createElement("div");2824      title.className = "sp-title";2825      title.textContent = entry.title;2826      platter.appendChild(title);28272828      const sub = document.createElement("div");2829      sub.className = "sp-username";2830      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2831      platter.appendChild(sub);28322833      const fill = document.createElement("button");2834      fill.className = "sp-fill-btn";2835      fill.type = "button";2836      fill.textContent = "Fill 2FA code";2837      fill.addEventListener("click", () => choose(entry));2838      platter.appendChild(fill);28392840      container.appendChild(platter);2841      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2842      return;2843    }28442845    const results = document.createElement("div");2846    results.className = "results";2847    container.appendChild(results);28482849    for (let i = 0; i < current.length; i++) {2850      const entry = current[i]!;2851      const row = document.createElement("div");2852      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2853      row.dataset.index = String(i);2854      row.setAttribute("tabindex", "-1");28552856      const icon = document.createElement("div");2857      icon.className = "entry-icon";2858      icon.innerHTML = keySvgStr();2859      row.appendChild(icon);2860      const info = document.createElement("div");2861      info.className = "entry-info";2862      const title = document.createElement("div");2863      title.className = "entry-title";2864      title.textContent = entry.title;2865      const sub = document.createElement("div");2866      sub.className = "entry-sub";2867      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2868      info.append(title, sub);2869      row.appendChild(info);28702871      const badge = document.createElement("span");2872      badge.className = "totp-badge";2873      badge.textContent = "Fill";2874      row.appendChild(badge);2875      row.addEventListener("click", () => choose(entry));2876      results.appendChild(row);2877    }2878  }28792880  function setFocused(index: number) {2881    focusedIndex = index;2882    container.querySelectorAll(".entry").forEach((el, i) => {2883      el.classList.toggle("focused", i === focusedIndex);2884      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2885    });2886  }28872888  function handleKeyDown(e: KeyboardEvent) {2889    if (e.key === "Escape" || e.key === "Tab") {2890      e.preventDefault();2891      dismiss(true);2892      return;2893    }2894    if (current.length === 0) return;2895    if (e.key === "Enter") {2896      e.preventDefault();2897      choose(current[Math.max(0, focusedIndex)]!);2898      return;2899    }2900    if (current.length === 1) return;2901    if (e.key === "ArrowDown") {2902      e.preventDefault();2903      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2904    } else if (e.key === "ArrowUp") {2905      e.preventDefault();2906      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2907    }2908  }29092910  let exitScheduled = false;2911  function dismiss(userAction = false) {2912    if (exitScheduled) return;2913    exitScheduled = true;2914    stopObserving();2915    document.removeEventListener("click", outsideClick, { capture: true });2916    document.removeEventListener("keydown", handleKeyDown);2917    if (userAction) options.onDismiss?.();2918    container.classList.add("is-exiting");2919    setTimeout(() => host.remove(), 130);2920  }29212922  function outsideClick(ev: MouseEvent) {2923    const path = ev.composedPath();2924    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2925  }29262927  document.addEventListener("keydown", handleKeyDown);2928  document.body.appendChild(host);2929  render();2930  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);29312932  return dismiss;2933}29342935export interface CardSelectorEntry {2936  id: string;2937  title: string;2938  cardholderName?: string;2939  last4?: string;2940  expMonth?: string;2941  expYear?: string;2942  network?: import("../shared/types").CardNetwork;2943}29442945interface CardSelectorOptions {2946  domain?: string;2947  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2948  onFill: (entry: import("../shared/types").VaultEntry) => void;2949  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2950  onDismiss?: () => void;2951}29522953/**2954 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2955 * passkey create or get. Renders as a fixed-position floating popup (no2956 * field anchor needed — passkeys don't require a focused input). Uses the2957 * same theme tokens and entrance animation as all other inline popup states.2958 */2959export function showPasskeyProGate(): void {2960  const domain = location.hostname.replace(/^www\./, "");29612962  const host = document.createElement("div");2963  host.setAttribute("data-peach-passkey-gate", "1");2964  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2965  const shadow = host.attachShadow({ mode: "closed" });29662967  const style = document.createElement("style");2968  style.textContent = `2969    :host { all: initial; }2970    .gate-wrap {2971      position: fixed;2972      top: 50%;2973      left: 50%;2974      transform: translate(-50%, -50%);2975      width: 280px;2976      pointer-events: auto;2977      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2978    }2979    @keyframes g-in {2980      from { opacity:0; transform: translate(-50%,-52%); }2981      to   { opacity:1; transform: translate(-50%,-50%); }2982    }2983    .gate-wrap.is-exiting {2984      animation: g-out 130ms ease-in forwards;2985    }2986    @keyframes g-out {2987      to { opacity:0; transform: translate(-50%,-52%); }2988    }2989    .gate {2990      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2991      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2992      border-radius: 12px;2993      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2994      padding: 16px;2995      font-family: Inter, sans-serif;2996    }2997    .gate-header {2998      display: flex;2999      align-items: center;3000      gap: 7px;3001      margin-bottom: 12px;3002      padding-bottom: 10px;3003      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3004    }3005    .gate-domain {3006      font-size: 12px;3007      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3008      font-family: "IBM Plex Mono", monospace;3009      overflow: hidden;3010      text-overflow: ellipsis;3011      white-space: nowrap;3012    }3013    .gate-title {3014      font-size: 14px;3015      font-weight: 500;3016      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3017      margin-bottom: 6px;3018    }3019    .gate-subtitle {3020      font-size: 12px;3021      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};3022      line-height: 1.5;3023      margin-bottom: 14px;3024    }3025    .gate-btn {3026      display: block;3027      width: 100%;3028      padding: 9px 0;3029      border-radius: 8px;3030      border: none;3031      cursor: pointer;3032      font-size: 13px;3033      font-family: Inter, sans-serif;3034      font-weight: 500;3035      transition: opacity 100ms;3036      margin-bottom: 7px;3037      text-align: center;3038    }3039    .gate-btn:last-child { margin-bottom: 0; }3040    .gate-btn--accent {3041      background: ${accentHex};3042      color: #fff;3043    }3044    .gate-btn--accent:hover { opacity: 0.88; }3045    .gate-btn--ghost {3046      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3047      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};3048    }3049    .gate-btn--ghost:hover { opacity: 0.75; }3050    .backdrop {3051      position: fixed;3052      inset: 0;3053      pointer-events: auto;3054    }3055  `;3056  shadow.appendChild(style);30573058  const backdrop = document.createElement("div");3059  backdrop.className = "backdrop";3060  shadow.appendChild(backdrop);30613062  const wrap = document.createElement("div");3063  wrap.className = "gate-wrap";3064  shadow.appendChild(wrap);30653066  const gate = document.createElement("div");3067  gate.className = "gate";3068  wrap.appendChild(gate);30693070  // Header: peach icon + domain3071  const header = document.createElement("div");3072  header.className = "gate-header";3073  const icon = document.createElement("span");3074  icon.innerHTML = peachIconSvg();3075  const domainEl = document.createElement("span");3076  domainEl.className = "gate-domain";3077  domainEl.textContent = domain;3078  header.append(icon, domainEl);3079  gate.appendChild(header);30803081  const title = document.createElement("div");3082  title.className = "gate-title";3083  title.textContent = "Passkeys are part of Peach Pro.";3084  gate.appendChild(title);30853086  const subtitle = document.createElement("div");3087  subtitle.className = "gate-subtitle";3088  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3089  gate.appendChild(subtitle);30903091  const upgradeBtn = document.createElement("button");3092  upgradeBtn.className = "gate-btn gate-btn--accent";3093  upgradeBtn.type = "button";3094  upgradeBtn.textContent = "Upgrade to Pro";3095  gate.appendChild(upgradeBtn);30963097  const laterBtn = document.createElement("button");3098  laterBtn.className = "gate-btn gate-btn--ghost";3099  laterBtn.type = "button";3100  laterBtn.textContent = "Not right now";3101  gate.appendChild(laterBtn);31023103  function dismiss() {3104    wrap.classList.add("is-exiting");3105    setTimeout(() => host.remove(), 130);3106  }31073108  upgradeBtn.addEventListener("click", () => {3109    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3110    dismiss();3111  });3112  laterBtn.addEventListener("click", dismiss);3113  backdrop.addEventListener("click", dismiss);31143115  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3116    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3117  });31183119  document.body.appendChild(host);3120}31213122/**3123 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3124 * detector sees the page invoke navigator.credentials.create(); content/index.ts3125 * checks vault + decline state then calls this. "Save passkey to Peach"3126 * initiates the popup-context credential flow; "Not now" records a 30-day3127 * decline for the domain so we don't re-show on every page reload.3128 */3129export function showPasskeyRegistrationOffer(args: {3130  rpId: string;3131  rpName?: string;3132  userName?: string;3133  userDisplayName?: string;3134}): void {3135  const domain = location.hostname.replace(/^www\./, "");3136  const displayName = args.rpName || domain;31373138  const host = document.createElement("div");3139  host.setAttribute("data-peach-passkey-offer", "1");3140  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3141  const shadow = host.attachShadow({ mode: "closed" });31423143  const style = document.createElement("style");3144  style.textContent = `3145    :host { all: initial; }3146    .offer-wrap {3147      position: fixed;3148      top: 16px;3149      right: 16px;3150      width: 320px;3151      pointer-events: auto;3152      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3153    }3154    @keyframes o-in {3155      from { opacity: 0; transform: translateY(-6px); }3156      to   { opacity: 1; transform: translateY(0); }3157    }3158    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3159    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3160    .offer {3161      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3162      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3163      border-radius: 12px;3164      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3165      padding: 14px 14px 12px;3166      font-family: Inter, sans-serif;3167      position: relative;3168    }3169    .offer-close {3170      position: absolute;3171      top: 8px;3172      right: 8px;3173      width: 18px;3174      height: 18px;3175      border: none;3176      background: transparent;3177      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3178      cursor: pointer;3179      font-size: 14px;3180      line-height: 1;3181      padding: 0;3182    }3183    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3184    .offer-header {3185      display: flex;3186      align-items: center;3187      gap: 7px;3188      margin-bottom: 8px;3189      padding-bottom: 8px;3190      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3191    }3192    .offer-domain {3193      font-size: 12px;3194      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3195      font-family: "IBM Plex Mono", monospace;3196      overflow: hidden;3197      text-overflow: ellipsis;3198      white-space: nowrap;3199    }3200    .offer-title {3201      font-size: 13px;3202      font-weight: 500;3203      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3204      margin-bottom: 4px;3205    }3206    .offer-subtitle {3207      font-size: 11px;3208      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3209      line-height: 1.45;3210      margin-bottom: 12px;3211    }3212    .offer-btn {3213      display: block;3214      width: 100%;3215      padding: 8px 0;3216      border-radius: 7px;3217      border: none;3218      cursor: pointer;3219      font-size: 12px;3220      font-family: Inter, sans-serif;3221      font-weight: 500;3222      transition: opacity 100ms;3223      margin-bottom: 6px;3224      text-align: center;3225    }3226    .offer-btn:last-child { margin-bottom: 0; }3227    .offer-btn--accent { background: ${accentHex}; color: #fff; }3228    .offer-btn--accent:hover { opacity: 0.88; }3229    .offer-btn--ghost {3230      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3231      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3232    }3233    .offer-btn--ghost:hover { opacity: 0.75; }3234  `;3235  shadow.appendChild(style);32363237  const wrap = document.createElement("div");3238  wrap.className = "offer-wrap";3239  shadow.appendChild(wrap);32403241  const offer = document.createElement("div");3242  offer.className = "offer";3243  wrap.appendChild(offer);32443245  const closeBtn = document.createElement("button");3246  closeBtn.className = "offer-close";3247  closeBtn.type = "button";3248  closeBtn.setAttribute("aria-label", "Dismiss");3249  closeBtn.textContent = "✕";3250  offer.appendChild(closeBtn);32513252  const header = document.createElement("div");3253  header.className = "offer-header";3254  const icon = document.createElement("span");3255  icon.innerHTML = peachIconSvg();3256  const domainEl = document.createElement("span");3257  domainEl.className = "offer-domain";3258  domainEl.textContent = domain;3259  header.append(icon, domainEl);3260  offer.appendChild(header);32613262  const title = document.createElement("div");3263  title.className = "offer-title";3264  title.textContent = "This site supports passkeys.";3265  offer.appendChild(title);32663267  const subtitle = document.createElement("div");3268  subtitle.className = "offer-subtitle";3269  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3270  offer.appendChild(subtitle);32713272  const saveBtn = document.createElement("button");3273  saveBtn.className = "offer-btn offer-btn--accent";3274  saveBtn.type = "button";3275  saveBtn.textContent = "Save passkey to Peach";3276  offer.appendChild(saveBtn);32773278  const laterBtn = document.createElement("button");3279  laterBtn.className = "offer-btn offer-btn--ghost";3280  laterBtn.type = "button";3281  laterBtn.textContent = "Not now";3282  offer.appendChild(laterBtn);32833284  function dismiss(decline: boolean) {3285    if (decline) {3286      chrome.runtime.sendMessage({3287        type: "PASSKEY_OFFER_DECLINE",3288        payload: { domain },3289      }).catch(() => {});3290    }3291    wrap.classList.add("is-exiting");3292    setTimeout(() => host.remove(), 130);3293  }32943295  saveBtn.addEventListener("click", () => {3296    chrome.runtime.sendMessage({3297      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3298      payload: {3299        rpId: args.rpId,3300        rpName: args.rpName ?? displayName,3301        userName: args.userName ?? "user",3302        userDisplayName: args.userDisplayName,3303      },3304    }).catch(() => {});3305    dismiss(false);3306  });3307  laterBtn.addEventListener("click", () => dismiss(true));3308  closeBtn.addEventListener("click", () => dismiss(true));33093310  document.body.appendChild(host);3311}33123313/**3314 * State 11 — passkey available indicator. Shown when the user lands on a3315 * domain for which they already have a stored passkey. Tells them where to3316 * find it (the entry already shows in the vault list); the "Sign in with3317 * passkey" button opens the popup so they can use the platform authenticator3318 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3319 * the actual sign-in transparently, so this banner is informational only.3320 */3321export function showPasskeyAvailable(args: {3322  rpId: string;3323  userName: string;3324  fromBrowser?: "chrome" | "firefox";3325  currentBrowser?: "chrome" | "firefox" | "unknown";3326}): void {3327  const domain = location.hostname.replace(/^www\./, "");3328  const crossBrowser =3329    args.fromBrowser &&3330    args.currentBrowser &&3331    args.currentBrowser !== "unknown" &&3332    args.fromBrowser !== args.currentBrowser;33333334  const host = document.createElement("div");3335  host.setAttribute("data-peach-passkey-available", "1");3336  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3337  const shadow = host.attachShadow({ mode: "closed" });33383339  const style = document.createElement("style");3340  style.textContent = `3341    :host { all: initial; }3342    .avail-wrap {3343      position: fixed;3344      top: 16px;3345      right: 16px;3346      width: 320px;3347      pointer-events: auto;3348      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3349    }3350    @keyframes a-in {3351      from { opacity: 0; transform: translateY(-6px); }3352      to   { opacity: 1; transform: translateY(0); }3353    }3354    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3355    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3356    .avail {3357      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3358      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3359      border-radius: 12px;3360      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3361      padding: 14px 14px 12px;3362      font-family: Inter, sans-serif;3363      position: relative;3364    }3365    .avail-close {3366      position: absolute;3367      top: 8px;3368      right: 8px;3369      width: 18px;3370      height: 18px;3371      border: none;3372      background: transparent;3373      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3374      cursor: pointer;3375      font-size: 14px;3376      line-height: 1;3377      padding: 0;3378    }3379    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3380    .avail-header {3381      display: flex;3382      align-items: center;3383      gap: 7px;3384      margin-bottom: 8px;3385      padding-bottom: 8px;3386      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3387    }3388    .avail-domain {3389      font-size: 12px;3390      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3391      font-family: "IBM Plex Mono", monospace;3392    }3393    .avail-label {3394      font-size: 9px;3395      letter-spacing: 0.16em;3396      text-transform: uppercase;3397      color: ${accentHex};3398      margin-bottom: 4px;3399    }3400    .avail-user {3401      font-size: 13px;3402      font-weight: 500;3403      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3404      margin-bottom: 12px;3405      overflow: hidden;3406      text-overflow: ellipsis;3407      white-space: nowrap;3408    }3409    .avail-cross {3410      font-size: 11px;3411      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3412      line-height: 1.45;3413      margin-bottom: 12px;3414      padding: 8px;3415      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3416      border-radius: 6px;3417    }3418    .avail-btn {3419      display: block;3420      width: 100%;3421      padding: 8px 0;3422      border-radius: 7px;3423      border: none;3424      cursor: pointer;3425      font-size: 12px;3426      font-family: Inter, sans-serif;3427      font-weight: 500;3428      transition: opacity 100ms;3429      margin-bottom: 6px;3430      text-align: center;3431    }3432    .avail-btn:last-child { margin-bottom: 0; }3433    .avail-btn--accent { background: ${accentHex}; color: #fff; }3434    .avail-btn--accent:hover { opacity: 0.88; }3435    .avail-btn--ghost {3436      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3437      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3438    }3439    .avail-btn--ghost:hover { opacity: 0.75; }3440  `;3441  shadow.appendChild(style);34423443  const wrap = document.createElement("div");3444  wrap.className = "avail-wrap";3445  shadow.appendChild(wrap);34463447  const avail = document.createElement("div");3448  avail.className = "avail";3449  wrap.appendChild(avail);34503451  const closeBtn = document.createElement("button");3452  closeBtn.className = "avail-close";3453  closeBtn.type = "button";3454  closeBtn.setAttribute("aria-label", "Dismiss");3455  closeBtn.textContent = "✕";3456  avail.appendChild(closeBtn);34573458  const header = document.createElement("div");3459  header.className = "avail-header";3460  const icon = document.createElement("span");3461  icon.innerHTML = peachIconSvg();3462  const domainEl = document.createElement("span");3463  domainEl.className = "avail-domain";3464  domainEl.textContent = domain;3465  header.append(icon, domainEl);3466  avail.appendChild(header);34673468  const label = document.createElement("div");3469  label.className = "avail-label";3470  label.textContent = "PASSKEY";3471  avail.appendChild(label);34723473  const user = document.createElement("div");3474  user.className = "avail-user";3475  user.textContent = args.userName;3476  avail.appendChild(user);34773478  if (crossBrowser) {3479    const cross = document.createElement("div");3480    cross.className = "avail-cross";3481    cross.textContent =3482      args.fromBrowser === "chrome"3483        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3484        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3485    avail.appendChild(cross);3486  }34873488  const signInBtn = document.createElement("button");3489  signInBtn.className = "avail-btn avail-btn--accent";3490  signInBtn.type = "button";3491  signInBtn.textContent = "Sign in with passkey";3492  avail.appendChild(signInBtn);34933494  const passwordBtn = document.createElement("button");3495  passwordBtn.className = "avail-btn avail-btn--ghost";3496  passwordBtn.type = "button";3497  passwordBtn.textContent = "Use password instead";3498  avail.appendChild(passwordBtn);34993500  function dismiss() {3501    wrap.classList.add("is-exiting");3502    setTimeout(() => host.remove(), 130);3503  }35043505  signInBtn.addEventListener("click", () => {3506    // On Chrome: the user clicking the page's own Sign-in button is what3507    //   triggers webAuthenticationProxy → existing background flow handles it.3508    //   Our button just dismisses since the page itself drives auth.3509    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3510    //   and surface the entry for manual reference (popup view).3511    dismiss();3512    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3513  });3514  passwordBtn.addEventListener("click", dismiss);3515  closeBtn.addEventListener("click", dismiss);35163517  document.body.appendChild(host);3518}35193520/**3521 * State 7 — card silver platter. Single-card focused fill view rendered3522 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3523 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3524 * so card and login flows render identically. Multi-card list view is a3525 * follow-up; today this picks the first card.3526 */3527export function showCardSelector(3528  anchorEl: HTMLInputElement,3529  cards: CardSelectorEntry[],3530  options: CardSelectorOptions3531): () => void {3532  if (cards.length === 0) return () => {};3533  const card = cards[0]!;35343535  const host = document.createElement("div");3536  host.style.cssText = "position: absolute; z-index: 2147483647;";3537  host.style.setProperty("--peach-accent", accentHex);3538  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3539  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3540  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3541  const shadow = host.attachShadow({ mode: "closed" });35423543  const style = shadow.appendChild(document.createElement("style"));3544  style.textContent = SELECTOR_STYLES;35453546  const rect = anchorEl.getBoundingClientRect();3547  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3548  host.style.left = `${rect.left + window.scrollX}px`;3549  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;35503551  const container = shadow.appendChild(document.createElement("div"));3552  container.className = "peach-inline-popup";3553  container.setAttribute("data-theme", popupTheme);35543555  // Domain header — eyebrow communicates the card context, not the site3556  const domHdr = document.createElement("div");3557  domHdr.className = "domain-header";3558  const eyebrow = document.createElement("div");3559  eyebrow.className = "domain-eyebrow";3560  eyebrow.textContent = "Pay with Peach";3561  const domName = document.createElement("div");3562  domName.className = "domain-name";3563  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3564  domHdr.append(eyebrow, domName);3565  container.appendChild(domHdr);35663567  const platter = document.createElement("div");3568  platter.className = "card-platter";35693570  if (card.network && card.network !== "unknown") {3571    const net = document.createElement("div");3572    net.className = "cp-network";3573    net.textContent = card.network;3574    platter.appendChild(net);3575  }35763577  const nick = document.createElement("div");3578  nick.className = "cp-nickname";3579  nick.textContent = card.title;3580  platter.appendChild(nick);35813582  if (card.last4) {3583    const l4 = document.createElement("div");3584    l4.className = "cp-last4";3585    l4.textContent = `•••• ${card.last4}`;3586    platter.appendChild(l4);3587  }35883589  const meta = document.createElement("div");3590  meta.className = "cp-meta";3591  if (card.cardholderName) {3592    const name = document.createElement("span");3593    name.textContent = card.cardholderName;3594    meta.appendChild(name);3595  }3596  if (card.expMonth && card.expYear) {3597    if (card.cardholderName) {3598      const sep = document.createElement("span");3599      sep.className = "cp-meta-sep";3600      sep.textContent = "·";3601      meta.appendChild(sep);3602    }3603    const exp = document.createElement("span");3604    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3605    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3606    meta.appendChild(exp);3607  }3608  if (meta.childElementCount > 0) platter.appendChild(meta);36093610  const fillWrap = document.createElement("div");3611  fillWrap.className = "cp-fill-wrap";3612  const fillBtn = document.createElement("button");3613  fillBtn.className = "sp-fill-btn";3614  fillBtn.type = "button";3615  fillBtn.textContent = "Fill card details";3616  fillBtn.addEventListener("click", async () => {3617    if (fillBtn.disabled) return;3618    fillBtn.disabled = true;3619    fillBtn.classList.add("filled");3620    fillBtn.innerHTML = checkSvgStr();3621    const resp = await chrome.runtime.sendMessage({3622      type: "GET_ENTRY_FOR_FILL",3623      payload: { id: card.id },3624    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3625    if (resp?.ok && resp.data) options.onFill(resp.data);3626    setTimeout(() => dismiss(), 400);3627  });3628  fillWrap.appendChild(fillBtn);3629  platter.appendChild(fillWrap);36303631  // Secondary actions — copy number, copy CVC, dismiss3632  const actions = document.createElement("div");3633  actions.className = "sp-actions";36343635  function flashBtn(b: HTMLButtonElement) {3636    b.classList.add("flashed");3637    setTimeout(() => b.classList.remove("flashed"), 700);3638  }36393640  // M3/QUA-005: clipboard + background COPY both failed — show user.3641  function flashCopyError(b: HTMLButtonElement) {3642    const original = b.textContent ?? "";3643    b.textContent = "Blocked";3644    b.classList.add("flashed");3645    setTimeout(() => {3646      b.classList.remove("flashed");3647      if (b.isConnected) b.textContent = original;3648    }, 1200);3649  }36503651  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3652    const resp = await chrome.runtime.sendMessage({3653      type: "GET_ENTRY_FOR_FILL",3654      payload: { id: card.id },3655    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3656    return resp?.ok && resp.data ? resp.data : null;3657  }36583659  const copyNum = document.createElement("button");3660  copyNum.className = "sp-action-btn";3661  copyNum.type = "button";3662  copyNum.title = "Copy card number";3663  copyNum.textContent = "Copy number";3664  copyNum.addEventListener("click", async (e) => {3665    e.stopPropagation();3666    const full = await fetchFullCard();3667    if (!full?.cardNumber) return;3668    let alreadyWritten = false;3669    try {3670      await navigator.clipboard.writeText(full.cardNumber);3671      alreadyWritten = true;3672    } catch (err) {3673      console.warn("[Peach] clipboard write denied:", err);3674    }3675    const resp = await chrome.runtime.sendMessage({3676      type: "COPY",3677      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3678    }).catch(() => null) as { ok?: boolean } | null;3679    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3680    else flashCopyError(copyNum);3681  });3682  actions.appendChild(copyNum);36833684  const copyCvc = document.createElement("button");3685  copyCvc.className = "sp-action-btn";3686  copyCvc.type = "button";3687  copyCvc.title = "Copy CVC";3688  copyCvc.textContent = "Copy CVC";3689  copyCvc.addEventListener("click", async (e) => {3690    e.stopPropagation();3691    const full = await fetchFullCard();3692    if (!full?.cvc) return;3693    let alreadyWritten = false;3694    try {3695      await navigator.clipboard.writeText(full.cvc);3696      alreadyWritten = true;3697    } catch (err) {3698      console.warn("[Peach] clipboard write denied:", err);3699    }3700    const resp = await chrome.runtime.sendMessage({3701      type: "COPY",3702      payload: { text: full.cvc, label: "CVC", alreadyWritten },3703    }).catch(() => null) as { ok?: boolean } | null;3704    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3705    else flashCopyError(copyCvc);3706  });3707  actions.appendChild(copyCvc);37083709  const closeBtn = document.createElement("button");3710  closeBtn.className = "sp-action-btn";3711  closeBtn.type = "button";3712  closeBtn.title = "Dismiss";3713  closeBtn.textContent = "✕";3714  closeBtn.addEventListener("click", (e) => {3715    e.stopPropagation();3716    dismiss(true);3717  });3718  actions.appendChild(closeBtn);37193720  platter.appendChild(actions);3721  container.appendChild(platter);37223723  document.body.appendChild(host);3724  function updatePosition() {3725    const r = anchorEl.getBoundingClientRect();3726    host.style.top = `${r.bottom + window.scrollY + 5}px`;3727    host.style.left = `${r.left + window.scrollX}px`;3728  }3729  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);37303731  function onKeyDown(e: KeyboardEvent) {3732    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3733  }3734  document.addEventListener("keydown", onKeyDown);37353736  let exitScheduled = false;3737  function dismiss(userAction = false) {3738    if (exitScheduled) return;3739    exitScheduled = true;3740    stopObserving();3741    document.removeEventListener("click", outsideClick, { capture: true });3742    document.removeEventListener("keydown", onKeyDown);3743    if (userAction) options.onDismiss?.();3744    container.classList.add("is-exiting");3745    setTimeout(() => host.remove(), 130);3746  }37473748  function outsideClick(ev: MouseEvent) {3749    const path = ev.composedPath();3750    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3751  }3752  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);37533754  return dismiss;3755}