inject.ts

100.5 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 { generateSmartPassword } 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  url?: string;41  hasTotp?: boolean;42}4344interface SelectorOptions {45  domain?: string;46  searchableEntries?: SelectorEntry[];47  /** True when shown on a signup form — changes header label and entry-click behaviour */48  isSignup?: boolean;49  /**50   * Derived identity list (emails then usernames) for signup mode (State 10).51   * When present, renderIdentityHelper() is used instead of renderList().52   */53  savedIdentities?: SavedIdentity[];54  /**55   * Called after the user picks a saved identity (signup mode only) or56   * after successfully saving a new entry on a signup form.57   * Lets the caller fill the visible username + password fields.58   */59  onFillFields?: (username: string, password: string) => void;60  /**61   * When true, show an inline unlock form instead of the entries list.62   * Used when the vault is locked so the user can unlock without opening63   * the popup.64   */65  locked?: boolean;66  /**67   * Called after a successful inline unlock — the caller should re-query68   * entries and re-open the selector with real data.69   */70  onUnlocked?: () => void;71  /**72   * Called when the user explicitly dismisses the selector (Escape, Tab, or73   * click outside) — NOT when an entry is selected or on auto-close.74   * Used by the caller to suppress spurious reopens on the same field.75   */76  onDismiss?: () => void;77}7879function getDomainFromUrl(url: string): string {80  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }81}8283function keySvgStr(): string {84  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>`;85}8687function plusSvgStr(): string {88  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>`;89}9091function peachIconSvg(): string {92  // Peach body is always brand-peach (#D96830), not `accentHex` — a sage93  // or sky accent must not turn the autofill icon green or blue. Accent94  // color still tints surrounding glow/hover halos below.95  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 64 64" fill="none" aria-hidden="true"><path d="M32 54C16 54 8 44 8 31C8 18 17 10 27 10C28 7 30 5.5 32 5.5C34 5.5 36 7 37 10C47 10 56 18 56 31C56 44 48 54 32 54Z" fill="#D96830"/><path d="M37 8.5C40.5 3.5 48 5 46 10.5C42 11 37 8.5 37 8.5Z" fill="#7B9060"/></svg>`;96}9798function genSvgStr(): string {99  return `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round"><path d="M9.5 2A4.5 4.5 0 1 0 10.5 5.5"/><path d="M8.5 2H9.5V1"/></svg>`;100}101102function checkSvgStr(): string {103  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="#7B9060" stroke-width="1.5" stroke-linecap="round"><path d="M4 10.5L8 14.5L16 6.5"/></svg>`;104}105106function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {107  const { hostname, origin } = location;108  const parts = hostname.split(".");109  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",110    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",111    "oidc", "federation", "saml", "cas", "ldap"];112  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());113  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;114  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);115  return { origin, title, loginSubdomain };116}117118/**119 * Shows a bottom-of-page toast after filling credentials when the entry has120 * never matched the current site — offering to add the current origin to the121 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.122 */123export function showRememberSiteToast(124  pageDomain: string,125  entryId: string,126): void {127  const host = document.createElement("div");128  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";129  host.style.setProperty("--peach-accent", accentHex);130  const shadow = host.attachShadow({ mode: "closed" });131132  const style = document.createElement("style");133  style.textContent = `134    .bar {135      display:flex;align-items:center;gap:10px;padding:10px 14px;136      background:#131109;border:1px solid rgba(240,232,216,0.09);137      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);138      font-family:Inter,sans-serif;white-space:nowrap;139      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;140    }141    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }142    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }143    .yes {144      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;145      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;146    }147    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }148    .no {149      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;150      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;151    }152  `;153  shadow.appendChild(style);154155  const bar = document.createElement("div"); bar.className = "bar";156  const txt = document.createElement("span"); txt.className = "txt";157  txt.textContent = `Remember ${pageDomain} for this entry?`;158  const yesBtn = document.createElement("button"); yesBtn.className = "yes";159  yesBtn.textContent = "Remember";160  yesBtn.addEventListener("click", async () => {161    await chrome.runtime.sendMessage({162      type: "ADD_ADDITIONAL_URL",163      payload: { id: entryId, url: location.origin },164    });165    host.remove();166  });167  const noBtn = document.createElement("button"); noBtn.className = "no";168  noBtn.textContent = "Not now";169  noBtn.addEventListener("click", () => host.remove());170  bar.append(txt, yesBtn, noBtn);171  shadow.appendChild(bar);172  document.body.appendChild(host);173  setTimeout(() => host.remove(), 9000);174}175176function generatePasswordForSite(policy: PasswordPolicy = {}): string {177  return generateSmartPassword(policy);178}179180export function observeAnchorPosition(181  anchorEl: HTMLElement,182  onUpdate: () => void183): () => void {184  let rafId = 0;185  let burstUntil = 0;186187  const runUpdate = () => {188    rafId = 0;189    onUpdate();190    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);191  };192  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };193  const scheduleBurst = (ms = 220) => {194    burstUntil = Math.max(burstUntil, performance.now() + ms);195    scheduleUpdate();196  };197198  const resizeObserver = new ResizeObserver(() => scheduleBurst());199  resizeObserver.observe(anchorEl);200  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);201202  const mutationObserver = new MutationObserver(() => scheduleBurst());203  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });204  if (anchorEl.parentElement) {205    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });206  }207208  const onScroll = () => scheduleUpdate();209  window.addEventListener("scroll", onScroll, true);210  window.addEventListener("resize", onScroll);211  window.visualViewport?.addEventListener("resize", onScroll);212  window.visualViewport?.addEventListener("scroll", onScroll);213  anchorEl.addEventListener("focus", () => scheduleBurst());214  anchorEl.addEventListener("input", () => scheduleBurst());215216  scheduleBurst(260);217218  return () => {219    if (rafId) cancelAnimationFrame(rafId);220    resizeObserver.disconnect();221    mutationObserver.disconnect();222    window.removeEventListener("scroll", onScroll, true);223    window.removeEventListener("resize", onScroll);224    window.visualViewport?.removeEventListener("resize", onScroll);225    window.visualViewport?.removeEventListener("scroll", onScroll);226  };227}228229export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {230  const button = document.createElement("button");231  button.type = "button";232  button.setAttribute("aria-label", "Peach autofill");233  button.title = "Fill with Peach";234  button.innerHTML = peachIconSvg();235  // position: fixed is load-bearing — not absolute. Absolute positioning236  // inherits the nearest positioned ancestor's box, which on sites with237  // overflow:hidden or sticky parents clips or offsets the icon. Fixed238  // anchors to the viewport and escapes all parent layout.239  button.style.cssText = `240    position: fixed; z-index: 2147483646;241    width: 26px; height: 26px; cursor: pointer;242    pointer-events: auto; border: none; padding: 3px;243    display: inline-flex; align-items: center; justify-content: center;244    background: transparent; border-radius: 999px;245    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;246    opacity: 0;247  `;248  button.addEventListener("mouseenter", () => {249    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;250    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;251    button.style.transform = "scale(1.08)";252  });253  button.addEventListener("mouseleave", () => {254    button.style.background = "transparent";255    button.style.boxShadow = "none";256    button.style.transform = "none";257  });258  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });259  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });260261  document.body.appendChild(button);262263  function updatePosition() {264    const rect = field.getBoundingClientRect();265    if (rect.width === 0 || rect.height === 0) {266      button.style.opacity = "0"; button.style.pointerEvents = "none";267      return;268    }269    const sz = 26;270    const inset = Math.max(5, Math.min(10, rect.height * 0.22));271    const top = rect.top + rect.height / 2 - sz / 2;272    // Clamp left so the icon stays fully inside the field's right edge, never273    // spilling onto an adjacent sibling button.274    const minLeft = rect.left + 4;275    const left = Math.max(minLeft, rect.right - sz - inset);276    // Hide if the field is too narrow to fit the icon cleanly (< 40px)277    if (rect.width < 40) {278      button.style.opacity = "0"; button.style.pointerEvents = "none";279      return;280    }281    button.style.top = `${top}px`;282    button.style.left = `${left}px`;283    button.style.opacity = "1"; button.style.pointerEvents = "auto";284  }285  updatePosition();286  requestAnimationFrame(() => { button.style.opacity = "1"; });287  const stopObserving = observeAnchorPosition(field, updatePosition);288  return () => { stopObserving(); button.remove(); };289}290291// All theme-dependent values resolve through tokens scoped to292// .peach-inline-popup[data-theme="dark|light"]. Accent variables293// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)294// are identical in both themes — only surface tokens differ. See295// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the296// theme switch — only literal brand-peach in peachIconSvg may stay raw.297const SELECTOR_STYLES = `298  :host { all: initial; }299  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }300301  .peach-inline-popup[data-theme="dark"] {302    --peach-bg:           #1a1410;303    --peach-bg-card:      #221c16;304    --peach-text:         #f5f0ea;305    --peach-text-dim:     #8a7a6a;306    --peach-text-muted:   #4a3a2a;307    --peach-border:       rgba(255,255,255,0.07);308    --peach-input-bg:     rgba(255,255,255,0.05);309    --peach-input-border: rgba(255,255,255,0.08);310  }311  .peach-inline-popup[data-theme="light"] {312    --peach-bg:           #fdf8f4;313    --peach-bg-card:      #f5ede4;314    --peach-text:         #1c1310;315    --peach-text-dim:     #6b5a4a;316    --peach-text-muted:   #a89080;317    --peach-border:       rgba(0,0,0,0.08);318    --peach-input-bg:     rgba(0,0,0,0.04);319    --peach-input-border: rgba(0,0,0,0.10);320  }321322  .peach-inline-popup {323    background: var(--peach-bg);324    border: 1px solid var(--peach-border-accent, var(--peach-border));325    border-radius: 14px;326    overflow: hidden;327    box-shadow:328      0 8px 40px var(--peach-glow, transparent),329      0 2px 12px rgba(0,0,0,0.5);330    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;331    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;332  }333  /* Light theme: shadow against a light page is too strong otherwise — drop both334     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */335  .peach-inline-popup[data-theme="light"] {336    box-shadow:337      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),338      0 2px 12px rgba(0,0,0,0.12);339  }340  .peach-inline-popup.is-exiting {341    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;342    pointer-events: none;343  }344345  @keyframes peach-enter {346    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }347    65%  { opacity: 1; filter: blur(0); }348    100% { opacity: 1; transform: translateY(0) scale(1); }349  }350  @keyframes peach-exit {351    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }352    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }353  }354  @keyframes peach-slide-in {355    from { opacity: 0; transform: translateX(12px); }356    to   { opacity: 1; transform: translateX(0); }357  }358  @keyframes peach-slide-back {359    from { opacity: 0; transform: translateX(-12px); }360    to   { opacity: 1; transform: translateX(0); }361  }362  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }363  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }364365  /* Domain header */366  .domain-header {367    padding: 9px 13px 7px;368    border-bottom: 1px solid var(--peach-border);369    display: flex; align-items: center; justify-content: space-between;370  }371  .domain-eyebrow {372    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;373    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;374  }375  .domain-name {376    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);377    font-family: "IBM Plex Mono", monospace;378  }379380  /* Search */381  .search-wrap {382    padding: 9px 12px 7px;383    border-bottom: 1px solid var(--peach-border);384  }385  .search {386    width: 100%; background: var(--peach-input-bg);387    border: 1px solid var(--peach-input-border);388    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;389    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;390    transition: border-color 120ms, box-shadow 120ms;391  }392  .search:focus {393    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);394    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);395  }396  .search::placeholder { color: var(--peach-text-muted); }397398  /* Results */399  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }400  .results::-webkit-scrollbar { display: none; }401402  /* Entry rows */403  .entry {404    display: flex; align-items: center; padding: 8px 12px;405    cursor: pointer; border-bottom: 1px solid var(--peach-border);406    transition: background 70ms; position: relative; outline: none;407  }408  .entry:last-child { border-bottom: none; }409  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }410  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }411  .entry.focused::before {412    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;413    width: 2px; border-radius: 2px;414    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);415  }416417  .entry-icon {418    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;419    background: var(--peach-input-bg); border: 1px solid var(--peach-border);420    display: flex; align-items: center; justify-content: center;421    overflow: hidden; margin-right: 10px;422  }423  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }424  .entry-icon.is-new {425    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);426    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);427    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);428  }429430  .entry-info { flex: 1; min-width: 0; }431  .entry-title {432    font-size: 12.5px; color: var(--peach-text);433    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;434    line-height: 1.3;435  }436  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }437  .entry-sub {438    font-size: 10px; color: var(--peach-text-dim);439    font-family: "IBM Plex Mono", monospace;440    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;441    margin-top: 1px;442  }443444  .totp-badge {445    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;446    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);447    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);448    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;449  }450451  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }452453  .empty-hint {454    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);455    font-family: "IBM Plex Mono", monospace;456  }457458  /* Create form */459  .create-form-wrap {460    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;461  }462  .create-head {463    display: flex; align-items: center; gap: 8px;464    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);465  }466  .back-btn {467    background: transparent; border: none; cursor: pointer;468    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;469    display: flex; align-items: center; line-height: 0;470    transition: color 100ms, background 100ms;471  }472  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }473  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }474  .create-body { padding: 12px; display: grid; gap: 9px; }475  .f-group { display: grid; gap: 3px; }476  .f-label {477    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;478    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;479  }480  .f-input {481    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);482    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;483    font-size: 11px; font-family: "IBM Plex Mono", monospace;484    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;485  }486  .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); }487  .f-input::placeholder { color: var(--peach-text-muted); }488  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }489  .f-row { display: flex; gap: 6px; }490  .f-row .f-input { flex: 1; min-width: 0; }491  .gen-btn {492    padding: 0 10px; border-radius: 7px; border: none;493    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);494    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);495    font-size: 10px; font-family: "IBM Plex Mono", monospace;496    cursor: pointer; white-space: nowrap; flex-shrink: 0;497    display: flex; align-items: center; gap: 4px;498    transition: background 100ms;499  }500  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }501  .save-btn {502    width: 100%; padding: 8px; border-radius: 8px; border: none;503    background: var(--peach-accent); color: #fff; font-size: 12px;504    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;505    transition: background 120ms, box-shadow 120ms, transform 80ms;506    letter-spacing: 0.01em;507  }508  .save-btn:hover {509    background: color-mix(in srgb, var(--peach-accent) 82%, #000);510    box-shadow: 0 4px 20px var(--peach-glow, transparent);511  }512  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }513  .url-hint {514    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);515    font-family: "IBM Plex Mono", monospace; font-style: italic;516  }517518  /* Success */519  .success-wrap {520    display: flex; flex-direction: column; align-items: center;521    padding: 24px 16px 20px; gap: 8px;522    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;523  }524  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }525  .success-ring {526    width: 40px; height: 40px; border-radius: 50%;527    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);528    display: flex; align-items: center; justify-content: center;529  }530  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }531  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }532533  /* Silver platter (State 1 — single match) */534  .silver-platter {535    padding: 14px 14px 12px;536    display: flex; flex-direction: column; gap: 6px;537  }538  .sp-title {539    font-size: 14px; font-weight: 500; color: var(--peach-text);540    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;541    line-height: 1.25;542  }543  .sp-username {544    font-size: 12px; color: var(--peach-text-dim);545    font-family: "IBM Plex Mono", monospace;546    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;547    margin-bottom: 6px;548  }549  .sp-fill-btn {550    width: 100%; padding: 11px; border-radius: 9px; border: none;551    background: var(--peach-accent); color: #fff;552    font-size: 13px; font-weight: 500; cursor: pointer;553    font-family: Inter, sans-serif; letter-spacing: 0.01em;554    display: flex; align-items: center; justify-content: center; min-height: 38px;555    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;556  }557  .sp-fill-btn:hover {558    filter: brightness(1.1);559    box-shadow: 0 4px 20px var(--peach-glow, transparent);560    transform: translateY(-1px);561  }562  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }563  .sp-fill-btn.filled {564    background: #16a34a; transform: none; filter: none;565    box-shadow: 0 4px 16px rgba(22,163,74,0.35);566    cursor: default;567  }568  .sp-fill-btn:disabled { cursor: default; }569  .sp-actions {570    display: flex; gap: 4px; justify-content: space-between; align-items: center;571    margin-top: 4px;572  }573  .sp-action-btn {574    flex: 1; height: 28px; border: none; border-radius: 6px;575    background: transparent; color: var(--peach-text-dim);576    font-size: 12px; cursor: pointer;577    transition: background 120ms ease, color 120ms ease;578    font-family: Inter, sans-serif; letter-spacing: 0.04em;579    display: inline-flex; align-items: center; justify-content: center; gap: 4px;580  }581  .sp-action-btn:hover:not(:disabled) {582    background: color-mix(in srgb, var(--peach-text) 5%, transparent);583    color: var(--peach-text);584  }585  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }586  .sp-action-btn.flashed {587    color: var(--peach-accent);588    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);589  }590591  /* TOTP tray — shown below the silver-platter secondary actions */592  .sp-tray {593    margin-top: 8px;594    padding: 10px 12px;595    border-radius: 9px;596    background: var(--peach-input-bg);597    border: 1px solid var(--peach-input-border);598    display: flex; align-items: center; gap: 12px;599    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;600  }601  .sp-tray-label {602    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;603    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;604    flex-shrink: 0;605  }606  .sp-totp-code {607    font-size: 18px; font-weight: 500;608    color: var(--peach-text);609    font-family: "IBM Plex Mono", monospace;610    letter-spacing: 0.12em;611    flex: 1;612    text-align: center;613  }614  .sp-totp-ring {615    width: 22px; height: 22px; flex-shrink: 0;616  }617  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }618  .sp-totp-ring .ring-fill {619    stroke: var(--peach-accent);620    transition: stroke-dashoffset 1s linear;621    transform: rotate(-90deg);622    transform-origin: center;623  }624  .sp-totp-copy {625    background: transparent; border: none; cursor: pointer;626    padding: 4px 8px; border-radius: 5px;627    color: var(--peach-text-dim); font-size: 11px;628    font-family: Inter, sans-serif;629    transition: background 120ms, color 120ms;630  }631  .sp-totp-copy:hover {632    background: color-mix(in srgb, var(--peach-text) 5%, transparent);633    color: var(--peach-text);634  }635636  /* Card silver platter (State 7) — reuses .sp-* primary action classes */637  .card-platter {638    padding: 12px 14px 10px;639    display: flex; flex-direction: column; gap: 4px;640  }641  .cp-network {642    font-size: 10px; font-weight: 600;643    color: var(--peach-accent);644    letter-spacing: 0.08em; text-transform: uppercase;645    font-family: Inter, sans-serif;646  }647  .cp-nickname {648    font-size: 14px; font-weight: 500; color: var(--peach-text);649    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;650    line-height: 1.2;651  }652  .cp-last4 {653    font-size: 12px; color: var(--peach-text-dim);654    font-family: "IBM Plex Mono", monospace;655    letter-spacing: 0.04em;656    margin-top: 2px;657  }658  .cp-meta {659    font-size: 11px; color: var(--peach-text-dim);660    font-family: "IBM Plex Mono", monospace;661    margin-top: 2px;662    display: flex; gap: 10px; align-items: center;663  }664  .cp-meta-sep { opacity: 0.5; }665  .cp-fill-wrap { margin-top: 10px; }666667  /* Locked state */668  .locked-wrap {669    display: flex; flex-direction: column; align-items: stretch;670    padding: 14px 13px 13px; gap: 9px;671  }672  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }673  .locked-icon {674    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;675    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);676    display: flex; align-items: center; justify-content: center;677  }678  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }679  .locked-input {680    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);681    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;682    font-size: 11px; font-family: "IBM Plex Mono", monospace;683    outline: none; transition: border-color 120ms, box-shadow 120ms;684  }685  .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); }686  .locked-input::placeholder { color: var(--peach-text-muted); }687  .locked-btn {688    width: 100%; padding: 8px; border-radius: 8px; border: none;689    background: var(--peach-accent); color: #fff; font-size: 12px;690    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;691    transition: background 120ms;692    letter-spacing: 0.01em;693    box-shadow: 0 2px 16px var(--peach-glow, transparent);694    animation: peach-pulse-glow 2.4s ease-in-out infinite;695  }696  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }697  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }698  .locked-error {699    font-size: 10px; color: rgba(220,80,60,0.85);700    font-family: "IBM Plex Mono", monospace;701  }702703  @keyframes peach-pulse-glow {704    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }705    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),706                            0 0 48px var(--peach-glow, transparent); }707  }708709  /* ── State 10: identity helper ─────────────────────────────── */710  .identity-list { max-height: 192px; overflow-y: auto; padding: 4px 0; }711  .peach-identity-row {712    display: flex; align-items: center; gap: 10px;713    padding: 9px 12px; cursor: pointer; border-radius: 8px;714    transition: background 100ms ease;715  }716  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }717  .peach-identity-value {718    font-family: "IBM Plex Mono", monospace; font-size: 13px;719    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;720  }721  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }722  .identity-alt-row {723    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;724    border-radius: 8px; transition: background 100ms ease;725    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;726  }727  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }728  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }729  .identity-alt-input-wrap.open { display: flex; }730  .identity-alt-input {731    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;732    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);733    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;734    outline: none; transition: border-color 120ms;735  }736  .identity-alt-input:focus {737    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);738    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);739  }740  .identity-alt-confirm {741    height: 32px; padding: 0 12px; border-radius: 7px; border: none;742    background: var(--peach-accent); color: #fff; font-size: 12px;743    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;744  }745  /* ── Generator view (after identity picked) ────────────────── */746  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }747  .gen-confirmed {748    display: flex; align-items: center; gap: 8px; padding: 7px 10px;749    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);750    border-radius: 8px;751  }752  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }753  .gen-confirmed-val {754    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);755    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;756  }757  .gen-label {758    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;759    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;760  }761  .gen-pw-row { display: flex; gap: 6px; align-items: center; }762  .gen-pw-val {763    flex: 1; padding: 8px 10px; border-radius: 7px;764    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);765    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);766    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;767  }768  .gen-regen-btn {769    height: 34px; padding: 0 10px; border-radius: 7px; border: none;770    background: color-mix(in srgb, var(--peach-text) 8%, transparent);771    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;772    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;773  }774  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }775  .gen-fill-btn {776    padding: 10px; border-radius: 8px; border: none;777    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;778    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;779    transition: filter 120ms ease, transform 80ms ease;780  }781  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }782  .gen-fill-btn:active { transform: translateY(0); }783  /* ── Save offer (after password filled) ───────────────────── */784  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }785  .save-offer-title {786    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;787  }788  .save-offer-row {789    display: flex; align-items: center; gap: 8px; padding: 6px 8px;790    border-radius: 7px; background: var(--peach-input-bg);791    border: 1px solid var(--peach-input-border);792  }793  .save-offer-lbl {794    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;795    font-family: "IBM Plex Mono", monospace;796  }797  .save-offer-val {798    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);799    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;800  }801  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }802  .save-offer-save {803    flex: 1; padding: 9px; border-radius: 8px; border: none;804    background: var(--peach-accent); color: #fff; font-size: 13px;805    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;806  }807  .save-offer-save:hover { filter: brightness(1.08); }808  .save-offer-skip {809    flex: 1; padding: 9px; border-radius: 8px; border: none;810    background: color-mix(in srgb, var(--peach-text) 8%, transparent);811    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;812    font-family: Inter, sans-serif; transition: background 100ms ease;813  }814  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }815`;816817export function showAutofillSelector(818  anchorEl: HTMLInputElement,819  entries: SelectorEntry[],820  onSelect: (id: string) => void,821  options: SelectorOptions = {}822): () => void {823  const host = document.createElement("div");824  host.style.cssText = "position: absolute; z-index: 2147483647;";825  host.style.setProperty("--peach-accent", accentHex);826  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));827  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));828  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));829  const shadow = host.attachShadow({ mode: "closed" });830831  const style = shadow.appendChild(document.createElement("style"));832  style.textContent = SELECTOR_STYLES;833834  const rect = anchorEl.getBoundingClientRect();835  host.style.top = `${rect.bottom + window.scrollY + 5}px`;836  host.style.left = `${rect.left + window.scrollX}px`;837  // Spec §1.1: 320px width. The Math.max() floor preserves usability on838  // wide single-input fields (e.g. centered email input on signup pages).839  host.style.width = `${Math.max(rect.width, 320)}px`;840841  const container = shadow.appendChild(document.createElement("div"));842  container.className = "peach-inline-popup";843  container.setAttribute("data-theme", popupTheme);844845  const searchableEntries = options.searchableEntries ?? [];846  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();847848  let query = "";849  let focusedIndex = -1;850  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";851  let searchInput: HTMLInputElement | null = null;852  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray853  // setInterval. Add to this list — don't fan out the dismiss function.854  const cleanupHooks: Array<() => void> = [];855856  // Pre-capture the anchor field value for username prefill857  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";858  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");859  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";860861  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {862    const seen = new Set<string>();863    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });864  }865866  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {867    const q = value.trim().toLowerCase();868    const deduped = uniqueEntries(source);869    if (!q) return deduped.slice(0, 8);870    return deduped.filter(e =>871      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)872    ).slice(0, 12);873  }874875  function activeEntries(): SelectorEntry[] {876    // When user is typing a search, filter across all known entries (domain matches + vault)877    if (query.trim()) {878      const merged = uniqueEntries([...entries, ...searchableEntries]);879      return filterEntries(merged, query);880    }881    // Default: show domain matches; fall back to vault search when no matches882    if (entries.length > 0) return entries;883    return filterEntries(searchableEntries, "").slice(0, 8);884  }885886  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {887    const icon = document.createElement("div");888    icon.className = `entry-icon${isNew ? " is-new" : ""}`;889    if (isNew) {890      icon.innerHTML = plusSvgStr();891    } else {892      // Use the generic key glyph for all entries in the page-injected selector.893      // Avoids disclosing vault domains to any third party and avoids needing894      // to expose the browser favicon API to page context via web_accessible_resources.895      void url;896      icon.innerHTML = keySvgStr();897    }898    return icon;899  }900901  function renderIdentityHelper() {902    container.innerHTML = "";903    const identities = options.savedIdentities ?? [];904905    // Header: "NEW ACCOUNT" + domain name906    const hdr = container.appendChild(document.createElement("div"));907    hdr.className = "domain-header";908    const eyebrow = hdr.appendChild(document.createElement("div"));909    eyebrow.className = "domain-eyebrow";910    eyebrow.textContent = "NEW ACCOUNT";911    const domName = hdr.appendChild(document.createElement("div"));912    domName.className = "domain-name";913    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");914915    // Identity rows916    const list = container.appendChild(document.createElement("div"));917    list.className = "identity-list";918    for (const id of identities) {919      const row = list.appendChild(document.createElement("div"));920      row.className = "peach-identity-row";921      row.setAttribute("tabindex", "-1");922      const val = row.appendChild(document.createElement("div"));923      val.className = "peach-identity-value";924      val.textContent = id.value;925      const meta = row.appendChild(document.createElement("div"));926      meta.className = "peach-identity-meta";927      meta.textContent = `used ${id.useCount}×`;928      row.addEventListener("click", () => {929        options.onFillFields?.(id.value, "");930        renderGenerator(id.value);931      });932    }933934    // Divider before "Use a different email…"935    if (identities.length > 0) {936      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));937    }938939    // "Use a different email…" expandable row940    const altRow = container.appendChild(document.createElement("div"));941    altRow.className = "identity-alt-row";942    altRow.textContent = "+ Use a different email…";943944    const altInputWrap = container.appendChild(document.createElement("div"));945    altInputWrap.className = "identity-alt-input-wrap";946    const altInput = altInputWrap.appendChild(document.createElement("input"));947    altInput.className = "identity-alt-input";948    altInput.type = "email";949    altInput.placeholder = "[email protected]";950    altInput.setAttribute("autocomplete", "off");951    const altConfirm = altInputWrap.appendChild(document.createElement("button"));952    altConfirm.className = "identity-alt-confirm";953    altConfirm.type = "button";954    altConfirm.textContent = "✓";955956    function fillCustomEmail() {957      const v = altInput.value.trim();958      if (!v) return;959      options.onFillFields?.(v, "");960      renderGenerator(v);961    }962963    altRow.addEventListener("click", () => {964      altRow.style.display = "none";965      altInputWrap.classList.add("open");966      altInput.focus();967    });968    altConfirm.addEventListener("click", fillCustomEmail);969    altInput.addEventListener("keydown", (e) => {970      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }971    });972  }973974  function renderGenerator(filledEmail: string) {975    container.innerHTML = "";976    const sitePolicy = detectPasswordPolicy();977    let pw = generatePasswordForSite(sitePolicy);978979    const wrap = container.appendChild(document.createElement("div"));980    wrap.className = "gen-view";981982    // Header: domain + NEW ACCOUNT983    const hdrRow = wrap.appendChild(document.createElement("div"));984    hdrRow.className = "domain-header";985    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));986    eyebrow2.className = "domain-eyebrow";987    eyebrow2.textContent = "NEW ACCOUNT";988    const domName2 = hdrRow.appendChild(document.createElement("div"));989    domName2.className = "domain-name";990    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");991992    // Confirmed email row993    const conf = wrap.appendChild(document.createElement("div"));994    conf.className = "gen-confirmed";995    const confCheck = conf.appendChild(document.createElement("span"));996    confCheck.className = "gen-confirmed-check";997    confCheck.textContent = "✓";998    const confVal = conf.appendChild(document.createElement("div"));999    confVal.className = "gen-confirmed-val";1000    confVal.textContent = filledEmail;10011002    // "Generate a password?" label1003    const lbl = wrap.appendChild(document.createElement("div"));1004    lbl.className = "gen-label";1005    lbl.textContent = "Generate a password";10061007    // Password display + regen1008    const pwRow = wrap.appendChild(document.createElement("div"));1009    pwRow.className = "gen-pw-row";1010    const pwVal = pwRow.appendChild(document.createElement("div"));1011    pwVal.className = "gen-pw-val";1012    pwVal.textContent = pw;1013    const regenBtn = pwRow.appendChild(document.createElement("button"));1014    regenBtn.className = "gen-regen-btn";1015    regenBtn.type = "button";1016    regenBtn.textContent = "⟳ regen";1017    regenBtn.addEventListener("click", () => {1018      pw = generatePasswordForSite(sitePolicy);1019      pwVal.textContent = pw;1020    });10211022    // "Copy & fill" button1023    const fillBtn = wrap.appendChild(document.createElement("button"));1024    fillBtn.className = "gen-fill-btn";1025    fillBtn.type = "button";1026    fillBtn.textContent = "Copy & fill";1027    fillBtn.addEventListener("click", () => {1028      options.onFillFields?.("", pw);1029      renderSaveOffer(filledEmail, pw);1030    });1031  }10321033  function renderSaveOffer(filledEmail: string, filledPassword: string) {1034    container.innerHTML = "";1035    const domain = options.domain ?? location.hostname.replace(/^www\./, "");10361037    const wrap = container.appendChild(document.createElement("div"));1038    wrap.className = "save-offer";10391040    const title = wrap.appendChild(document.createElement("div"));1041    title.className = "save-offer-title";1042    title.textContent = "Save this login to Peach?";10431044    function detailRow(label: string, value: string) {1045      const row = wrap.appendChild(document.createElement("div"));1046      row.className = "save-offer-row";1047      const lbl = row.appendChild(document.createElement("div"));1048      lbl.className = "save-offer-lbl";1049      lbl.textContent = label;1050      const val = row.appendChild(document.createElement("div"));1051      val.className = "save-offer-val";1052      val.textContent = value;1053    }10541055    detailRow("site", domain);1056    detailRow("email", filledEmail);1057    detailRow("password", "••••••••••••••••");10581059    const btns = wrap.appendChild(document.createElement("div"));1060    btns.className = "save-offer-btns";10611062    const saveBtn = btns.appendChild(document.createElement("button"));1063    saveBtn.className = "save-offer-save";1064    saveBtn.type = "button";1065    saveBtn.textContent = "Save";1066    saveBtn.addEventListener("click", async () => {1067      saveBtn.disabled = true;1068      saveBtn.textContent = "Saving…";1069      try {1070        const res = await chrome.runtime.sendMessage({1071          type: "ADD_ENTRY",1072          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1073        });1074        if ((res as { ok?: boolean }).ok) {1075          showSuccess(sTitle);1076        } else {1077          saveBtn.disabled = false;1078          saveBtn.textContent = "Save";1079        }1080      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1081    });10821083    const skipBtn = btns.appendChild(document.createElement("button"));1084    skipBtn.className = "save-offer-skip";1085    skipBtn.type = "button";1086    skipBtn.textContent = "Not now";1087    skipBtn.addEventListener("click", () => { dismiss(true); });1088  }10891090  function renderList() {1091    container.innerHTML = "";1092    focusedIndex = -1;1093    searchInput = null;10941095    const current = activeEntries();10961097    // Domain header (always show)1098    const domHdr = document.createElement("div");1099    domHdr.className = "domain-header";1100    const eyebrow = document.createElement("div");1101    eyebrow.className = "domain-eyebrow";1102    eyebrow.textContent = options.isSignup1103      ? "Sign up as"1104      : entries.length > 0 ? "Saved for this site" : "No saved login";1105    const domName = document.createElement("div");1106    domName.className = "domain-name";1107    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1108    domHdr.append(eyebrow, domName);1109    container.appendChild(domHdr);11101111    // Search — always show so user can find entries beyond the domain matches1112    const sw = document.createElement("div"); sw.className = "search-wrap";1113    searchInput = document.createElement("input");1114    searchInput.className = "search";1115    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1116    searchInput.value = query;1117    searchInput.addEventListener("input", () => {1118      query = searchInput?.value ?? "";1119      renderList();1120      searchInput?.focus();1121      searchInput?.setSelectionRange(query.length, query.length);1122    });1123    sw.appendChild(searchInput);1124    container.appendChild(sw);11251126    // Results1127    const results = document.createElement("div");1128    results.className = "results";1129    container.appendChild(results);11301131    if (current.length === 0 && entries.length > 0) {1132      // Show a hint but don't render empty entries1133    }11341135    for (let i = 0; i < current.length; i++) {1136      const e = current[i]!;1137      const entryEl = document.createElement("div");1138      entryEl.className = "entry";1139      entryEl.dataset.id = e.id;1140      entryEl.dataset.index = String(i);1141      entryEl.setAttribute("tabindex", "-1");11421143      entryEl.appendChild(makeEntryIcon(e.url));11441145      const info = document.createElement("div"); info.className = "entry-info";1146      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1147      const subEl = document.createElement("div"); subEl.className = "entry-sub";1148      const domain = e.url ? getDomainFromUrl(e.url) : "";1149      subEl.textContent = domain || e.username || "";1150      info.append(titleEl, subEl);1151      entryEl.appendChild(info);11521153      if (e.hasTotp) {1154        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1155        entryEl.appendChild(badge);1156      }11571158      entryEl.addEventListener("click", () => {1159        if (options.isSignup && options.onFillFields) {1160          // Signup mode: clicking a saved identity fills the username field1161          options.onFillFields(e.username ?? "", "");1162          dismiss();1163        } else {1164          onSelect(e.id);1165          dismiss();1166        }1167      });1168      results.appendChild(entryEl);1169    }11701171    // Divider before "New entry"1172    if (current.length > 0) {1173      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1174    }11751176    // "New entry" row — always present1177    const newEl = document.createElement("div");1178    newEl.className = "entry";1179    newEl.setAttribute("tabindex", "-1");1180    newEl.appendChild(makeEntryIcon(undefined, true));11811182    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1183    const newTitle = document.createElement("div");1184    newTitle.className = "entry-title is-new";1185    newTitle.textContent = `New entry for ${sTitle}`;1186    const newSub = document.createElement("div");1187    newSub.className = "entry-sub";1188    newSub.textContent = sOrigin;1189    newInfo.append(newTitle, newSub);1190    newEl.appendChild(newInfo);1191    newEl.addEventListener("click", showCreateForm);1192    results.appendChild(newEl);11931194    // Focus search if present1195    if (searchInput) {1196      requestAnimationFrame(() => searchInput?.focus());1197    }1198  }11991200  function setFocused(idx: number) {1201    const all = container.querySelectorAll<HTMLElement>(".entry");1202    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1203    focusedIndex = idx;1204    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1205  }12061207  async function showCreateForm() {1208    currentMode = "create";1209    container.innerHTML = "";12101211    // Guard: the service worker may lock the vault between when the selector1212    // opens and when the user clicks "New entry". Show the inline unlock form1213    // instead of silently failing on save.1214    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1215    if (!statusRes?.unlocked) {1216      renderLocked();1217      return;1218    }12191220    // Detect page password policy once for this form — reused on every1221    // regenerate click so the user always gets a compliant password.1222    const sitePolicy = detectPasswordPolicy();12231224    const wrap = document.createElement("div");1225    wrap.className = "create-form-wrap";12261227    // Header1228    const head = document.createElement("div"); head.className = "create-head";1229    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1230    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>`;1231    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1232    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1233    head.append(backBtn, lbl);12341235    // Body1236    const body = document.createElement("div"); body.className = "create-body";12371238    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1239      const g = document.createElement("div"); g.className = "f-group";1240      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1241      const inp = document.createElement("input"); inp.className = "f-input";1242      g.append(l, inp); return { g, inp };1243    }12441245    // Title1246    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1247    body.appendChild(tg.g);12481249    // URL1250    const ug = fGroup("website");1251    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1252    if (loginSubdomain) {1253      const h = document.createElement("div"); h.className = "url-hint";1254      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1255    }1256    body.appendChild(ug.g);12571258    // Username (pre-fill from anchor field)1259    const xg = fGroup("username / email");1260    xg.inp.value = preUsername; xg.inp.placeholder = "[email protected]";1261    xg.inp.setAttribute("autocomplete", "off");1262    body.appendChild(xg.g);12631264    // Password + generate1265    const pg = fGroup("password");1266    const pwInp = document.createElement("input"); pwInp.className = "f-input";1267    pwInp.type = "text"; pwInp.value = prePassword || generatePasswordForSite(sitePolicy);1268    pwInp.style.fontFamily = '"IBM Plex Mono", monospace';1269    pwInp.style.letterSpacing = "0.04em";1270    pwInp.setAttribute("autocomplete", "off"); pwInp.setAttribute("spellcheck", "false");1271    const genBtn = document.createElement("button"); genBtn.className = "gen-btn"; genBtn.type = "button";1272    genBtn.innerHTML = genSvgStr() + " regen";1273    genBtn.addEventListener("click", () => { pwInp.value = generatePasswordForSite(sitePolicy); });1274    const pwRow = document.createElement("div"); pwRow.className = "f-row";1275    pwRow.append(pwInp, genBtn); pg.g.appendChild(pwRow);1276    body.appendChild(pg.g);12771278    // Save1279    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1280    saveBtn.textContent = "Save entry";1281    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1282    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1283    saveBtn.addEventListener("click", async () => {1284      const title = tg.inp.value.trim();1285      const pw = pwInp.value.trim();1286      const username = xg.inp.value.trim();1287      if (!title) {1288        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1289        showFormError("Entry needs a title");1290        return;1291      }1292      if (!pw) {1293        pwInp.style.borderColor = "rgba(220,70,60,0.5)"; pwInp.focus();1294        showFormError("Entry needs a password");1295        return;1296      }1297      errEl.style.display = "none";1298      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1299      try {1300        const res = await chrome.runtime.sendMessage({1301          type: "ADD_ENTRY",1302          payload: { title, url: ug.inp.value.trim(), username, password: pw, type: "login" },1303        });1304        if ((res as { ok?: boolean }).ok) {1305          // Fill the detected form regardless of mode. For login the user1306          // created an entry to use here; for signup the password was just1307          // generated for this site. Either way the credentials land in1308          // the form. options.onFillFields is wired by the caller (index.ts)1309          // and also records the form into filledForms so the popup will1310          // not re-attach to the filled fields.1311          options.onFillFields?.(username, pw);1312          showSuccess(title);1313        } else {1314          const errMsg = (res as { error?: string }).error === "vault locked"1315            ? "Vault locked — open Peach to save"1316            : "Could not save entry";1317          showFormError(errMsg);1318          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1319        }1320      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1321    });1322    body.appendChild(saveBtn);1323    body.appendChild(errEl);13241325    wrap.append(head, body);1326    container.appendChild(wrap);1327    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1328  }13291330  function showSuccess(title: string) {1331    currentMode = "success";1332    container.innerHTML = "";1333    const wrap = document.createElement("div"); wrap.className = "success-wrap";1334    const ring = document.createElement("div"); ring.className = "success-ring";1335    ring.innerHTML = checkSvgStr();1336    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1337    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1338    wrap.append(ring, t, s);1339    container.appendChild(wrap);1340    setTimeout(() => dismiss(), 1600);1341  }13421343  function flashActionBtn(btn: HTMLButtonElement) {1344    btn.classList.add("flashed");1345    setTimeout(() => btn.classList.remove("flashed"), 700);1346  }13471348  function renderSilverPlatter(entry: SelectorEntry) {1349    container.innerHTML = "";1350    searchInput = null;1351    focusedIndex = -1;1352    currentMode = "silver-platter";13531354    const domHdr = document.createElement("div");1355    domHdr.className = "domain-header";1356    const eyebrow = document.createElement("div");1357    eyebrow.className = "domain-eyebrow";1358    eyebrow.textContent = "Saved for this site";1359    const domName = document.createElement("div");1360    domName.className = "domain-name";1361    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1362    domHdr.append(eyebrow, domName);1363    container.appendChild(domHdr);13641365    const platter = document.createElement("div");1366    platter.className = "silver-platter";13671368    const titleEl = document.createElement("div");1369    titleEl.className = "sp-title";1370    titleEl.textContent = entry.title;1371    platter.appendChild(titleEl);13721373    if (entry.username) {1374      const userEl = document.createElement("div");1375      userEl.className = "sp-username";1376      userEl.textContent = entry.username;1377      platter.appendChild(userEl);1378    }13791380    const fillBtn = document.createElement("button");1381    fillBtn.className = "sp-fill-btn";1382    fillBtn.type = "button";1383    fillBtn.textContent = "Fill credentials";1384    fillBtn.addEventListener("click", () => {1385      if (fillBtn.disabled) return;1386      fillBtn.disabled = true;1387      fillBtn.classList.add("filled");1388      fillBtn.innerHTML = checkSvgStr();1389      // Fire the fill, then exit via the standard exit animation. The fill1390      // itself is async (handled in index.ts) — by 400ms the form is filled1391      // and the popup begins its exit. Total dwell from click to host1392      // removal: 400ms + 130ms (exit animation) = 530ms.1393      onSelect(entry.id);1394      setTimeout(() => dismiss(), 400);1395    });1396    platter.appendChild(fillBtn);13971398    const actions = document.createElement("div");1399    actions.className = "sp-actions";14001401    const copyU = document.createElement("button");1402    copyU.className = "sp-action-btn";1403    copyU.type = "button";1404    copyU.title = "Copy username";1405    copyU.textContent = "Copy username";1406    copyU.disabled = !entry.username;1407    copyU.addEventListener("click", async (e) => {1408      e.stopPropagation();1409      if (!entry.username) return;1410      let alreadyWritten = false;1411      try { await navigator.clipboard.writeText(entry.username); alreadyWritten = true; } catch {}1412      // Mirror the popup's copy path so the COPY message can clear the1413      // clipboard via the configured timeout. alreadyWritten lets the SW1414      // skip a redundant write when the page-level write succeeded.1415      await chrome.runtime.sendMessage({1416        type: "COPY",1417        payload: { text: entry.username, label: "Username", alreadyWritten },1418      }).catch(() => {});1419      flashActionBtn(copyU);1420    });1421    actions.appendChild(copyU);14221423    const copyP = document.createElement("button");1424    copyP.className = "sp-action-btn";1425    copyP.type = "button";1426    copyP.title = "Copy password";1427    copyP.textContent = "Copy password";1428    copyP.addEventListener("click", async (e) => {1429      e.stopPropagation();1430      const resp = await chrome.runtime.sendMessage({1431        type: "GET_ENTRY_FOR_FILL",1432        payload: { id: entry.id },1433      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;1434      if (!resp?.ok || !resp.data?.password) return;1435      let alreadyWritten = false;1436      try { await navigator.clipboard.writeText(resp.data.password); alreadyWritten = true; } catch {}1437      await chrome.runtime.sendMessage({1438        type: "COPY",1439        payload: { text: resp.data.password, label: "Password", alreadyWritten },1440      }).catch(() => {});1441      flashActionBtn(copyP);1442    });1443    actions.appendChild(copyP);14441445    let trayEl: HTMLDivElement | null = null;1446    let trayInterval: ReturnType<typeof setInterval> | null = null;14471448    function closeTray() {1449      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }1450      trayEl?.remove();1451      trayEl = null;1452    }1453    // Register so dismiss() will close the tray and clear the interval1454    // even if the user dismisses without explicitly closing the tray.1455    cleanupHooks.push(closeTray);14561457    async function openTOTPTray() {1458      // Fetch the entry to get the TOTP secret. The selector summary doesn't1459      // carry it (and shouldn't — passing secrets only at fill/copy time keeps1460      // the message-passing surface minimal per Projects.md §5.2).1461      const resp = await chrome.runtime.sendMessage({1462        type: "GET_ENTRY_FOR_FILL",1463        payload: { id: entry.id },1464      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;1465      const secret = resp?.ok ? resp.data?.totp : undefined;1466      if (!secret) return;14671468      trayEl = document.createElement("div");1469      trayEl.className = "sp-tray";14701471      const label = document.createElement("span");1472      label.className = "sp-tray-label";1473      label.textContent = "2FA";1474      trayEl.appendChild(label);14751476      const codeEl = document.createElement("div");1477      codeEl.className = "sp-totp-code";1478      trayEl.appendChild(codeEl);14791480      const ringNs = "http://www.w3.org/2000/svg";1481      const ring = document.createElementNS(ringNs, "svg");1482      ring.setAttribute("class", "sp-totp-ring");1483      ring.setAttribute("viewBox", "0 0 24 24");1484      const trackC = document.createElementNS(ringNs, "circle");1485      trackC.setAttribute("class", "ring-track");1486      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");1487      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");1488      const fillC = document.createElementNS(ringNs, "circle");1489      fillC.setAttribute("class", "ring-fill");1490      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");1491      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");1492      fillC.setAttribute("stroke-linecap", "round");1493      fillC.setAttribute("stroke-dasharray", "62.83");1494      ring.append(trackC, fillC);1495      trayEl.appendChild(ring);14961497      const copyBtn = document.createElement("button");1498      copyBtn.className = "sp-totp-copy";1499      copyBtn.type = "button";1500      copyBtn.textContent = "Copy";1501      trayEl.appendChild(copyBtn);15021503      function refresh() {1504        const { code, remaining } = generateTOTP(secret!);1505        // Group as "847 291" — easier to read than "847291"1506        codeEl.textContent = code.length === 61507          ? `${code.slice(0, 3)} ${code.slice(3)}`1508          : code;1509        // Ring fills counter-clockwise as time elapses: dashoffset goes from1510        // 0 (full ring) to 62.83 (empty) over the 30s window.1511        const fraction = (30 - remaining) / 30;1512        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));1513      }1514      refresh();1515      trayInterval = setInterval(refresh, 1000);15161517      copyBtn.addEventListener("click", async (e) => {1518        e.stopPropagation();1519        const { code } = generateTOTP(secret!);1520        let alreadyWritten = false;1521        try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}1522        await chrome.runtime.sendMessage({1523          type: "COPY",1524          payload: { text: code, label: "TOTP", alreadyWritten },1525        }).catch(() => {});1526        copyBtn.textContent = "Copied";1527        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);1528      });15291530      platter.appendChild(trayEl);1531    }15321533    if (entry.hasTotp) {1534      const moreBtn = document.createElement("button");1535      moreBtn.className = "sp-action-btn";1536      moreBtn.type = "button";1537      moreBtn.title = "Show 2FA code";1538      moreBtn.textContent = "···";1539      moreBtn.addEventListener("click", (e) => {1540        e.stopPropagation();1541        if (trayEl) {1542          closeTray();1543          moreBtn.classList.remove("flashed");1544        } else {1545          moreBtn.classList.add("flashed");1546          void openTOTPTray();1547        }1548      });1549      actions.appendChild(moreBtn);1550    }15511552    const closeBtn = document.createElement("button");1553    closeBtn.className = "sp-action-btn";1554    closeBtn.type = "button";1555    closeBtn.title = "Dismiss";1556    closeBtn.textContent = "✕";1557    closeBtn.addEventListener("click", (e) => {1558      e.stopPropagation();1559      closeTray();1560      dismiss(true);1561    });1562    actions.appendChild(closeBtn);15631564    platter.appendChild(actions);1565    container.appendChild(platter);1566  }15671568  function renderLocked() {1569    container.innerHTML = "";15701571    // Domain header (same as list view)1572    const domHdr = document.createElement("div");1573    domHdr.className = "domain-header";1574    const eyebrow = document.createElement("div");1575    eyebrow.className = "domain-eyebrow";1576    eyebrow.textContent = "vault locked";1577    const domName = document.createElement("div");1578    domName.className = "domain-name";1579    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1580    domHdr.append(eyebrow, domName);1581    container.appendChild(domHdr);15821583    const wrap = document.createElement("div");1584    wrap.className = "locked-wrap";15851586    // Icon + label row1587    const head = document.createElement("div"); head.className = "locked-head";1588    const icon = document.createElement("div"); icon.className = "locked-icon";1589    icon.innerHTML = keySvgStr();1590    const title = document.createElement("div"); title.className = "locked-title";1591    title.textContent = "unlock to autofill";1592    head.append(icon, title);15931594    // Password input1595    const pwInp = document.createElement("input");1596    pwInp.className = "locked-input";1597    pwInp.type = "password";1598    pwInp.placeholder = "master password";1599    pwInp.setAttribute("autocomplete", "current-password");16001601    // Error line (hidden initially)1602    const errEl = document.createElement("div");1603    errEl.className = "locked-error";1604    errEl.style.display = "none";16051606    // Unlock button1607    const unlockBtn = document.createElement("button");1608    unlockBtn.className = "locked-btn";1609    unlockBtn.type = "button";1610    unlockBtn.textContent = "unlock";16111612    async function tryUnlock() {1613      const pw = pwInp.value.trim();1614      if (!pw) { pwInp.focus(); return; }1615      unlockBtn.disabled = true;1616      unlockBtn.textContent = "unlocking…";1617      errEl.style.display = "none";1618      try {1619        const res = await chrome.runtime.sendMessage({1620          type: "UNLOCK",1621          payload: { password: pw },1622        });1623        if ((res as { ok?: boolean }).ok) {1624          dismiss();1625          options.onUnlocked?.();1626        } else {1627          errEl.textContent = "incorrect password";1628          errEl.style.display = "block";1629          pwInp.value = "";1630          pwInp.focus();1631          unlockBtn.disabled = false;1632          unlockBtn.textContent = "unlock";1633        }1634      } catch {1635        errEl.textContent = "could not reach Peach";1636        errEl.style.display = "block";1637        unlockBtn.disabled = false;1638        unlockBtn.textContent = "unlock";1639      }1640    }16411642    pwInp.addEventListener("keydown", (e) => {1643      e.stopPropagation();1644      if (e.key === "Enter") void tryUnlock();1645    });1646    pwInp.addEventListener("keyup", (e) => e.stopPropagation());1647    pwInp.addEventListener("keypress", (e) => e.stopPropagation());1648    unlockBtn.addEventListener("click", () => void tryUnlock());16491650    wrap.append(head, pwInp, errEl, unlockBtn);1651    container.appendChild(wrap);16521653    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)1654    // the page reclaims focus from our Shadow DOM input before the user can1655    // type. Fighting over focus with a focusout→refocus loop hangs the tab.1656    // Instead: intercept keystrokes at the document capture phase — this runs1657    // before any page handler regardless of which element technically has1658    // OS focus — and route them into our input.1659    const captureKeydown = (e: KeyboardEvent) => {1660      if (!host.isConnected) {1661        document.removeEventListener("keydown", captureKeydown, true);1662        return;1663      }1664      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.1665      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;1666      // Intercept before page handlers and give our input focus.1667      e.stopImmediatePropagation();1668      if (e.key === "Escape") { dismiss(true); return; }1669      if (e.key === "Enter") { void tryUnlock(); return; }1670      // For all other printable/editing keys, ensure our input has focus so1671      // the browser delivers the keystroke there naturally.1672      if (document.activeElement !== host) {1673        pwInp.focus({ preventScroll: true });1674      }1675    };1676    captureKeydownRef = captureKeydown;1677    document.addEventListener("keydown", captureKeydown, true);16781679    // Best-effort focus on open — may be overridden by page focus trap,1680    // but the capture listener above handles typing regardless.1681    pwInp.focus({ preventScroll: true });1682    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });1683  }16841685  function handleKeyDown(e: KeyboardEvent) {1686    if (options.locked) {1687      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }1688      return;1689    }1690    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {1691      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }1692      return;1693    }1694    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");1695    const count = allEntryEls.length;1696    if (document.activeElement === searchInput) {1697      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }1698      if (count === 0) return;1699      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;1700    }1701    if (count === 0) return;1702    switch (e.key) {1703      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;1704      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;1705      case "Enter": {1706        if (focusedIndex >= 0) {1707          const el = allEntryEls[focusedIndex] as HTMLElement;1708          const id = el.dataset.id;1709          if (id) { onSelect(id); dismiss(); }1710          else if (el.classList.contains("is-new") || !id) {1711            // "New entry" row (last item, no data-id)1712            showCreateForm();1713          }1714        }1715        break;1716      }1717      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;1718    }1719  }17201721  document.addEventListener("keydown", handleKeyDown);17221723  document.body.appendChild(host);17241725  function updatePosition() {1726    const r = anchorEl.getBoundingClientRect();1727    host.style.top = `${r.bottom + window.scrollY + 5}px`;1728    host.style.left = `${r.left + window.scrollX}px`;1729    host.style.width = `${Math.max(r.width, 260)}px`;1730  }1731  // These bindings are referenced from renderLocked()/dismiss() — they MUST1732  // be initialized before renderLocked() runs, or the synchronous assignment1733  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ1734  // and throws ReferenceError. The throw lands after the popup is rendered1735  // but before showAutofillSelector returns its dismiss handle, leaving an1736  // orphan host in the DOM (which is what caused the locked-popup stacking1737  // and missing autofocus on every click).1738  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;1739  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);17401741  if (options.locked) {1742    renderLocked();1743  } else if (options.isSignup && options.savedIdentities) {1744    // State 10: identity helper — signup form detected, show derived1745    // identity list (emails then usernames) instead of vault entry list.1746    renderIdentityHelper();1747  } else if (entries.length === 1 && !options.isSignup) {1748    // Silver platter (State 1): single domain match → focused fill view.1749    // Multi-match goes through renderList instead.1750    renderSilverPlatter(entries[0]!);1751  } else {1752    renderList();1753  }17541755  let exitScheduled = false;1756  function dismiss(userAction = false) {1757    // Idempotent: dismiss() can be called from multiple paths (Escape,1758    // outside click, entry select, fill success, host page nav). The exit1759    // animation must only play once and host.remove() must run exactly once.1760    if (exitScheduled) return;1761    exitScheduled = true;1762    // Detach listeners synchronously so nothing can re-trigger during the1763    // 130ms exit window (a focusin firing here would race against the1764    // dismiss-lock work in Pass 2).1765    stopObserving();1766    document.removeEventListener("click", outsideClick, { capture: true });1767    document.removeEventListener("keydown", handleKeyDown);1768    if (captureKeydownRef) {1769      document.removeEventListener("keydown", captureKeydownRef, true);1770      captureKeydownRef = null;1771    }1772    for (const cleanup of cleanupHooks) {1773      try { cleanup(); } catch { /* defensive — one hook must not block others */ }1774    }1775    if (userAction) options.onDismiss?.();1776    container.classList.add("is-exiting");1777    setTimeout(() => host.remove(), 130);1778  }17791780  function outsideClick(ev: MouseEvent) {1781    const path = ev.composedPath();1782    // Never dismiss when clicking the anchor field itself — that click is1783    // what triggered the selector to open, and the user may click the field1784    // again to re-focus it without intending to close the selector.1785    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);1786  }1787  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler1788  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);17891790  return dismiss;1791}17921793export interface CardSelectorEntry {1794  id: string;1795  title: string;1796  cardholderName?: string;1797  last4?: string;1798  expMonth?: string;1799  expYear?: string;1800  network?: import("../shared/types").CardNetwork;1801}18021803interface CardSelectorOptions {1804  domain?: string;1805  /** Caller-provided fill — receives the full CardEntry payload from the SW. */1806  onFill: (entry: import("../shared/types").VaultEntry) => void;1807  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */1808  onDismiss?: () => void;1809}18101811/**1812 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn1813 * passkey create or get. Renders as a fixed-position floating popup (no1814 * field anchor needed — passkeys don't require a focused input). Uses the1815 * same theme tokens and entrance animation as all other inline popup states.1816 */1817export function showPasskeyProGate(): void {1818  const domain = location.hostname.replace(/^www\./, "");18191820  const host = document.createElement("div");1821  host.setAttribute("data-peach-passkey-gate", "1");1822  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";1823  const shadow = host.attachShadow({ mode: "closed" });18241825  const style = document.createElement("style");1826  style.textContent = `1827    :host { all: initial; }1828    .gate-wrap {1829      position: fixed;1830      top: 50%;1831      left: 50%;1832      transform: translate(-50%, -50%);1833      width: 280px;1834      pointer-events: auto;1835      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;1836    }1837    @keyframes g-in {1838      from { opacity:0; transform: translate(-50%,-52%); }1839      to   { opacity:1; transform: translate(-50%,-50%); }1840    }1841    .gate-wrap.is-exiting {1842      animation: g-out 130ms ease-in forwards;1843    }1844    @keyframes g-out {1845      to { opacity:0; transform: translate(-50%,-52%); }1846    }1847    .gate {1848      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};1849      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};1850      border-radius: 12px;1851      box-shadow: 0 12px 48px rgba(0,0,0,0.75);1852      padding: 16px;1853      font-family: Inter, sans-serif;1854    }1855    .gate-header {1856      display: flex;1857      align-items: center;1858      gap: 7px;1859      margin-bottom: 12px;1860      padding-bottom: 10px;1861      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};1862    }1863    .gate-domain {1864      font-size: 12px;1865      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};1866      font-family: "IBM Plex Mono", monospace;1867      overflow: hidden;1868      text-overflow: ellipsis;1869      white-space: nowrap;1870    }1871    .gate-title {1872      font-size: 14px;1873      font-weight: 500;1874      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};1875      margin-bottom: 6px;1876    }1877    .gate-subtitle {1878      font-size: 12px;1879      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};1880      line-height: 1.5;1881      margin-bottom: 14px;1882    }1883    .gate-btn {1884      display: block;1885      width: 100%;1886      padding: 9px 0;1887      border-radius: 8px;1888      border: none;1889      cursor: pointer;1890      font-size: 13px;1891      font-family: Inter, sans-serif;1892      font-weight: 500;1893      transition: opacity 100ms;1894      margin-bottom: 7px;1895      text-align: center;1896    }1897    .gate-btn:last-child { margin-bottom: 0; }1898    .gate-btn--accent {1899      background: ${accentHex};1900      color: #fff;1901    }1902    .gate-btn--accent:hover { opacity: 0.88; }1903    .gate-btn--ghost {1904      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};1905      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};1906    }1907    .gate-btn--ghost:hover { opacity: 0.75; }1908    .backdrop {1909      position: fixed;1910      inset: 0;1911      pointer-events: auto;1912    }1913  `;1914  shadow.appendChild(style);19151916  const backdrop = document.createElement("div");1917  backdrop.className = "backdrop";1918  shadow.appendChild(backdrop);19191920  const wrap = document.createElement("div");1921  wrap.className = "gate-wrap";1922  shadow.appendChild(wrap);19231924  const gate = document.createElement("div");1925  gate.className = "gate";1926  wrap.appendChild(gate);19271928  // Header: peach icon + domain1929  const header = document.createElement("div");1930  header.className = "gate-header";1931  const icon = document.createElement("span");1932  icon.innerHTML = peachIconSvg();1933  const domainEl = document.createElement("span");1934  domainEl.className = "gate-domain";1935  domainEl.textContent = domain;1936  header.append(icon, domainEl);1937  gate.appendChild(header);19381939  const title = document.createElement("div");1940  title.className = "gate-title";1941  title.textContent = "Passkeys are part of Peach Pro.";1942  gate.appendChild(title);19431944  const subtitle = document.createElement("div");1945  subtitle.className = "gate-subtitle";1946  subtitle.textContent = "Store and use passkeys across all your devices, securely.";1947  gate.appendChild(subtitle);19481949  const upgradeBtn = document.createElement("button");1950  upgradeBtn.className = "gate-btn gate-btn--accent";1951  upgradeBtn.type = "button";1952  upgradeBtn.textContent = "Upgrade to Pro";1953  gate.appendChild(upgradeBtn);19541955  const laterBtn = document.createElement("button");1956  laterBtn.className = "gate-btn gate-btn--ghost";1957  laterBtn.type = "button";1958  laterBtn.textContent = "Not right now";1959  gate.appendChild(laterBtn);19601961  function dismiss() {1962    wrap.classList.add("is-exiting");1963    setTimeout(() => host.remove(), 130);1964  }19651966  upgradeBtn.addEventListener("click", () => {1967    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});1968    dismiss();1969  });1970  laterBtn.addEventListener("click", dismiss);1971  backdrop.addEventListener("click", dismiss);19721973  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {1974    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }1975  });19761977  document.body.appendChild(host);1978}19791980/**1981 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world1982 * detector sees the page invoke navigator.credentials.create(); content/index.ts1983 * checks vault + decline state then calls this. "Save passkey to Peach"1984 * initiates the popup-context credential flow; "Not now" records a 30-day1985 * decline for the domain so we don't re-show on every page reload.1986 */1987export function showPasskeyRegistrationOffer(args: {1988  rpId: string;1989  rpName?: string;1990  userName?: string;1991  userDisplayName?: string;1992}): void {1993  const domain = location.hostname.replace(/^www\./, "");1994  const displayName = args.rpName || domain;19951996  const host = document.createElement("div");1997  host.setAttribute("data-peach-passkey-offer", "1");1998  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";1999  const shadow = host.attachShadow({ mode: "closed" });20002001  const style = document.createElement("style");2002  style.textContent = `2003    :host { all: initial; }2004    .offer-wrap {2005      position: fixed;2006      top: 16px;2007      right: 16px;2008      width: 320px;2009      pointer-events: auto;2010      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2011    }2012    @keyframes o-in {2013      from { opacity: 0; transform: translateY(-6px); }2014      to   { opacity: 1; transform: translateY(0); }2015    }2016    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2017    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2018    .offer {2019      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2020      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2021      border-radius: 12px;2022      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2023      padding: 14px 14px 12px;2024      font-family: Inter, sans-serif;2025      position: relative;2026    }2027    .offer-close {2028      position: absolute;2029      top: 8px;2030      right: 8px;2031      width: 18px;2032      height: 18px;2033      border: none;2034      background: transparent;2035      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2036      cursor: pointer;2037      font-size: 14px;2038      line-height: 1;2039      padding: 0;2040    }2041    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2042    .offer-header {2043      display: flex;2044      align-items: center;2045      gap: 7px;2046      margin-bottom: 8px;2047      padding-bottom: 8px;2048      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2049    }2050    .offer-domain {2051      font-size: 12px;2052      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2053      font-family: "IBM Plex Mono", monospace;2054      overflow: hidden;2055      text-overflow: ellipsis;2056      white-space: nowrap;2057    }2058    .offer-title {2059      font-size: 13px;2060      font-weight: 500;2061      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2062      margin-bottom: 4px;2063    }2064    .offer-subtitle {2065      font-size: 11px;2066      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2067      line-height: 1.45;2068      margin-bottom: 12px;2069    }2070    .offer-btn {2071      display: block;2072      width: 100%;2073      padding: 8px 0;2074      border-radius: 7px;2075      border: none;2076      cursor: pointer;2077      font-size: 12px;2078      font-family: Inter, sans-serif;2079      font-weight: 500;2080      transition: opacity 100ms;2081      margin-bottom: 6px;2082      text-align: center;2083    }2084    .offer-btn:last-child { margin-bottom: 0; }2085    .offer-btn--accent { background: ${accentHex}; color: #fff; }2086    .offer-btn--accent:hover { opacity: 0.88; }2087    .offer-btn--ghost {2088      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2089      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2090    }2091    .offer-btn--ghost:hover { opacity: 0.75; }2092  `;2093  shadow.appendChild(style);20942095  const wrap = document.createElement("div");2096  wrap.className = "offer-wrap";2097  shadow.appendChild(wrap);20982099  const offer = document.createElement("div");2100  offer.className = "offer";2101  wrap.appendChild(offer);21022103  const closeBtn = document.createElement("button");2104  closeBtn.className = "offer-close";2105  closeBtn.type = "button";2106  closeBtn.setAttribute("aria-label", "Dismiss");2107  closeBtn.textContent = "✕";2108  offer.appendChild(closeBtn);21092110  const header = document.createElement("div");2111  header.className = "offer-header";2112  const icon = document.createElement("span");2113  icon.innerHTML = peachIconSvg();2114  const domainEl = document.createElement("span");2115  domainEl.className = "offer-domain";2116  domainEl.textContent = domain;2117  header.append(icon, domainEl);2118  offer.appendChild(header);21192120  const title = document.createElement("div");2121  title.className = "offer-title";2122  title.textContent = "This site supports passkeys.";2123  offer.appendChild(title);21242125  const subtitle = document.createElement("div");2126  subtitle.className = "offer-subtitle";2127  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2128  offer.appendChild(subtitle);21292130  const saveBtn = document.createElement("button");2131  saveBtn.className = "offer-btn offer-btn--accent";2132  saveBtn.type = "button";2133  saveBtn.textContent = "Save passkey to Peach";2134  offer.appendChild(saveBtn);21352136  const laterBtn = document.createElement("button");2137  laterBtn.className = "offer-btn offer-btn--ghost";2138  laterBtn.type = "button";2139  laterBtn.textContent = "Not now";2140  offer.appendChild(laterBtn);21412142  function dismiss(decline: boolean) {2143    if (decline) {2144      chrome.runtime.sendMessage({2145        type: "PASSKEY_OFFER_DECLINE",2146        payload: { domain },2147      }).catch(() => {});2148    }2149    wrap.classList.add("is-exiting");2150    setTimeout(() => host.remove(), 130);2151  }21522153  saveBtn.addEventListener("click", () => {2154    chrome.runtime.sendMessage({2155      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2156      payload: {2157        rpId: args.rpId,2158        rpName: args.rpName ?? displayName,2159        userName: args.userName ?? "user",2160        userDisplayName: args.userDisplayName,2161      },2162    }).catch(() => {});2163    dismiss(false);2164  });2165  laterBtn.addEventListener("click", () => dismiss(true));2166  closeBtn.addEventListener("click", () => dismiss(true));21672168  document.body.appendChild(host);2169}21702171/**2172 * State 11 — passkey available indicator. Shown when the user lands on a2173 * domain for which they already have a stored passkey. Tells them where to2174 * find it (the entry already shows in the vault list); the "Sign in with2175 * passkey" button opens the popup so they can use the platform authenticator2176 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2177 * the actual sign-in transparently, so this banner is informational only.2178 */2179export function showPasskeyAvailable(args: {2180  rpId: string;2181  userName: string;2182  fromBrowser?: "chrome" | "firefox";2183  currentBrowser?: "chrome" | "firefox" | "unknown";2184}): void {2185  const domain = location.hostname.replace(/^www\./, "");2186  const crossBrowser =2187    args.fromBrowser &&2188    args.currentBrowser &&2189    args.currentBrowser !== "unknown" &&2190    args.fromBrowser !== args.currentBrowser;21912192  const host = document.createElement("div");2193  host.setAttribute("data-peach-passkey-available", "1");2194  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2195  const shadow = host.attachShadow({ mode: "closed" });21962197  const style = document.createElement("style");2198  style.textContent = `2199    :host { all: initial; }2200    .avail-wrap {2201      position: fixed;2202      top: 16px;2203      right: 16px;2204      width: 320px;2205      pointer-events: auto;2206      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;2207    }2208    @keyframes a-in {2209      from { opacity: 0; transform: translateY(-6px); }2210      to   { opacity: 1; transform: translateY(0); }2211    }2212    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }2213    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }2214    .avail {2215      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2216      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2217      border-radius: 12px;2218      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2219      padding: 14px 14px 12px;2220      font-family: Inter, sans-serif;2221      position: relative;2222    }2223    .avail-close {2224      position: absolute;2225      top: 8px;2226      right: 8px;2227      width: 18px;2228      height: 18px;2229      border: none;2230      background: transparent;2231      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2232      cursor: pointer;2233      font-size: 14px;2234      line-height: 1;2235      padding: 0;2236    }2237    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2238    .avail-header {2239      display: flex;2240      align-items: center;2241      gap: 7px;2242      margin-bottom: 8px;2243      padding-bottom: 8px;2244      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2245    }2246    .avail-domain {2247      font-size: 12px;2248      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2249      font-family: "IBM Plex Mono", monospace;2250    }2251    .avail-label {2252      font-size: 9px;2253      letter-spacing: 0.16em;2254      text-transform: uppercase;2255      color: ${accentHex};2256      margin-bottom: 4px;2257    }2258    .avail-user {2259      font-size: 13px;2260      font-weight: 500;2261      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2262      margin-bottom: 12px;2263      overflow: hidden;2264      text-overflow: ellipsis;2265      white-space: nowrap;2266    }2267    .avail-cross {2268      font-size: 11px;2269      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2270      line-height: 1.45;2271      margin-bottom: 12px;2272      padding: 8px;2273      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};2274      border-radius: 6px;2275    }2276    .avail-btn {2277      display: block;2278      width: 100%;2279      padding: 8px 0;2280      border-radius: 7px;2281      border: none;2282      cursor: pointer;2283      font-size: 12px;2284      font-family: Inter, sans-serif;2285      font-weight: 500;2286      transition: opacity 100ms;2287      margin-bottom: 6px;2288      text-align: center;2289    }2290    .avail-btn:last-child { margin-bottom: 0; }2291    .avail-btn--accent { background: ${accentHex}; color: #fff; }2292    .avail-btn--accent:hover { opacity: 0.88; }2293    .avail-btn--ghost {2294      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2295      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2296    }2297    .avail-btn--ghost:hover { opacity: 0.75; }2298  `;2299  shadow.appendChild(style);23002301  const wrap = document.createElement("div");2302  wrap.className = "avail-wrap";2303  shadow.appendChild(wrap);23042305  const avail = document.createElement("div");2306  avail.className = "avail";2307  wrap.appendChild(avail);23082309  const closeBtn = document.createElement("button");2310  closeBtn.className = "avail-close";2311  closeBtn.type = "button";2312  closeBtn.setAttribute("aria-label", "Dismiss");2313  closeBtn.textContent = "✕";2314  avail.appendChild(closeBtn);23152316  const header = document.createElement("div");2317  header.className = "avail-header";2318  const icon = document.createElement("span");2319  icon.innerHTML = peachIconSvg();2320  const domainEl = document.createElement("span");2321  domainEl.className = "avail-domain";2322  domainEl.textContent = domain;2323  header.append(icon, domainEl);2324  avail.appendChild(header);23252326  const label = document.createElement("div");2327  label.className = "avail-label";2328  label.textContent = "PASSKEY";2329  avail.appendChild(label);23302331  const user = document.createElement("div");2332  user.className = "avail-user";2333  user.textContent = args.userName;2334  avail.appendChild(user);23352336  if (crossBrowser) {2337    const cross = document.createElement("div");2338    cross.className = "avail-cross";2339    cross.textContent =2340      args.fromBrowser === "chrome"2341        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."2342        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";2343    avail.appendChild(cross);2344  }23452346  const signInBtn = document.createElement("button");2347  signInBtn.className = "avail-btn avail-btn--accent";2348  signInBtn.type = "button";2349  signInBtn.textContent = "Sign in with passkey";2350  avail.appendChild(signInBtn);23512352  const passwordBtn = document.createElement("button");2353  passwordBtn.className = "avail-btn avail-btn--ghost";2354  passwordBtn.type = "button";2355  passwordBtn.textContent = "Use password instead";2356  avail.appendChild(passwordBtn);23572358  function dismiss() {2359    wrap.classList.add("is-exiting");2360    setTimeout(() => host.remove(), 130);2361  }23622363  signInBtn.addEventListener("click", () => {2364    // On Chrome: the user clicking the page's own Sign-in button is what2365    //   triggers webAuthenticationProxy → existing background flow handles it.2366    //   Our button just dismisses since the page itself drives auth.2367    // On Firefox: cross-browser passkeys can't be used, so we just dismiss2368    //   and surface the entry for manual reference (popup view).2369    dismiss();2370    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});2371  });2372  passwordBtn.addEventListener("click", dismiss);2373  closeBtn.addEventListener("click", dismiss);23742375  document.body.appendChild(host);2376}23772378/**2379 * State 7 — card silver platter. Single-card focused fill view rendered2380 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the2381 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes2382 * so card and login flows render identically. Multi-card list view is a2383 * follow-up; today this picks the first card.2384 */2385export function showCardSelector(2386  anchorEl: HTMLInputElement,2387  cards: CardSelectorEntry[],2388  options: CardSelectorOptions2389): () => void {2390  if (cards.length === 0) return () => {};2391  const card = cards[0]!;23922393  const host = document.createElement("div");2394  host.style.cssText = "position: absolute; z-index: 2147483647;";2395  host.style.setProperty("--peach-accent", accentHex);2396  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2397  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2398  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2399  const shadow = host.attachShadow({ mode: "closed" });24002401  const style = shadow.appendChild(document.createElement("style"));2402  style.textContent = SELECTOR_STYLES;24032404  const rect = anchorEl.getBoundingClientRect();2405  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2406  host.style.left = `${rect.left + window.scrollX}px`;2407  host.style.width = `${Math.max(rect.width, 320)}px`;24082409  const container = shadow.appendChild(document.createElement("div"));2410  container.className = "peach-inline-popup";2411  container.setAttribute("data-theme", popupTheme);24122413  // Domain header — eyebrow communicates the card context, not the site2414  const domHdr = document.createElement("div");2415  domHdr.className = "domain-header";2416  const eyebrow = document.createElement("div");2417  eyebrow.className = "domain-eyebrow";2418  eyebrow.textContent = "Pay with Peach";2419  const domName = document.createElement("div");2420  domName.className = "domain-name";2421  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2422  domHdr.append(eyebrow, domName);2423  container.appendChild(domHdr);24242425  const platter = document.createElement("div");2426  platter.className = "card-platter";24272428  if (card.network && card.network !== "unknown") {2429    const net = document.createElement("div");2430    net.className = "cp-network";2431    net.textContent = card.network;2432    platter.appendChild(net);2433  }24342435  const nick = document.createElement("div");2436  nick.className = "cp-nickname";2437  nick.textContent = card.title;2438  platter.appendChild(nick);24392440  if (card.last4) {2441    const l4 = document.createElement("div");2442    l4.className = "cp-last4";2443    l4.textContent = `•••• ${card.last4}`;2444    platter.appendChild(l4);2445  }24462447  const meta = document.createElement("div");2448  meta.className = "cp-meta";2449  if (card.cardholderName) {2450    const name = document.createElement("span");2451    name.textContent = card.cardholderName;2452    meta.appendChild(name);2453  }2454  if (card.expMonth && card.expYear) {2455    if (card.cardholderName) {2456      const sep = document.createElement("span");2457      sep.className = "cp-meta-sep";2458      sep.textContent = "·";2459      meta.appendChild(sep);2460    }2461    const exp = document.createElement("span");2462    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;2463    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;2464    meta.appendChild(exp);2465  }2466  if (meta.childElementCount > 0) platter.appendChild(meta);24672468  const fillWrap = document.createElement("div");2469  fillWrap.className = "cp-fill-wrap";2470  const fillBtn = document.createElement("button");2471  fillBtn.className = "sp-fill-btn";2472  fillBtn.type = "button";2473  fillBtn.textContent = "Fill card details";2474  fillBtn.addEventListener("click", async () => {2475    if (fillBtn.disabled) return;2476    fillBtn.disabled = true;2477    fillBtn.classList.add("filled");2478    fillBtn.innerHTML = checkSvgStr();2479    const resp = await chrome.runtime.sendMessage({2480      type: "GET_ENTRY_FOR_FILL",2481      payload: { id: card.id },2482    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;2483    if (resp?.ok && resp.data) options.onFill(resp.data);2484    setTimeout(() => dismiss(), 400);2485  });2486  fillWrap.appendChild(fillBtn);2487  platter.appendChild(fillWrap);24882489  // Secondary actions — copy number, copy CVC, dismiss2490  const actions = document.createElement("div");2491  actions.className = "sp-actions";24922493  function flashBtn(b: HTMLButtonElement) {2494    b.classList.add("flashed");2495    setTimeout(() => b.classList.remove("flashed"), 700);2496  }24972498  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {2499    const resp = await chrome.runtime.sendMessage({2500      type: "GET_ENTRY_FOR_FILL",2501      payload: { id: card.id },2502    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;2503    return resp?.ok && resp.data ? resp.data : null;2504  }25052506  const copyNum = document.createElement("button");2507  copyNum.className = "sp-action-btn";2508  copyNum.type = "button";2509  copyNum.title = "Copy card number";2510  copyNum.textContent = "Copy number";2511  copyNum.addEventListener("click", async (e) => {2512    e.stopPropagation();2513    const full = await fetchFullCard();2514    if (!full?.cardNumber) return;2515    let alreadyWritten = false;2516    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}2517    await chrome.runtime.sendMessage({2518      type: "COPY",2519      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },2520    }).catch(() => {});2521    flashBtn(copyNum);2522  });2523  actions.appendChild(copyNum);25242525  const copyCvc = document.createElement("button");2526  copyCvc.className = "sp-action-btn";2527  copyCvc.type = "button";2528  copyCvc.title = "Copy CVC";2529  copyCvc.textContent = "Copy CVC";2530  copyCvc.addEventListener("click", async (e) => {2531    e.stopPropagation();2532    const full = await fetchFullCard();2533    if (!full?.cvc) return;2534    let alreadyWritten = false;2535    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}2536    await chrome.runtime.sendMessage({2537      type: "COPY",2538      payload: { text: full.cvc, label: "CVC", alreadyWritten },2539    }).catch(() => {});2540    flashBtn(copyCvc);2541  });2542  actions.appendChild(copyCvc);25432544  const closeBtn = document.createElement("button");2545  closeBtn.className = "sp-action-btn";2546  closeBtn.type = "button";2547  closeBtn.title = "Dismiss";2548  closeBtn.textContent = "✕";2549  closeBtn.addEventListener("click", (e) => {2550    e.stopPropagation();2551    dismiss(true);2552  });2553  actions.appendChild(closeBtn);25542555  platter.appendChild(actions);2556  container.appendChild(platter);25572558  document.body.appendChild(host);2559  function updatePosition() {2560    const r = anchorEl.getBoundingClientRect();2561    host.style.top = `${r.bottom + window.scrollY + 5}px`;2562    host.style.left = `${r.left + window.scrollX}px`;2563    host.style.width = `${Math.max(r.width, 320)}px`;2564  }2565  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);25662567  function onKeyDown(e: KeyboardEvent) {2568    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2569  }2570  document.addEventListener("keydown", onKeyDown);25712572  let exitScheduled = false;2573  function dismiss(userAction = false) {2574    if (exitScheduled) return;2575    exitScheduled = true;2576    stopObserving();2577    document.removeEventListener("click", outsideClick, { capture: true });2578    document.removeEventListener("keydown", onKeyDown);2579    if (userAction) options.onDismiss?.();2580    container.classList.add("is-exiting");2581    setTimeout(() => host.remove(), 130);2582  }25832584  function outsideClick(ev: MouseEvent) {2585    const path = ev.composedPath();2586    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2587  }2588  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);25892590  return dismiss;2591}