inject.ts

124.8 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { generatePassword, 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  email?: string;41  url?: string;42  hasTotp?: boolean;43  /** True when the entry also has a passkey credential attached. */44  hasPasskey?: boolean;45}4647interface SelectorOptions {48  domain?: string;49  searchableEntries?: SelectorEntry[];50  /** True when shown on a signup form — changes header label and entry-click behaviour */51  isSignup?: boolean;52  /**53   * Derived identity list (emails then usernames) for signup mode (State 10).54   * When present, renderIdentityHelper() is used instead of renderList().55   */56  savedIdentities?: SavedIdentity[];57  /**58   * Called after the user picks a saved identity (signup mode only) or59   * after successfully saving a new entry on a signup form.60   * Lets the caller fill the visible username + password fields.61   */62  onFillFields?: (username: string, password: string) => void;63  /**64   * When true, show an inline unlock form instead of the entries list.65   * Used when the vault is locked so the user can unlock without opening66   * the popup.67   */68  locked?: boolean;69  /**70   * Called after a successful inline unlock — the caller should re-query71   * entries and re-open the selector with real data.72   */73  onUnlocked?: () => void;74  /**75   * Called when the user explicitly dismisses the selector (Escape, Tab, or76   * click outside) — NOT when an entry is selected or on auto-close.77   * Used by the caller to suppress spurious reopens on the same field.78   */79  onDismiss?: () => void;80}8182function getDomainFromUrl(url: string): string {83  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }84}8586function keySvgStr(): string {87  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" stroke="rgba(240,232,216,0.35)" stroke-width="0.95" stroke-linecap="round"><rect x="2" y="5.5" width="8" height="6" rx="1.5"/><path d="M4 5.5V4.25A2 2 0 0 1 6 2.25A2 2 0 0 1 8 4.25V5.5"/></svg>`;88}8990function plusSvgStr(): string {91  return `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M6 1.5v9M1.5 6h9"/></svg>`;92}9394function peachIconSvg(): string {95  // Peach body is always brand-peach (#D96830), not `accentHex` — a sage96  // or sky accent must not turn the autofill icon green or blue. Accent97  // color still tints surrounding glow/hover halos below.98  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>`;99}100101function genSvgStr(): string {102  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>`;103}104105function checkSvgStr(): string {106  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>`;107}108109function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {110  const { hostname, origin } = location;111  const parts = hostname.split(".");112  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",113    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",114    "oidc", "federation", "saml", "cas", "ldap"];115  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());116  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;117  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);118  return { origin, title, loginSubdomain };119}120121/**122 * Shows a bottom-of-page toast after filling credentials when the entry has123 * never matched the current site — offering to add the current origin to the124 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.125 */126export function showRememberSiteToast(127  pageDomain: string,128  entryId: string,129): void {130  const host = document.createElement("div");131  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";132  host.style.setProperty("--peach-accent", accentHex);133  const shadow = host.attachShadow({ mode: "closed" });134135  const style = document.createElement("style");136  style.textContent = `137    .bar {138      display:flex;align-items:center;gap:10px;padding:10px 14px;139      background:#131109;border:1px solid rgba(240,232,216,0.09);140      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);141      font-family:Inter,sans-serif;white-space:nowrap;142      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;143    }144    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }145    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }146    .yes {147      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;148      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;149    }150    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }151    .no {152      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;153      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;154    }155  `;156  shadow.appendChild(style);157158  const bar = document.createElement("div"); bar.className = "bar";159  const txt = document.createElement("span"); txt.className = "txt";160  txt.textContent = `Remember ${pageDomain} for this entry?`;161  const yesBtn = document.createElement("button"); yesBtn.className = "yes";162  yesBtn.textContent = "Remember";163  yesBtn.addEventListener("click", async () => {164    await chrome.runtime.sendMessage({165      type: "ADD_ADDITIONAL_URL",166      payload: { id: entryId, url: location.origin },167    });168    host.remove();169  });170  const noBtn = document.createElement("button"); noBtn.className = "no";171  noBtn.textContent = "Not now";172  noBtn.addEventListener("click", () => host.remove());173  bar.append(txt, yesBtn, noBtn);174  shadow.appendChild(bar);175  document.body.appendChild(host);176  setTimeout(() => host.remove(), 9000);177}178179function generatePasswordForSite(policy: PasswordPolicy = {}): string {180  return generateSmartPassword(policy);181}182183interface SmartGenerator {184  root: HTMLElement;185  getPassword: () => string;186  /** Copy the current password to the clipboard with the standard pulse UX. */187  copy: () => Promise<void>;188}189190interface SmartGeneratorOptions {191  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */192  policy: PasswordPolicy;193  /**194   * Seed value: used as the displayed password without regenerating, e.g. the195   * password the user already typed into the page. The generator still196   * regenerates the moment any control changes.197   */198  initialPassword?: string;199  /** Fires every time the password regenerates (initial + on changes). */200  onChange?: (pw: string) => void;201}202203/**204 * Build the inline-popup smart-password generator. Mirrors the main popup's205 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset206 * pills + a policy hint that names the constraints Peach detected on the207 * page. Writing this in pure DOM rather than reusing the Solid component208 * keeps the content-script bundle small.209 */210function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {211  const policy = opts.policy ?? {};212213  let length = 64;214  if (policy.minLength) length = Math.max(length, policy.minLength);215  if (policy.maxLength) length = Math.min(length, policy.maxLength);216  if (length < 8) length = 8;217  if (length > 128) length = 128;218219  let upper = true;220  let lower = true;221  let numbers = true;222  let symbols = !policy.forbidsSymbols;223  if (policy.requiresSymbols) symbols = true;224  const forbiddenChars = policy.forbiddenChars ?? "";225226  let password = "";227228  const root = document.createElement("div");229  root.className = "pwgen-block";230231  const displayRow = root.appendChild(document.createElement("div"));232  displayRow.className = "pwgen-display-row";233  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;234  output.type = "text";235  output.className = "pwgen-output";236  output.setAttribute("autocomplete", "off");237  output.setAttribute("spellcheck", "false");238  output.setAttribute("autocorrect", "off");239  output.setAttribute("autocapitalize", "off");240241  const regenBtn = displayRow.appendChild(document.createElement("button"));242  regenBtn.className = "pwgen-icon-btn";243  regenBtn.type = "button";244  regenBtn.setAttribute("aria-label", "Regenerate password");245  regenBtn.title = "Regenerate";246  regenBtn.innerHTML = `<svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round"><path d="M11 2.5A5.5 5.5 0 1 0 12.5 7"/><path d="M9.5 2.5H11V1"/></svg>`;247248  const copyBtn = displayRow.appendChild(document.createElement("button"));249  copyBtn.className = "pwgen-icon-btn";250  copyBtn.type = "button";251  copyBtn.setAttribute("aria-label", "Copy password");252  copyBtn.title = "Copy";253  copyBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="8" height="9" rx="1.5"/><path d="M10 4V2.5A1.5 1.5 0 0 0 8.5 1h-6A1.5 1.5 0 0 0 1 2.5v7A1.5 1.5 0 0 0 2.5 11H4"/></svg>`;254255  const controls = root.appendChild(document.createElement("div"));256  controls.className = "pwgen-controls-row";257  const slider = controls.appendChild(document.createElement("input"));258  slider.type = "range";259  slider.className = "pwgen-slider";260  slider.min = "8";261  slider.max = "128";262  slider.value = String(length);263  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));264  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));265  const lenNum = controls.appendChild(document.createElement("span"));266  lenNum.className = "pwgen-len-num pwgen-len-num--edit";267  lenNum.textContent = String(length);268  lenNum.addEventListener("click", () => {269    const li = document.createElement("input");270    li.type = "text"; li.inputMode = "numeric";271    li.className = "pwgen-len-input"; li.value = String(length);272    lenNum.replaceWith(li);273    requestAnimationFrame(() => li.select());274    function commitLenEdit() {275      const n = parseInt(li.value, 10);276      if (!isNaN(n)) {277        length = Math.max(8, Math.min(128, n));278        slider.value = String(length);279        regenerate();280      }281      lenNum.textContent = String(length);282      li.replaceWith(lenNum);283    }284    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });285    li.addEventListener("blur", commitLenEdit);286  });287288  const pills = root.appendChild(document.createElement("div"));289  pills.className = "pwgen-pills";290291  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {292    const b = document.createElement("button");293    b.type = "button";294    b.className = `pwgen-pill ${on ? "is-on" : ""}`;295    b.textContent = label;296    b.addEventListener("click", () => {297      const next = !b.classList.contains("is-on");298      b.classList.toggle("is-on", next);299      onToggle(next);300    });301    return b;302  }303  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));304  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));305  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));306  pills.appendChild(makePill("!@#", symbols, (next) => {307    // The site forbids symbols — UI lets the user override but still warn.308    symbols = next;309    regenerate();310  }));311312  // Policy hint — surfaces what Peach read off the site so the user knows the313  // generator is already tuned to it. Only shows when something interesting314  // was detected.315  const hintParts: string[] = [];316  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);317  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);318  if (policy.requiresSymbols) hintParts.push("requires symbols");319  if (policy.forbidsSymbols) hintParts.push("no symbols");320  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);321  if (hintParts.length > 0) {322    const hint = root.appendChild(document.createElement("div"));323    hint.className = "pwgen-policy-hint";324    const accent = document.createElement("span");325    accent.className = "pwgen-hint-accent";326    accent.textContent = "site rules · ";327    const text = document.createTextNode(hintParts.join(" · "));328    hint.appendChild(accent);329    hint.appendChild(text);330  }331332  function regenerate() {333    // Falls back gracefully when the user toggles every charset off — the334    // shared generator forces lowercase in that case rather than throwing.335    password = generatePassword({336      length,337      includeUppercase: upper,338      includeLowercase: lower,339      includeNumbers: numbers,340      includeSymbols: symbols,341      forbiddenChars,342    });343    output.value = password;344    opts.onChange?.(password);345  }346347  output.addEventListener("input", () => {348    password = output.value;349    opts.onChange?.(password);350  });351352  slider.addEventListener("input", () => {353    length = parseInt(slider.value, 10);354    lenNum.textContent = String(length);355    regenerate();356  });357  regenBtn.addEventListener("click", regenerate);358359  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;360  async function copy(): Promise<void> {361    try {362      await navigator.clipboard.writeText(password);363      copyBtn.classList.add("is-copied");364      if (copyResetTimer) clearTimeout(copyResetTimer);365      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);366    } catch {367      // Clipboard API may be denied — silently no-op; user still has regen UI.368    }369  }370  copyBtn.addEventListener("click", () => { void copy(); });371372  if (opts.initialPassword) {373    password = opts.initialPassword;374    output.value = password;375    opts.onChange?.(password);376  } else {377    regenerate();378  }379380  return {381    root,382    getPassword: () => password,383    copy,384  };385}386387export function observeAnchorPosition(388  anchorEl: HTMLElement,389  onUpdate: () => void390): () => void {391  let rafId = 0;392  let burstUntil = 0;393394  const runUpdate = () => {395    rafId = 0;396    onUpdate();397    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);398  };399  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };400  const scheduleBurst = (ms = 220) => {401    burstUntil = Math.max(burstUntil, performance.now() + ms);402    scheduleUpdate();403  };404405  const resizeObserver = new ResizeObserver(() => scheduleBurst());406  resizeObserver.observe(anchorEl);407  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);408409  const mutationObserver = new MutationObserver(() => scheduleBurst());410  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });411  if (anchorEl.parentElement) {412    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });413  }414415  const onScroll = () => scheduleUpdate();416  window.addEventListener("scroll", onScroll, true);417  window.addEventListener("resize", onScroll);418  window.visualViewport?.addEventListener("resize", onScroll);419  window.visualViewport?.addEventListener("scroll", onScroll);420  anchorEl.addEventListener("focus", () => scheduleBurst());421  anchorEl.addEventListener("input", () => scheduleBurst());422423  scheduleBurst(260);424425  return () => {426    if (rafId) cancelAnimationFrame(rafId);427    resizeObserver.disconnect();428    mutationObserver.disconnect();429    window.removeEventListener("scroll", onScroll, true);430    window.removeEventListener("resize", onScroll);431    window.visualViewport?.removeEventListener("resize", onScroll);432    window.visualViewport?.removeEventListener("scroll", onScroll);433  };434}435436export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {437  const button = document.createElement("button");438  button.type = "button";439  button.setAttribute("aria-label", "Peach autofill");440  button.title = "Fill with Peach";441  button.innerHTML = peachIconSvg();442  // position: fixed is load-bearing — not absolute. Absolute positioning443  // inherits the nearest positioned ancestor's box, which on sites with444  // overflow:hidden or sticky parents clips or offsets the icon. Fixed445  // anchors to the viewport and escapes all parent layout.446  button.style.cssText = `447    position: fixed; z-index: 2147483646;448    width: 26px; height: 26px; cursor: pointer;449    pointer-events: auto; border: none; padding: 3px;450    display: inline-flex; align-items: center; justify-content: center;451    background: transparent; border-radius: 999px;452    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;453    opacity: 0;454  `;455  button.addEventListener("mouseenter", () => {456    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;457    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;458    button.style.transform = "scale(1.08)";459  });460  button.addEventListener("mouseleave", () => {461    button.style.background = "transparent";462    button.style.boxShadow = "none";463    button.style.transform = "none";464  });465  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });466  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });467468  document.body.appendChild(button);469470  function updatePosition() {471    const rect = field.getBoundingClientRect();472    if (rect.width === 0 || rect.height === 0) {473      button.style.opacity = "0"; button.style.pointerEvents = "none";474      return;475    }476    const sz = 26;477    const inset = Math.max(5, Math.min(10, rect.height * 0.22));478    const top = rect.top + rect.height / 2 - sz / 2;479    // Clamp left so the icon stays fully inside the field's right edge, never480    // spilling onto an adjacent sibling button.481    const minLeft = rect.left + 4;482    const left = Math.max(minLeft, rect.right - sz - inset);483    // Hide if the field is too narrow to fit the icon cleanly (< 40px)484    if (rect.width < 40) {485      button.style.opacity = "0"; button.style.pointerEvents = "none";486      return;487    }488    button.style.top = `${top}px`;489    button.style.left = `${left}px`;490    button.style.opacity = "1"; button.style.pointerEvents = "auto";491  }492  updatePosition();493  requestAnimationFrame(() => { button.style.opacity = "1"; });494  const stopObserving = observeAnchorPosition(field, updatePosition);495  return () => { stopObserving(); button.remove(); };496}497498// All theme-dependent values resolve through tokens scoped to499// .peach-inline-popup[data-theme="dark|light"]. Accent variables500// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)501// are identical in both themes — only surface tokens differ. See502// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the503// theme switch — only literal brand-peach in peachIconSvg may stay raw.504const SELECTOR_STYLES = `505  :host { all: initial; }506  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }507508  .peach-inline-popup[data-theme="dark"] {509    --peach-bg:           #1a1410;510    --peach-bg-card:      #221c16;511    --peach-text:         #f5f0ea;512    --peach-text-dim:     #8a7a6a;513    --peach-text-muted:   #4a3a2a;514    --peach-border:       rgba(255,255,255,0.07);515    --peach-input-bg:     rgba(255,255,255,0.05);516    --peach-input-border: rgba(255,255,255,0.08);517  }518  .peach-inline-popup[data-theme="light"] {519    --peach-bg:           #fdf8f4;520    --peach-bg-card:      #f5ede4;521    --peach-text:         #1c1310;522    --peach-text-dim:     #6b5a4a;523    --peach-text-muted:   #a89080;524    --peach-border:       rgba(0,0,0,0.08);525    --peach-input-bg:     rgba(0,0,0,0.04);526    --peach-input-border: rgba(0,0,0,0.10);527  }528529  .peach-inline-popup {530    background: var(--peach-bg);531    border: 1px solid var(--peach-border-accent, var(--peach-border));532    border-radius: 14px;533    overflow: hidden;534    box-shadow:535      0 8px 40px var(--peach-glow, transparent),536      0 2px 12px rgba(0,0,0,0.5);537    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;538    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;539  }540  /* Light theme: shadow against a light page is too strong otherwise — drop both541     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */542  .peach-inline-popup[data-theme="light"] {543    box-shadow:544      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),545      0 2px 12px rgba(0,0,0,0.12);546  }547  .peach-inline-popup.is-exiting {548    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;549    pointer-events: none;550  }551552  @keyframes peach-enter {553    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }554    65%  { opacity: 1; filter: blur(0); }555    100% { opacity: 1; transform: translateY(0) scale(1); }556  }557  @keyframes peach-exit {558    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }559    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }560  }561  @keyframes peach-slide-in {562    from { opacity: 0; transform: translateX(12px); }563    to   { opacity: 1; transform: translateX(0); }564  }565  @keyframes peach-slide-back {566    from { opacity: 0; transform: translateX(-12px); }567    to   { opacity: 1; transform: translateX(0); }568  }569  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }570  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }571572  /* Domain header */573  .domain-header {574    padding: 9px 13px 7px;575    border-bottom: 1px solid var(--peach-border);576    display: flex; align-items: center; justify-content: space-between;577    gap: 8px;578  }579  .domain-header-text {580    display: flex; flex-direction: column; gap: 2px;581    min-width: 0; flex: 1;582  }583  .domain-eyebrow {584    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;585    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;586  }587  .domain-name {588    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);589    font-family: "IBM Plex Mono", monospace;590    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;591  }592  .domain-add-btn {593    flex-shrink: 0;594    width: 22px; height: 22px;595    display: inline-flex; align-items: center; justify-content: center;596    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);597    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);598    border-radius: 6px;599    color: var(--peach-accent);600    cursor: pointer; padding: 0;601    transition: background 120ms, border-color 120ms, transform 80ms;602    font-family: "IBM Plex Mono", monospace;603    font-size: 14px; line-height: 1;604  }605  .domain-add-btn:hover {606    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);607    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);608    transform: scale(1.06);609  }610  .domain-add-btn:active { transform: scale(0.96); }611612  /* Search */613  .search-wrap {614    padding: 9px 12px 7px;615    border-bottom: 1px solid var(--peach-border);616  }617  .search {618    width: 100%; background: var(--peach-input-bg);619    border: 1px solid var(--peach-input-border);620    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;621    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;622    transition: border-color 120ms, box-shadow 120ms;623  }624  .search:focus {625    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);626    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);627  }628  .search::placeholder { color: var(--peach-text-muted); }629630  /* Results */631  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }632  .results::-webkit-scrollbar { display: none; }633634  /* Entry rows */635  .entry {636    display: flex; align-items: center; padding: 8px 12px;637    cursor: pointer; border-bottom: 1px solid var(--peach-border);638    transition: background 70ms; position: relative; outline: none;639  }640  .entry:last-child { border-bottom: none; }641  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }642  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }643  .entry.focused::before {644    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;645    width: 2px; border-radius: 2px;646    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);647  }648649  .entry-icon {650    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;651    background: var(--peach-input-bg); border: 1px solid var(--peach-border);652    display: flex; align-items: center; justify-content: center;653    overflow: hidden; margin-right: 10px;654  }655  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }656  .entry-icon.is-new {657    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);658    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);659    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);660  }661662  .entry-info { flex: 1; min-width: 0; }663  .entry-title {664    font-size: 12.5px; color: var(--peach-text);665    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;666    line-height: 1.3;667  }668  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }669  .entry-sub {670    font-size: 10px; color: var(--peach-text-dim);671    font-family: "IBM Plex Mono", monospace;672    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;673    margin-top: 1px;674  }675676  .totp-badge {677    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;678    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);679    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);680    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;681  }682  .passkey-badge {683    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;684    border-radius: 4px;685    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);686    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);687    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);688    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;689  }690691  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }692693  .empty-hint {694    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);695    font-family: "IBM Plex Mono", monospace;696  }697698  /* Create form */699  .create-form-wrap {700    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;701  }702  .create-head {703    display: flex; align-items: center; gap: 8px;704    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);705  }706  .back-btn {707    background: transparent; border: none; cursor: pointer;708    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;709    display: flex; align-items: center; line-height: 0;710    transition: color 100ms, background 100ms;711  }712  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }713  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }714  /* minmax(0, 1fr) caps the grid track at the popup width — without it,715     long monospace content (e.g. a 60-char generated password) would716     auto-size the track wider than the popup and overflow the right edge. */717  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }718  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }719  .f-label {720    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;721    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;722  }723  .f-input {724    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);725    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;726    font-size: 11px; font-family: "IBM Plex Mono", monospace;727    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;728  }729  .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); }730  .f-input::placeholder { color: var(--peach-text-muted); }731  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }732  .f-row { display: flex; gap: 6px; }733  .f-row .f-input { flex: 1; min-width: 0; }734  .gen-btn {735    padding: 0 10px; border-radius: 7px; border: none;736    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);737    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);738    font-size: 10px; font-family: "IBM Plex Mono", monospace;739    cursor: pointer; white-space: nowrap; flex-shrink: 0;740    display: flex; align-items: center; gap: 4px;741    transition: background 100ms;742  }743  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }744  .save-btn {745    width: 100%; padding: 8px; border-radius: 8px; border: none;746    background: var(--peach-accent); color: #fff; font-size: 12px;747    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;748    transition: background 120ms, box-shadow 120ms, transform 80ms;749    letter-spacing: 0.01em;750  }751  .save-btn:hover {752    background: color-mix(in srgb, var(--peach-accent) 82%, #000);753    box-shadow: 0 4px 20px var(--peach-glow, transparent);754  }755  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }756  .url-hint {757    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);758    font-family: "IBM Plex Mono", monospace; font-style: italic;759  }760761  /* Success */762  .success-wrap {763    display: flex; flex-direction: column; align-items: center;764    padding: 24px 16px 20px; gap: 8px;765    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;766  }767  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }768  .success-ring {769    width: 40px; height: 40px; border-radius: 50%;770    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);771    display: flex; align-items: center; justify-content: center;772  }773  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }774  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }775776  /* Silver platter (State 1 — single match) */777  .silver-platter {778    padding: 14px 14px 12px;779    display: flex; flex-direction: column; gap: 6px;780  }781  .sp-title {782    font-size: 14px; font-weight: 500; color: var(--peach-text);783    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;784    line-height: 1.25;785  }786  .sp-identity-row {787    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;788  }789  .sp-identity-label {790    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;791    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;792  }793  .sp-username {794    font-size: 12px; color: var(--peach-text-dim);795    font-family: "IBM Plex Mono", monospace;796    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;797    margin-bottom: 0;798  }799  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }800  .sp-fill-btn {801    width: 100%; padding: 11px; border-radius: 9px; border: none;802    background: var(--peach-accent); color: #fff;803    font-size: 13px; font-weight: 500; cursor: pointer;804    font-family: Inter, sans-serif; letter-spacing: 0.01em;805    display: flex; align-items: center; justify-content: center; min-height: 38px;806    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;807  }808  .sp-fill-btn:hover {809    filter: brightness(1.1);810    box-shadow: 0 4px 20px var(--peach-glow, transparent);811    transform: translateY(-1px);812  }813  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }814  .sp-fill-btn.filled {815    background: #16a34a; transform: none; filter: none;816    box-shadow: 0 4px 16px rgba(22,163,74,0.35);817    cursor: default;818  }819  .sp-fill-btn:disabled { cursor: default; }820  .sp-actions {821    display: flex; gap: 4px; justify-content: space-between; align-items: center;822    margin-top: 4px;823  }824  .sp-action-btn {825    flex: 1; height: 28px; border: none; border-radius: 6px;826    background: transparent; color: var(--peach-text-dim);827    font-size: 12px; cursor: pointer;828    transition: background 120ms ease, color 120ms ease;829    font-family: Inter, sans-serif; letter-spacing: 0.04em;830    display: inline-flex; align-items: center; justify-content: center; gap: 4px;831    white-space: nowrap; overflow: hidden;832  }833  .sp-action-btn:hover:not(:disabled) {834    background: color-mix(in srgb, var(--peach-text) 5%, transparent);835    color: var(--peach-text);836  }837  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }838  .sp-action-btn.flashed {839    color: var(--peach-accent);840    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);841  }842843  /* TOTP tray — shown below the silver-platter secondary actions */844  .sp-tray {845    margin-top: 8px;846    padding: 10px 12px;847    border-radius: 9px;848    background: var(--peach-input-bg);849    border: 1px solid var(--peach-input-border);850    display: flex; align-items: center; gap: 12px;851    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;852  }853  .sp-tray-label {854    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;855    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;856    flex-shrink: 0;857  }858  .sp-totp-code {859    font-size: 18px; font-weight: 500;860    color: var(--peach-text);861    font-family: "IBM Plex Mono", monospace;862    letter-spacing: 0.12em;863    flex: 1;864    text-align: center;865  }866  .sp-totp-ring {867    width: 22px; height: 22px; flex-shrink: 0;868  }869  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }870  .sp-totp-ring .ring-fill {871    stroke: var(--peach-accent);872    transition: stroke-dashoffset 1s linear;873    transform: rotate(-90deg);874    transform-origin: center;875  }876  .sp-totp-copy {877    background: transparent; border: none; cursor: pointer;878    padding: 4px 8px; border-radius: 5px;879    color: var(--peach-text-dim); font-size: 11px;880    font-family: Inter, sans-serif;881    transition: background 120ms, color 120ms;882  }883  .sp-totp-copy:hover {884    background: color-mix(in srgb, var(--peach-text) 5%, transparent);885    color: var(--peach-text);886  }887888  /* Card silver platter (State 7) — reuses .sp-* primary action classes */889  .card-platter {890    padding: 12px 14px 10px;891    display: flex; flex-direction: column; gap: 4px;892  }893  .cp-network {894    font-size: 10px; font-weight: 600;895    color: var(--peach-accent);896    letter-spacing: 0.08em; text-transform: uppercase;897    font-family: Inter, sans-serif;898  }899  .cp-nickname {900    font-size: 14px; font-weight: 500; color: var(--peach-text);901    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;902    line-height: 1.2;903  }904  .cp-last4 {905    font-size: 12px; color: var(--peach-text-dim);906    font-family: "IBM Plex Mono", monospace;907    letter-spacing: 0.04em;908    margin-top: 2px;909  }910  .cp-meta {911    font-size: 11px; color: var(--peach-text-dim);912    font-family: "IBM Plex Mono", monospace;913    margin-top: 2px;914    display: flex; gap: 10px; align-items: center;915  }916  .cp-meta-sep { opacity: 0.5; }917  .cp-fill-wrap { margin-top: 10px; }918919  /* Locked state */920  .locked-wrap {921    display: flex; flex-direction: column; align-items: stretch;922    padding: 14px 13px 13px; gap: 9px;923  }924  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }925  .locked-icon {926    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;927    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);928    display: flex; align-items: center; justify-content: center;929  }930  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }931  .locked-input {932    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);933    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;934    font-size: 11px; font-family: "IBM Plex Mono", monospace;935    outline: none; transition: border-color 120ms, box-shadow 120ms;936  }937  .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); }938  .locked-input::placeholder { color: var(--peach-text-muted); }939  .locked-btn {940    width: 100%; padding: 8px; border-radius: 8px; border: none;941    background: var(--peach-accent); color: #fff; font-size: 12px;942    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;943    transition: background 120ms;944    letter-spacing: 0.01em;945    box-shadow: 0 2px 16px var(--peach-glow, transparent);946    animation: peach-pulse-glow 2.4s ease-in-out infinite;947  }948  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }949  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }950  .locked-error {951    font-size: 10px; color: rgba(220,80,60,0.85);952    font-family: "IBM Plex Mono", monospace;953  }954955  @keyframes peach-pulse-glow {956    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }957    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),958                            0 0 48px var(--peach-glow, transparent); }959  }960961  /* ── State 10: identity helper ─────────────────────────────── */962  .identity-list {963    max-height: 192px; overflow-y: auto; padding: 4px 0;964    scrollbar-width: none;965  }966  .identity-list::-webkit-scrollbar { display: none; }967  .peach-identity-row {968    display: flex; align-items: center; gap: 10px;969    padding: 9px 12px; cursor: pointer; border-radius: 8px;970    transition: background 100ms ease;971  }972  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }973  .peach-identity-value {974    font-family: "IBM Plex Mono", monospace; font-size: 13px;975    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;976  }977  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }978  .identity-alt-row {979    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;980    border-radius: 8px; transition: background 100ms ease;981    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;982  }983  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }984  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }985  .identity-alt-input-wrap.open { display: flex; }986  .identity-alt-input {987    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;988    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);989    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;990    outline: none; transition: border-color 120ms;991  }992  .identity-alt-input:focus {993    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);994    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);995  }996  .identity-alt-confirm {997    height: 32px; padding: 0 12px; border-radius: 7px; border: none;998    background: var(--peach-accent); color: #fff; font-size: 12px;999    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1000  }1001  /* ── Generator view (after identity picked) ────────────────── */1002  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1003  .gen-confirmed {1004    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1005    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1006    border-radius: 8px;1007  }1008  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1009  .gen-confirmed-val {1010    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1011    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1012  }1013  .gen-label {1014    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1015    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1016  }1017  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1018  .gen-pw-val {1019    flex: 1; padding: 8px 10px; border-radius: 7px;1020    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1021    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1022    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1023  }1024  .gen-regen-btn {1025    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1026    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1027    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1028    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1029  }1030  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1031  .gen-fill-btn {1032    padding: 10px; border-radius: 8px; border: none;1033    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1034    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1035    transition: filter 120ms ease, transform 80ms ease;1036  }1037  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1038  .gen-fill-btn:active { transform: translateY(0); }10391040  /* ── Smart password generator (parity with main UI compact mode) ─── */1041  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1042  .pwgen-display-row {1043    display: flex; align-items: center; gap: 6px;1044    padding: 8px 10px; border-radius: 7px;1045    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1046  }1047  .pwgen-output {1048    flex: 1; min-width: 0; width: 0;1049    font-family: "IBM Plex Mono", monospace; font-size: 12px;1050    color: var(--peach-text);1051    background: transparent; border: none; outline: none; padding: 0;1052  }1053  .pwgen-icon-btn {1054    flex-shrink: 0;1055    width: 26px; height: 26px;1056    display: inline-flex; align-items: center; justify-content: center;1057    background: transparent; border: 1px solid var(--peach-input-border);1058    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1059    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1060  }1061  .pwgen-icon-btn:hover {1062    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1063    color: var(--peach-accent);1064    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1065  }1066  .pwgen-icon-btn.is-copied {1067    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1068    color: var(--peach-accent);1069    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1070  }1071  .pwgen-controls-row {1072    display: flex; align-items: center; gap: 8px;1073    flex-wrap: wrap;1074  }1075  .pwgen-slider {1076    flex: 1; min-width: 110px;1077    accent-color: var(--peach-accent);1078    cursor: pointer; height: 2px; background: transparent;1079  }1080  .pwgen-len-num {1081    font-family: "IBM Plex Mono", monospace; font-size: 11px;1082    color: var(--peach-accent); min-width: 22px; text-align: right;1083  }1084  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1085  .pwgen-len-input {1086    font-family: "IBM Plex Mono", monospace; font-size: 11px;1087    color: var(--peach-accent); width: 28px; text-align: right;1088    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1089    outline: none; padding: 0; min-width: 22px;1090  }1091  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px; }1092  .identity-suggest-row {1093    display: flex; align-items: center; justify-content: space-between;1094    width: 100%; padding: 4px 8px; border-radius: 5px; border: none;1095    background: transparent; cursor: pointer; text-align: left;1096    transition: background 80ms;1097  }1098  .identity-suggest-row:hover { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); }1099  .identity-suggest-val {1100    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1101    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1102  }1103  .identity-suggest-meta {1104    font-family: "IBM Plex Mono", monospace; font-size: 9px;1105    color: var(--peach-text-muted); flex-shrink: 0; margin-left: 6px;1106  }1107  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1108  .pwgen-pill {1109    padding: 3px 8px; border-radius: 999px;1110    border: 1px solid var(--peach-input-border);1111    background: transparent; color: var(--peach-text-muted);1112    font-family: "IBM Plex Mono", monospace; font-size: 9px;1113    letter-spacing: 0.06em; cursor: pointer;1114    transition: all 130ms ease;1115  }1116  .pwgen-pill.is-on {1117    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1118    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1119    color: var(--peach-accent);1120  }1121  .pwgen-pill:not(.is-on):hover {1122    color: var(--peach-text-dim);1123    border-color: var(--peach-text-muted);1124  }1125  .pwgen-policy-hint {1126    font-size: 10px; color: var(--peach-text-muted);1127    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1128    line-height: 1.3;1129  }1130  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11311132  /* ── Save offer (after password filled) ───────────────────── */1133  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1134  .save-offer-title {1135    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1136  }1137  .save-offer-row {1138    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1139    border-radius: 7px; background: var(--peach-input-bg);1140    border: 1px solid var(--peach-input-border);1141  }1142  .save-offer-lbl {1143    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1144    font-family: "IBM Plex Mono", monospace;1145  }1146  .save-offer-val {1147    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1148    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1149  }1150  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1151  .save-offer-save {1152    flex: 1; padding: 9px; border-radius: 8px; border: none;1153    background: var(--peach-accent); color: #fff; font-size: 13px;1154    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1155  }1156  .save-offer-save:hover { filter: brightness(1.08); }1157  .save-offer-skip {1158    flex: 1; padding: 9px; border-radius: 8px; border: none;1159    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1160    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1161    font-family: Inter, sans-serif; transition: background 100ms ease;1162  }1163  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1164`;11651166export function showAutofillSelector(1167  anchorEl: HTMLInputElement,1168  entries: SelectorEntry[],1169  onSelect: (id: string) => void,1170  options: SelectorOptions = {}1171): () => void {1172  const host = document.createElement("div");1173  host.style.cssText = "position: absolute; z-index: 2147483647;";1174  host.style.setProperty("--peach-accent", accentHex);1175  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1176  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1177  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1178  const shadow = host.attachShadow({ mode: "closed" });11791180  const style = shadow.appendChild(document.createElement("style"));1181  style.textContent = SELECTOR_STYLES;11821183  const rect = anchorEl.getBoundingClientRect();1184  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1185  host.style.left = `${rect.left + window.scrollX}px`;1186  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1187  // wide single-input fields (e.g. centered email input on signup pages).1188  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;11891190  const container = shadow.appendChild(document.createElement("div"));1191  container.className = "peach-inline-popup";1192  container.setAttribute("data-theme", popupTheme);11931194  const searchableEntries = options.searchableEntries ?? [];1195  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();11961197  let query = "";1198  let focusedIndex = -1;1199  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1200  let searchInput: HTMLInputElement | null = null;1201  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1202  // setInterval. Add to this list — don't fan out the dismiss function.1203  const cleanupHooks: Array<() => void> = [];12041205  // Pre-capture the anchor field value for username prefill1206  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1207  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1208  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";12091210  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1211    const seen = new Set<string>();1212    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1213  }12141215  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1216    const q = value.trim().toLowerCase();1217    const deduped = uniqueEntries(source);1218    if (!q) return deduped.slice(0, 8);1219    return deduped.filter(e =>1220      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1221    ).slice(0, 12);1222  }12231224  function activeEntries(): SelectorEntry[] {1225    // When user is typing a search, filter across all known entries (domain matches + vault)1226    if (query.trim()) {1227      const merged = uniqueEntries([...entries, ...searchableEntries]);1228      return filterEntries(merged, query);1229    }1230    // Default: show domain matches; fall back to vault search when no matches1231    if (entries.length > 0) return entries;1232    return filterEntries(searchableEntries, "").slice(0, 8);1233  }12341235  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1236    const icon = document.createElement("div");1237    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1238    if (isNew) {1239      icon.innerHTML = plusSvgStr();1240    } else {1241      // Use the generic key glyph for all entries in the page-injected selector.1242      // Avoids disclosing vault domains to any third party and avoids needing1243      // to expose the browser favicon API to page context via web_accessible_resources.1244      void url;1245      icon.innerHTML = keySvgStr();1246    }1247    return icon;1248  }12491250  function renderIdentityHelper() {1251    container.innerHTML = "";1252    const identities = options.savedIdentities ?? [];12531254    // Header: "NEW ACCOUNT" + domain name1255    const hdr = container.appendChild(document.createElement("div"));1256    hdr.className = "domain-header";1257    const eyebrow = hdr.appendChild(document.createElement("div"));1258    eyebrow.className = "domain-eyebrow";1259    eyebrow.textContent = "NEW ACCOUNT";1260    const domName = hdr.appendChild(document.createElement("div"));1261    domName.className = "domain-name";1262    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");12631264    // Identity rows1265    const list = container.appendChild(document.createElement("div"));1266    list.className = "identity-list";1267    for (const id of identities) {1268      const row = list.appendChild(document.createElement("div"));1269      row.className = "peach-identity-row";1270      row.setAttribute("tabindex", "-1");1271      const val = row.appendChild(document.createElement("div"));1272      val.className = "peach-identity-value";1273      val.textContent = id.value;1274      const meta = row.appendChild(document.createElement("div"));1275      meta.className = "peach-identity-meta";1276      meta.textContent = `used ${id.useCount}×`;1277      row.addEventListener("click", () => {1278        options.onFillFields?.(id.value, "");1279        renderGenerator(id.value);1280      });1281    }12821283    // Divider before "Use a different email…"1284    if (identities.length > 0) {1285      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1286    }12871288    // "Use a different email…" expandable row1289    const altRow = container.appendChild(document.createElement("div"));1290    altRow.className = "identity-alt-row";1291    altRow.textContent = "+ Use a different email…";12921293    const altInputWrap = container.appendChild(document.createElement("div"));1294    altInputWrap.className = "identity-alt-input-wrap";1295    const altInput = altInputWrap.appendChild(document.createElement("input"));1296    altInput.className = "identity-alt-input";1297    altInput.type = "email";1298    altInput.placeholder = "[email protected]";1299    altInput.setAttribute("autocomplete", "off");1300    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1301    altConfirm.className = "identity-alt-confirm";1302    altConfirm.type = "button";1303    altConfirm.textContent = "✓";13041305    function fillCustomEmail() {1306      const v = altInput.value.trim();1307      if (!v) return;1308      options.onFillFields?.(v, "");1309      renderGenerator(v);1310    }13111312    altRow.addEventListener("click", () => {1313      altRow.style.display = "none";1314      altInputWrap.classList.add("open");1315      altInput.focus();1316    });1317    altConfirm.addEventListener("click", fillCustomEmail);1318    altInput.addEventListener("keydown", (e) => {1319      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1320    });1321  }13221323  function renderGenerator(filledEmail: string) {1324    container.innerHTML = "";1325    const sitePolicy = detectPasswordPolicy();13261327    const wrap = container.appendChild(document.createElement("div"));1328    wrap.className = "gen-view";13291330    // Header: domain + NEW ACCOUNT1331    const hdrRow = wrap.appendChild(document.createElement("div"));1332    hdrRow.className = "domain-header";1333    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1334    eyebrow2.className = "domain-eyebrow";1335    eyebrow2.textContent = "NEW ACCOUNT";1336    const domName2 = hdrRow.appendChild(document.createElement("div"));1337    domName2.className = "domain-name";1338    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13391340    // Confirmed email row1341    const conf = wrap.appendChild(document.createElement("div"));1342    conf.className = "gen-confirmed";1343    const confCheck = conf.appendChild(document.createElement("span"));1344    confCheck.className = "gen-confirmed-check";1345    confCheck.textContent = "✓";1346    const confVal = conf.appendChild(document.createElement("div"));1347    confVal.className = "gen-confirmed-val";1348    confVal.textContent = filledEmail;13491350    const lbl = wrap.appendChild(document.createElement("div"));1351    lbl.className = "gen-label";1352    lbl.textContent = "Generate a password";13531354    let currentPw = "";1355    const smartGen = createSmartGenerator({1356      policy: sitePolicy,1357      onChange: (pw) => { currentPw = pw; },1358    });1359    wrap.appendChild(smartGen.root);13601361    const fillBtn = wrap.appendChild(document.createElement("button"));1362    fillBtn.className = "gen-fill-btn";1363    fillBtn.type = "button";1364    fillBtn.textContent = "Copy & fill";1365    fillBtn.addEventListener("click", () => {1366      if (!currentPw) return;1367      options.onFillFields?.("", currentPw);1368      renderSaveOffer(filledEmail, currentPw);1369    });1370  }13711372  function renderSaveOffer(filledEmail: string, filledPassword: string) {1373    container.innerHTML = "";1374    const domain = options.domain ?? location.hostname.replace(/^www\./, "");13751376    const wrap = container.appendChild(document.createElement("div"));1377    wrap.className = "save-offer";13781379    const title = wrap.appendChild(document.createElement("div"));1380    title.className = "save-offer-title";1381    title.textContent = "Save this login to Peach?";13821383    function detailRow(label: string, value: string) {1384      const row = wrap.appendChild(document.createElement("div"));1385      row.className = "save-offer-row";1386      const lbl = row.appendChild(document.createElement("div"));1387      lbl.className = "save-offer-lbl";1388      lbl.textContent = label;1389      const val = row.appendChild(document.createElement("div"));1390      val.className = "save-offer-val";1391      val.textContent = value;1392    }13931394    detailRow("site", domain);1395    detailRow("email", filledEmail);1396    detailRow("password", "••••••••••••••••");13971398    const btns = wrap.appendChild(document.createElement("div"));1399    btns.className = "save-offer-btns";14001401    const saveBtn = btns.appendChild(document.createElement("button"));1402    saveBtn.className = "save-offer-save";1403    saveBtn.type = "button";1404    saveBtn.textContent = "Save";1405    saveBtn.addEventListener("click", async () => {1406      saveBtn.disabled = true;1407      saveBtn.textContent = "Saving…";1408      try {1409        const res = await chrome.runtime.sendMessage({1410          type: "ADD_ENTRY",1411          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1412        });1413        if ((res as { ok?: boolean }).ok) {1414          showSuccess(sTitle);1415        } else {1416          saveBtn.disabled = false;1417          saveBtn.textContent = "Save";1418        }1419      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1420    });14211422    const skipBtn = btns.appendChild(document.createElement("button"));1423    skipBtn.className = "save-offer-skip";1424    skipBtn.type = "button";1425    skipBtn.textContent = "Not now";1426    skipBtn.addEventListener("click", () => { dismiss(true); });1427  }14281429  function renderList() {1430    container.innerHTML = "";1431    focusedIndex = -1;1432    searchInput = null;14331434    const current = activeEntries();14351436    // Domain header (always show) — eyebrow + domain on the left,1437    // a "+" shortcut to the create form on the right so the user is never1438    // trapped in the search list when they want to make a new entry.1439    const domHdr = document.createElement("div");1440    domHdr.className = "domain-header";1441    const headText = document.createElement("div");1442    headText.className = "domain-header-text";1443    const eyebrow = document.createElement("div");1444    eyebrow.className = "domain-eyebrow";1445    eyebrow.textContent = options.isSignup1446      ? "Sign up as"1447      : entries.length > 0 ? "Saved for this site" : "No saved login";1448    const domName = document.createElement("div");1449    domName.className = "domain-name";1450    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1451    headText.append(eyebrow, domName);1452    domHdr.appendChild(headText);14531454    if (!options.isSignup) {1455      const addBtn = document.createElement("button");1456      addBtn.className = "domain-add-btn";1457      addBtn.type = "button";1458      addBtn.setAttribute("aria-label", "Create new entry");1459      addBtn.title = "Create new entry";1460      addBtn.textContent = "+";1461      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1462      domHdr.appendChild(addBtn);1463    }14641465    container.appendChild(domHdr);14661467    // Search — always show so user can find entries beyond the domain matches1468    const sw = document.createElement("div"); sw.className = "search-wrap";1469    searchInput = document.createElement("input");1470    searchInput.className = "search";1471    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1472    searchInput.value = query;1473    searchInput.addEventListener("input", () => {1474      query = searchInput?.value ?? "";1475      renderList();1476      searchInput?.focus();1477      searchInput?.setSelectionRange(query.length, query.length);1478    });1479    sw.appendChild(searchInput);1480    container.appendChild(sw);14811482    // Results1483    const results = document.createElement("div");1484    results.className = "results";1485    container.appendChild(results);14861487    if (current.length === 0 && entries.length > 0) {1488      // Show a hint but don't render empty entries1489    }14901491    for (let i = 0; i < current.length; i++) {1492      const e = current[i]!;1493      const entryEl = document.createElement("div");1494      entryEl.className = "entry";1495      entryEl.dataset.id = e.id;1496      entryEl.dataset.index = String(i);1497      entryEl.setAttribute("tabindex", "-1");14981499      entryEl.appendChild(makeEntryIcon(e.url));15001501      const info = document.createElement("div"); info.className = "entry-info";1502      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1503      const subEl = document.createElement("div"); subEl.className = "entry-sub";1504      const domain = e.url ? getDomainFromUrl(e.url) : "";1505      subEl.textContent = domain || e.username || "";1506      info.append(titleEl, subEl);1507      entryEl.appendChild(info);15081509      if (e.hasTotp) {1510        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1511        entryEl.appendChild(badge);1512      }1513      if (e.hasPasskey) {1514        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1515        entryEl.appendChild(badge);1516      }15171518      entryEl.addEventListener("click", () => {1519        if (options.isSignup && options.onFillFields) {1520          // Signup mode: clicking a saved identity fills the username field1521          options.onFillFields(e.username ?? "", "");1522          dismiss();1523        } else {1524          onSelect(e.id);1525          dismiss();1526        }1527      });1528      results.appendChild(entryEl);1529    }15301531    // Divider before "New entry"1532    if (current.length > 0) {1533      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1534    }15351536    // "New entry" row — always present1537    const newEl = document.createElement("div");1538    newEl.className = "entry";1539    newEl.setAttribute("tabindex", "-1");1540    newEl.appendChild(makeEntryIcon(undefined, true));15411542    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1543    const newTitle = document.createElement("div");1544    newTitle.className = "entry-title is-new";1545    newTitle.textContent = `New entry for ${sTitle}`;1546    const newSub = document.createElement("div");1547    newSub.className = "entry-sub";1548    newSub.textContent = sOrigin;1549    newInfo.append(newTitle, newSub);1550    newEl.appendChild(newInfo);1551    newEl.addEventListener("click", showCreateForm);1552    results.appendChild(newEl);15531554    // Focus search if present1555    if (searchInput) {1556      requestAnimationFrame(() => searchInput?.focus());1557    }1558  }15591560  function setFocused(idx: number) {1561    const all = container.querySelectorAll<HTMLElement>(".entry");1562    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1563    focusedIndex = idx;1564    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1565  }15661567  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[]): void {1568    if (!identities.length) return;1569    const list = g.appendChild(document.createElement("div"));1570    list.className = "identity-suggest-list";1571    list.style.display = "none";1572    function render() {1573      const q = inp.value.toLowerCase();1574      const filtered = identities.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 6);1575      list.innerHTML = "";1576      if (!filtered.length) { list.style.display = "none"; return; }1577      for (const s of filtered) {1578        const row = list.appendChild(document.createElement("button"));1579        row.type = "button"; row.className = "identity-suggest-row";1580        const val = row.appendChild(document.createElement("span"));1581        val.className = "identity-suggest-val"; val.textContent = s.value;1582        const meta = row.appendChild(document.createElement("span"));1583        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1584        row.addEventListener("mousedown", (e) => {1585          e.preventDefault();1586          inp.value = s.value;1587          list.style.display = "none";1588        });1589      }1590      list.style.display = "";1591    }1592    inp.addEventListener("focus", render);1593    inp.addEventListener("input", render);1594    inp.addEventListener("blur", () => setTimeout(() => { list.style.display = "none"; }, 150));1595  }15961597  async function showCreateForm() {1598    currentMode = "create";1599    container.innerHTML = "";16001601    // Guard: the service worker may lock the vault between when the selector1602    // opens and when the user clicks "New entry". Show the inline unlock form1603    // instead of silently failing on save.1604    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1605    if (!statusRes?.unlocked) {1606      renderLocked();1607      return;1608    }16091610    // Detect page password policy once for this form — reused on every1611    // regenerate click so the user always gets a compliant password.1612    const sitePolicy = detectPasswordPolicy();16131614    const wrap = document.createElement("div");1615    wrap.className = "create-form-wrap";16161617    // Header1618    const head = document.createElement("div"); head.className = "create-head";1619    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1620    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>`;1621    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1622    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1623    head.append(backBtn, lbl);16241625    // Body1626    const body = document.createElement("div"); body.className = "create-body";16271628    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1629      const g = document.createElement("div"); g.className = "f-group";1630      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1631      const inp = document.createElement("input"); inp.className = "f-input";1632      g.append(l, inp); return { g, inp };1633    }16341635    // Title1636    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1637    body.appendChild(tg.g);16381639    // URL1640    const ug = fGroup("website");1641    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1642    if (loginSubdomain) {1643      const h = document.createElement("div"); h.className = "url-hint";1644      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1645    }1646    body.appendChild(ug.g);16471648    // Username — pre-fill from anchor if it doesn't look like an email1649    const xg = fGroup("username");1650    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1651    xg.inp.placeholder = "johndoe";1652    xg.inp.setAttribute("autocomplete", "off");1653    if (options.savedIdentities?.length) attachIdentitySuggestions(xg.g, xg.inp, options.savedIdentities);1654    body.appendChild(xg.g);16551656    // Email — pre-fill from anchor if it looks like an email1657    const eg = fGroup("email");1658    (eg.inp as HTMLInputElement).type = "email";1659    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1660    eg.inp.placeholder = "[email protected]";1661    eg.inp.setAttribute("autocomplete", "off");1662    if (options.savedIdentities?.length) attachIdentitySuggestions(eg.g, eg.inp, options.savedIdentities);1663    body.appendChild(eg.g);16641665    // Password — full smart generator with charset pills + length slider +1666    // policy hint. Mirrors the main UI's compact generator so users get the1667    // same controls inline as in the popup.1668    const pg = fGroup("password");1669    let currentPassword = prePassword || "";1670    const smartGen = createSmartGenerator({1671      policy: sitePolicy,1672      initialPassword: prePassword || undefined,1673      onChange: (pw) => { currentPassword = pw; },1674    });1675    pg.g.appendChild(smartGen.root);1676    body.appendChild(pg.g);16771678    // Save1679    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1680    saveBtn.textContent = "Save entry";1681    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1682    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1683    saveBtn.addEventListener("click", async () => {1684      const title = tg.inp.value.trim();1685      const pw = currentPassword.trim();1686      const username = xg.inp.value.trim();1687      const email = eg.inp.value.trim();1688      if (!title) {1689        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1690        showFormError("Entry needs a title");1691        return;1692      }1693      if (!pw) {1694        showFormError("Entry needs a password — tap regen to make one");1695        return;1696      }1697      errEl.style.display = "none";1698      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1699      try {1700        const res = await chrome.runtime.sendMessage({1701          type: "ADD_ENTRY",1702          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1703        });1704        if ((res as { ok?: boolean }).ok) {1705          // Fill the detected form. onFillFields uses whichever identity the1706          // page anchored on — the vault captures both username and email.1707          options.onFillFields?.(username || email, pw);1708          showSuccess(title);1709        } else {1710          const errMsg = (res as { error?: string }).error === "vault locked"1711            ? "Vault locked — open Peach to save"1712            : "Could not save entry";1713          showFormError(errMsg);1714          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1715        }1716      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1717    });1718    body.appendChild(saveBtn);1719    body.appendChild(errEl);17201721    wrap.append(head, body);1722    container.appendChild(wrap);1723    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1724  }17251726  function showSuccess(title: string) {1727    currentMode = "success";1728    container.innerHTML = "";1729    const wrap = document.createElement("div"); wrap.className = "success-wrap";1730    const ring = document.createElement("div"); ring.className = "success-ring";1731    ring.innerHTML = checkSvgStr();1732    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1733    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1734    wrap.append(ring, t, s);1735    container.appendChild(wrap);1736    setTimeout(() => dismiss(), 1600);1737  }17381739  function flashActionBtn(btn: HTMLButtonElement) {1740    btn.classList.add("flashed");1741    setTimeout(() => btn.classList.remove("flashed"), 700);1742  }17431744  function renderSilverPlatter(entry: SelectorEntry) {1745    container.innerHTML = "";1746    searchInput = null;1747    focusedIndex = -1;1748    currentMode = "silver-platter";17491750    const domHdr = document.createElement("div");1751    domHdr.className = "domain-header";1752    const headText = document.createElement("div");1753    headText.className = "domain-header-text";1754    const eyebrow = document.createElement("div");1755    eyebrow.className = "domain-eyebrow";1756    eyebrow.textContent = "Saved for this site";1757    const domName = document.createElement("div");1758    domName.className = "domain-name";1759    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1760    headText.append(eyebrow, domName);1761    domHdr.appendChild(headText);1762    if (!options.isSignup) {1763      const addBtn = document.createElement("button");1764      addBtn.className = "domain-add-btn";1765      addBtn.type = "button";1766      addBtn.setAttribute("aria-label", "Create new entry");1767      addBtn.title = "Create new entry";1768      addBtn.textContent = "+";1769      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1770      domHdr.appendChild(addBtn);1771    }1772    container.appendChild(domHdr);17731774    const platter = document.createElement("div");1775    platter.className = "silver-platter";17761777    const titleEl = document.createElement("div");1778    titleEl.className = "sp-title";1779    titleEl.textContent = entry.title;1780    platter.appendChild(titleEl);17811782    if (entry.email) {1783      const emailEl = document.createElement("div");1784      emailEl.className = "sp-identity-row";1785      const emailLbl = document.createElement("span");1786      emailLbl.className = "sp-identity-label";1787      emailLbl.textContent = "email";1788      const emailVal = document.createElement("span");1789      emailVal.className = "sp-username";1790      emailVal.textContent = entry.email;1791      emailEl.append(emailLbl, emailVal);1792      platter.appendChild(emailEl);1793    }17941795    if (entry.username) {1796      const userEl = document.createElement("div");1797      userEl.className = "sp-identity-row";1798      const userLbl = document.createElement("span");1799      userLbl.className = "sp-identity-label";1800      userLbl.textContent = entry.username.includes("@") ? "email" : "username";1801      const userVal = document.createElement("span");1802      userVal.className = "sp-username";1803      userVal.textContent = entry.username;1804      userEl.append(userLbl, userVal);1805      platter.appendChild(userEl);1806    }18071808    const fillBtn = document.createElement("button");1809    fillBtn.className = "sp-fill-btn";1810    fillBtn.type = "button";1811    fillBtn.textContent = "Fill credentials";1812    fillBtn.addEventListener("click", () => {1813      if (fillBtn.disabled) return;1814      fillBtn.disabled = true;1815      fillBtn.classList.add("filled");1816      fillBtn.innerHTML = checkSvgStr();1817      // Fire the fill, then exit via the standard exit animation. The fill1818      // itself is async (handled in index.ts) — by 400ms the form is filled1819      // and the popup begins its exit. Total dwell from click to host1820      // removal: 400ms + 130ms (exit animation) = 530ms.1821      onSelect(entry.id);1822      setTimeout(() => dismiss(), 400);1823    });1824    platter.appendChild(fillBtn);18251826    const actions = document.createElement("div");1827    actions.className = "sp-actions";18281829    if (entry.email) {1830      const copyEmail = document.createElement("button");1831      copyEmail.className = "sp-action-btn";1832      copyEmail.type = "button";1833      copyEmail.title = "Copy email";1834      copyEmail.textContent = "Copy email";1835      copyEmail.addEventListener("click", async (e) => {1836        e.stopPropagation();1837        let alreadyWritten = false;1838        try { await navigator.clipboard.writeText(entry.email!); alreadyWritten = true; } catch {}1839        await chrome.runtime.sendMessage({1840          type: "COPY",1841          payload: { text: entry.email, label: "Email", alreadyWritten },1842        }).catch(() => {});1843        flashActionBtn(copyEmail);1844      });1845      actions.appendChild(copyEmail);1846    }18471848    const copyU = document.createElement("button");1849    copyU.className = "sp-action-btn";1850    copyU.type = "button";1851    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";1852    copyU.title = copyULabel;1853    copyU.textContent = copyULabel;1854    copyU.disabled = !entry.username;1855    copyU.addEventListener("click", async (e) => {1856      e.stopPropagation();1857      if (!entry.username) return;1858      let alreadyWritten = false;1859      try { await navigator.clipboard.writeText(entry.username); alreadyWritten = true; } catch {}1860      await chrome.runtime.sendMessage({1861        type: "COPY",1862        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },1863      }).catch(() => {});1864      flashActionBtn(copyU);1865    });1866    actions.appendChild(copyU);18671868    const copyP = document.createElement("button");1869    copyP.className = "sp-action-btn";1870    copyP.type = "button";1871    copyP.title = "Copy password";1872    copyP.textContent = "Copy password";1873    copyP.addEventListener("click", async (e) => {1874      e.stopPropagation();1875      const resp = await chrome.runtime.sendMessage({1876        type: "GET_ENTRY_FOR_FILL",1877        payload: { id: entry.id },1878      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;1879      if (!resp?.ok || !resp.data?.password) return;1880      let alreadyWritten = false;1881      try { await navigator.clipboard.writeText(resp.data.password); alreadyWritten = true; } catch {}1882      await chrome.runtime.sendMessage({1883        type: "COPY",1884        payload: { text: resp.data.password, label: "Password", alreadyWritten },1885      }).catch(() => {});1886      flashActionBtn(copyP);1887    });1888    actions.appendChild(copyP);18891890    let trayEl: HTMLDivElement | null = null;1891    let trayInterval: ReturnType<typeof setInterval> | null = null;18921893    function closeTray() {1894      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }1895      trayEl?.remove();1896      trayEl = null;1897    }1898    // Register so dismiss() will close the tray and clear the interval1899    // even if the user dismisses without explicitly closing the tray.1900    cleanupHooks.push(closeTray);19011902    async function openTOTPTray() {1903      // Fetch the entry to get the TOTP secret. The selector summary doesn't1904      // carry it (and shouldn't — passing secrets only at fill/copy time keeps1905      // the message-passing surface minimal per Projects.md §5.2).1906      const resp = await chrome.runtime.sendMessage({1907        type: "GET_ENTRY_FOR_FILL",1908        payload: { id: entry.id },1909      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;1910      const secret = resp?.ok ? resp.data?.totp : undefined;1911      if (!secret) return;19121913      trayEl = document.createElement("div");1914      trayEl.className = "sp-tray";19151916      const label = document.createElement("span");1917      label.className = "sp-tray-label";1918      label.textContent = "2FA";1919      trayEl.appendChild(label);19201921      const codeEl = document.createElement("div");1922      codeEl.className = "sp-totp-code";1923      trayEl.appendChild(codeEl);19241925      const ringNs = "http://www.w3.org/2000/svg";1926      const ring = document.createElementNS(ringNs, "svg");1927      ring.setAttribute("class", "sp-totp-ring");1928      ring.setAttribute("viewBox", "0 0 24 24");1929      const trackC = document.createElementNS(ringNs, "circle");1930      trackC.setAttribute("class", "ring-track");1931      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");1932      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");1933      const fillC = document.createElementNS(ringNs, "circle");1934      fillC.setAttribute("class", "ring-fill");1935      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");1936      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");1937      fillC.setAttribute("stroke-linecap", "round");1938      fillC.setAttribute("stroke-dasharray", "62.83");1939      ring.append(trackC, fillC);1940      trayEl.appendChild(ring);19411942      const copyBtn = document.createElement("button");1943      copyBtn.className = "sp-totp-copy";1944      copyBtn.type = "button";1945      copyBtn.textContent = "Copy";1946      trayEl.appendChild(copyBtn);19471948      function refresh() {1949        const { code, remaining } = generateTOTP(secret!);1950        // Group as "847 291" — easier to read than "847291"1951        codeEl.textContent = code.length === 61952          ? `${code.slice(0, 3)} ${code.slice(3)}`1953          : code;1954        // Ring fills counter-clockwise as time elapses: dashoffset goes from1955        // 0 (full ring) to 62.83 (empty) over the 30s window.1956        const fraction = (30 - remaining) / 30;1957        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));1958      }1959      refresh();1960      trayInterval = setInterval(refresh, 1000);19611962      copyBtn.addEventListener("click", async (e) => {1963        e.stopPropagation();1964        const { code } = generateTOTP(secret!);1965        let alreadyWritten = false;1966        try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}1967        await chrome.runtime.sendMessage({1968          type: "COPY",1969          payload: { text: code, label: "TOTP", alreadyWritten },1970        }).catch(() => {});1971        copyBtn.textContent = "Copied";1972        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);1973      });19741975      platter.appendChild(trayEl);1976    }19771978    const editBtn = document.createElement("button");1979    editBtn.className = "sp-action-btn sp-action-edit";1980    editBtn.type = "button";1981    editBtn.title = "Edit entry";1982    editBtn.textContent = "Edit";1983    editBtn.addEventListener("click", (e) => {1984      e.stopPropagation();1985      closeTray();1986      void renderInlineEdit(entry);1987    });1988    actions.appendChild(editBtn);19891990    // Always show the 2FA tray when the entry has TOTP — hiding it behind a1991    // "···" toggle was zero-savings (the toggle button took the same space1992    // the "2FA" label needed) and made the code one extra click away.1993    if (entry.hasTotp) void openTOTPTray();19941995    platter.appendChild(actions);1996    container.appendChild(platter);1997  }19981999  /**2000   * Inline-popup edit mode. Swaps the silver platter for an editable form2001   * over the same shadow-DOM surface so the user never leaves the page.2002   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2003   * with the new fields. Cancel returns without writing.2004   */2005  async function renderInlineEdit(summary: SelectorEntry) {2006    container.innerHTML = "";2007    const wrap = document.createElement("div");2008    wrap.className = "create-form-wrap";20092010    const head = document.createElement("div");2011    head.className = "create-head";2012    const back = document.createElement("button");2013    back.className = "back-btn";2014    back.type = "button";2015    back.title = "Cancel";2016    back.innerHTML = `<svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"><path d="M7 2L3 5.5L7 9"/></svg>`;2017    back.addEventListener("click", () => renderSilverPlatter(summary));2018    head.appendChild(back);2019    const headLbl = document.createElement("div");2020    headLbl.className = "create-label";2021    headLbl.textContent = "Edit entry";2022    head.appendChild(headLbl);2023    wrap.appendChild(head);20242025    const body = document.createElement("div");2026    body.className = "create-body";20272028    // Loading shimmer while we fetch the full entry2029    const loading = document.createElement("div");2030    loading.className = "empty-hint";2031    loading.textContent = "loading…";2032    body.appendChild(loading);2033    wrap.appendChild(body);2034    container.appendChild(wrap);20352036    const res = (await chrome.runtime.sendMessage({2037      type: "GET_ENTRY_FOR_FILL",2038      payload: { id: summary.id },2039    }).catch(() => null)) as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;20402041    if (!res || !res.ok || !res.data) {2042      loading.textContent = "couldn't load this entry. try again from the popup.";2043      return;2044    }2045    body.innerHTML = "";20462047    function field(label: string, value: string, type: "text" | "password" = "text"): HTMLInputElement {2048      const group = document.createElement("div");2049      group.className = "f-group";2050      const lbl = document.createElement("div");2051      lbl.className = "f-label";2052      lbl.textContent = label;2053      const input = document.createElement("input");2054      input.className = "f-input";2055      input.type = type;2056      input.value = value;2057      input.autocomplete = "off";2058      group.append(lbl, input);2059      body.appendChild(group);2060      return input;2061    }20622063    const titleInput = field("title", res.data.title ?? "");2064    const urlInput = field("url", res.data.url ?? "");2065    urlInput.classList.add("url-f");2066    const usernameLabel = (res.data.username ?? "").includes("@") ? "email" : "username";2067    const usernameInput = field(usernameLabel, res.data.username ?? "");2068    const emailInput = field("email", res.data.email ?? "");20692070    // Password row with reveal toggle2071    const pwGroup = document.createElement("div");2072    pwGroup.className = "f-group";2073    const pwLbl = document.createElement("div");2074    pwLbl.className = "f-label";2075    pwLbl.textContent = "password";2076    const pwRow = document.createElement("div");2077    pwRow.className = "f-row";2078    const pwInput = document.createElement("input");2079    pwInput.className = "f-input";2080    pwInput.type = "password";2081    pwInput.value = res.data.password ?? "";2082    pwInput.autocomplete = "new-password";2083    const revealBtn = document.createElement("button");2084    revealBtn.className = "gen-btn";2085    revealBtn.type = "button";2086    revealBtn.textContent = "show";2087    revealBtn.addEventListener("click", () => {2088      const reveal = pwInput.type === "password";2089      pwInput.type = reveal ? "text" : "password";2090      revealBtn.textContent = reveal ? "hide" : "show";2091    });2092    pwRow.append(pwInput, revealBtn);2093    pwGroup.append(pwLbl, pwRow);2094    body.appendChild(pwGroup);20952096    const totpInput = field("2fa secret", res.data.totp ?? "");20972098    // Notes2099    const notesGroup = document.createElement("div");2100    notesGroup.className = "f-group";2101    const notesLbl = document.createElement("div");2102    notesLbl.className = "f-label";2103    notesLbl.textContent = "notes";2104    const notesInput = document.createElement("textarea");2105    notesInput.className = "f-input";2106    notesInput.rows = 3;2107    notesInput.value = res.data.notes ?? "";2108    notesInput.style.fontFamily = "Inter, sans-serif";2109    notesInput.style.resize = "vertical";2110    notesGroup.append(notesLbl, notesInput);2111    body.appendChild(notesGroup);21122113    // Save / Cancel row2114    const actionsRow = document.createElement("div");2115    actionsRow.className = "f-row";2116    const saveBtn = document.createElement("button");2117    saveBtn.className = "save-btn";2118    saveBtn.type = "button";2119    saveBtn.textContent = "Save changes";2120    saveBtn.style.flex = "1";2121    const cancelBtn = document.createElement("button");2122    cancelBtn.className = "gen-btn";2123    cancelBtn.type = "button";2124    cancelBtn.textContent = "cancel";2125    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2126    actionsRow.append(saveBtn, cancelBtn);2127    body.appendChild(actionsRow);21282129    saveBtn.addEventListener("click", async () => {2130      saveBtn.disabled = true;2131      const originalLabel = saveBtn.textContent;2132      saveBtn.textContent = "Saving…";2133      const patch: Record<string, unknown> = {2134        title: titleInput.value.trim(),2135        url: urlInput.value.trim(),2136        username: usernameInput.value.trim(),2137        email: emailInput.value.trim() || undefined,2138        password: pwInput.value,2139        totp: totpInput.value.trim(),2140        notes: notesInput.value,2141      };2142      const updateRes = (await chrome.runtime.sendMessage({2143        type: "UPDATE_ENTRY",2144        payload: { id: summary.id, patch },2145      }).catch(() => null)) as { ok: boolean; error?: string } | null;2146      if (!updateRes?.ok) {2147        saveBtn.disabled = false;2148        saveBtn.textContent = originalLabel;2149        const err = document.createElement("div");2150        err.className = "empty-hint";2151        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2152        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2153        body.appendChild(err);2154        setTimeout(() => err.remove(), 3000);2155        return;2156      }2157      // Refresh the platter with updated summary fields2158      const refreshed: SelectorEntry = {2159        id: summary.id,2160        title: patch.title as string,2161        username: patch.username as string,2162        email: patch.email as string | undefined,2163        url: patch.url as string,2164        hasTotp: Boolean(patch.totp),2165        hasPasskey: summary.hasPasskey,2166      };2167      renderSilverPlatter(refreshed);2168    });21692170    queueMicrotask(() => titleInput.focus());2171  }21722173  function renderLocked() {2174    container.innerHTML = "";21752176    // Domain header (same as list view)2177    const domHdr = document.createElement("div");2178    domHdr.className = "domain-header";2179    const eyebrow = document.createElement("div");2180    eyebrow.className = "domain-eyebrow";2181    eyebrow.textContent = "vault locked";2182    const domName = document.createElement("div");2183    domName.className = "domain-name";2184    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2185    domHdr.append(eyebrow, domName);2186    container.appendChild(domHdr);21872188    const wrap = document.createElement("div");2189    wrap.className = "locked-wrap";21902191    // Icon + label row2192    const head = document.createElement("div"); head.className = "locked-head";2193    const icon = document.createElement("div"); icon.className = "locked-icon";2194    icon.innerHTML = keySvgStr();2195    const title = document.createElement("div"); title.className = "locked-title";2196    title.textContent = "unlock to autofill";2197    head.append(icon, title);21982199    // Password input2200    const pwInp = document.createElement("input");2201    pwInp.className = "locked-input";2202    pwInp.type = "password";2203    pwInp.placeholder = "master password";2204    pwInp.setAttribute("autocomplete", "current-password");22052206    // Error line (hidden initially)2207    const errEl = document.createElement("div");2208    errEl.className = "locked-error";2209    errEl.style.display = "none";22102211    // Unlock button2212    const unlockBtn = document.createElement("button");2213    unlockBtn.className = "locked-btn";2214    unlockBtn.type = "button";2215    unlockBtn.textContent = "unlock";22162217    async function tryUnlock() {2218      const pw = pwInp.value.trim();2219      if (!pw) { pwInp.focus(); return; }2220      unlockBtn.disabled = true;2221      unlockBtn.textContent = "unlocking…";2222      errEl.style.display = "none";2223      try {2224        const res = await chrome.runtime.sendMessage({2225          type: "UNLOCK",2226          payload: { password: pw },2227        });2228        if ((res as { ok?: boolean }).ok) {2229          dismiss();2230          options.onUnlocked?.();2231        } else {2232          errEl.textContent = "incorrect password";2233          errEl.style.display = "block";2234          pwInp.value = "";2235          pwInp.focus();2236          unlockBtn.disabled = false;2237          unlockBtn.textContent = "unlock";2238        }2239      } catch {2240        errEl.textContent = "could not reach Peach";2241        errEl.style.display = "block";2242        unlockBtn.disabled = false;2243        unlockBtn.textContent = "unlock";2244      }2245    }22462247    pwInp.addEventListener("keydown", (e) => {2248      e.stopPropagation();2249      if (e.key === "Enter") void tryUnlock();2250    });2251    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2252    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2253    unlockBtn.addEventListener("click", () => void tryUnlock());22542255    wrap.append(head, pwInp, errEl, unlockBtn);2256    container.appendChild(wrap);22572258    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2259    // the page reclaims focus from our Shadow DOM input before the user can2260    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2261    // Instead: intercept keystrokes at the document capture phase — this runs2262    // before any page handler regardless of which element technically has2263    // OS focus — and route them into our input.2264    const captureKeydown = (e: KeyboardEvent) => {2265      if (!host.isConnected) {2266        document.removeEventListener("keydown", captureKeydown, true);2267        return;2268      }2269      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2270      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2271      // Intercept before page handlers and give our input focus.2272      e.stopImmediatePropagation();2273      if (e.key === "Escape") { dismiss(true); return; }2274      if (e.key === "Enter") { void tryUnlock(); return; }2275      // For all other printable/editing keys, ensure our input has focus so2276      // the browser delivers the keystroke there naturally.2277      if (document.activeElement !== host) {2278        pwInp.focus({ preventScroll: true });2279      }2280    };2281    captureKeydownRef = captureKeydown;2282    document.addEventListener("keydown", captureKeydown, true);22832284    // Best-effort focus on open — may be overridden by page focus trap,2285    // but the capture listener above handles typing regardless.2286    pwInp.focus({ preventScroll: true });2287    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2288  }22892290  function handleKeyDown(e: KeyboardEvent) {2291    if (options.locked) {2292      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2293      return;2294    }2295    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2296      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2297      return;2298    }2299    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2300    const count = allEntryEls.length;2301    if (document.activeElement === searchInput) {2302      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2303      if (count === 0) return;2304      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2305    }2306    if (count === 0) return;2307    switch (e.key) {2308      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2309      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2310      case "Enter": {2311        if (focusedIndex >= 0) {2312          const el = allEntryEls[focusedIndex] as HTMLElement;2313          const id = el.dataset.id;2314          if (id) { onSelect(id); dismiss(); }2315          else if (el.classList.contains("is-new") || !id) {2316            // "New entry" row (last item, no data-id)2317            showCreateForm();2318          }2319        }2320        break;2321      }2322      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2323    }2324  }23252326  document.addEventListener("keydown", handleKeyDown);23272328  document.body.appendChild(host);23292330  function updatePosition() {2331    const r = anchorEl.getBoundingClientRect();2332    host.style.top = `${r.bottom + window.scrollY + 5}px`;2333    host.style.left = `${r.left + window.scrollX}px`;2334  }2335  // These bindings are referenced from renderLocked()/dismiss() — they MUST2336  // be initialized before renderLocked() runs, or the synchronous assignment2337  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2338  // and throws ReferenceError. The throw lands after the popup is rendered2339  // but before showAutofillSelector returns its dismiss handle, leaving an2340  // orphan host in the DOM (which is what caused the locked-popup stacking2341  // and missing autofocus on every click).2342  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2343  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);23442345  if (options.locked) {2346    renderLocked();2347  } else if (options.isSignup && options.savedIdentities) {2348    // State 10: identity helper — signup form detected, show derived2349    // identity list (emails then usernames) instead of vault entry list.2350    renderIdentityHelper();2351  } else if (entries.length === 1 && !options.isSignup) {2352    // Silver platter (State 1): single domain match → focused fill view.2353    // Multi-match goes through renderList instead.2354    renderSilverPlatter(entries[0]!);2355  } else {2356    renderList();2357  }23582359  let exitScheduled = false;2360  function dismiss(userAction = false) {2361    // Idempotent: dismiss() can be called from multiple paths (Escape,2362    // outside click, entry select, fill success, host page nav). The exit2363    // animation must only play once and host.remove() must run exactly once.2364    if (exitScheduled) return;2365    exitScheduled = true;2366    // Detach listeners synchronously so nothing can re-trigger during the2367    // 130ms exit window (a focusin firing here would race against the2368    // dismiss-lock work in Pass 2).2369    stopObserving();2370    document.removeEventListener("click", outsideClick, { capture: true });2371    document.removeEventListener("keydown", handleKeyDown);2372    if (captureKeydownRef) {2373      document.removeEventListener("keydown", captureKeydownRef, true);2374      captureKeydownRef = null;2375    }2376    for (const cleanup of cleanupHooks) {2377      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2378    }2379    if (userAction) options.onDismiss?.();2380    container.classList.add("is-exiting");2381    setTimeout(() => host.remove(), 130);2382  }23832384  function outsideClick(ev: MouseEvent) {2385    const path = ev.composedPath();2386    // Never dismiss when clicking the anchor field itself — that click is2387    // what triggered the selector to open, and the user may click the field2388    // again to re-focus it without intending to close the selector.2389    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2390  }2391  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2392  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);23932394  return dismiss;2395}23962397export interface CardSelectorEntry {2398  id: string;2399  title: string;2400  cardholderName?: string;2401  last4?: string;2402  expMonth?: string;2403  expYear?: string;2404  network?: import("../shared/types").CardNetwork;2405}24062407interface CardSelectorOptions {2408  domain?: string;2409  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2410  onFill: (entry: import("../shared/types").VaultEntry) => void;2411  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2412  onDismiss?: () => void;2413}24142415/**2416 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2417 * passkey create or get. Renders as a fixed-position floating popup (no2418 * field anchor needed — passkeys don't require a focused input). Uses the2419 * same theme tokens and entrance animation as all other inline popup states.2420 */2421export function showPasskeyProGate(): void {2422  const domain = location.hostname.replace(/^www\./, "");24232424  const host = document.createElement("div");2425  host.setAttribute("data-peach-passkey-gate", "1");2426  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2427  const shadow = host.attachShadow({ mode: "closed" });24282429  const style = document.createElement("style");2430  style.textContent = `2431    :host { all: initial; }2432    .gate-wrap {2433      position: fixed;2434      top: 50%;2435      left: 50%;2436      transform: translate(-50%, -50%);2437      width: 280px;2438      pointer-events: auto;2439      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2440    }2441    @keyframes g-in {2442      from { opacity:0; transform: translate(-50%,-52%); }2443      to   { opacity:1; transform: translate(-50%,-50%); }2444    }2445    .gate-wrap.is-exiting {2446      animation: g-out 130ms ease-in forwards;2447    }2448    @keyframes g-out {2449      to { opacity:0; transform: translate(-50%,-52%); }2450    }2451    .gate {2452      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2453      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2454      border-radius: 12px;2455      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2456      padding: 16px;2457      font-family: Inter, sans-serif;2458    }2459    .gate-header {2460      display: flex;2461      align-items: center;2462      gap: 7px;2463      margin-bottom: 12px;2464      padding-bottom: 10px;2465      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2466    }2467    .gate-domain {2468      font-size: 12px;2469      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2470      font-family: "IBM Plex Mono", monospace;2471      overflow: hidden;2472      text-overflow: ellipsis;2473      white-space: nowrap;2474    }2475    .gate-title {2476      font-size: 14px;2477      font-weight: 500;2478      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2479      margin-bottom: 6px;2480    }2481    .gate-subtitle {2482      font-size: 12px;2483      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2484      line-height: 1.5;2485      margin-bottom: 14px;2486    }2487    .gate-btn {2488      display: block;2489      width: 100%;2490      padding: 9px 0;2491      border-radius: 8px;2492      border: none;2493      cursor: pointer;2494      font-size: 13px;2495      font-family: Inter, sans-serif;2496      font-weight: 500;2497      transition: opacity 100ms;2498      margin-bottom: 7px;2499      text-align: center;2500    }2501    .gate-btn:last-child { margin-bottom: 0; }2502    .gate-btn--accent {2503      background: ${accentHex};2504      color: #fff;2505    }2506    .gate-btn--accent:hover { opacity: 0.88; }2507    .gate-btn--ghost {2508      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2509      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2510    }2511    .gate-btn--ghost:hover { opacity: 0.75; }2512    .backdrop {2513      position: fixed;2514      inset: 0;2515      pointer-events: auto;2516    }2517  `;2518  shadow.appendChild(style);25192520  const backdrop = document.createElement("div");2521  backdrop.className = "backdrop";2522  shadow.appendChild(backdrop);25232524  const wrap = document.createElement("div");2525  wrap.className = "gate-wrap";2526  shadow.appendChild(wrap);25272528  const gate = document.createElement("div");2529  gate.className = "gate";2530  wrap.appendChild(gate);25312532  // Header: peach icon + domain2533  const header = document.createElement("div");2534  header.className = "gate-header";2535  const icon = document.createElement("span");2536  icon.innerHTML = peachIconSvg();2537  const domainEl = document.createElement("span");2538  domainEl.className = "gate-domain";2539  domainEl.textContent = domain;2540  header.append(icon, domainEl);2541  gate.appendChild(header);25422543  const title = document.createElement("div");2544  title.className = "gate-title";2545  title.textContent = "Passkeys are part of Peach Pro.";2546  gate.appendChild(title);25472548  const subtitle = document.createElement("div");2549  subtitle.className = "gate-subtitle";2550  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2551  gate.appendChild(subtitle);25522553  const upgradeBtn = document.createElement("button");2554  upgradeBtn.className = "gate-btn gate-btn--accent";2555  upgradeBtn.type = "button";2556  upgradeBtn.textContent = "Upgrade to Pro";2557  gate.appendChild(upgradeBtn);25582559  const laterBtn = document.createElement("button");2560  laterBtn.className = "gate-btn gate-btn--ghost";2561  laterBtn.type = "button";2562  laterBtn.textContent = "Not right now";2563  gate.appendChild(laterBtn);25642565  function dismiss() {2566    wrap.classList.add("is-exiting");2567    setTimeout(() => host.remove(), 130);2568  }25692570  upgradeBtn.addEventListener("click", () => {2571    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2572    dismiss();2573  });2574  laterBtn.addEventListener("click", dismiss);2575  backdrop.addEventListener("click", dismiss);25762577  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2578    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2579  });25802581  document.body.appendChild(host);2582}25832584/**2585 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2586 * detector sees the page invoke navigator.credentials.create(); content/index.ts2587 * checks vault + decline state then calls this. "Save passkey to Peach"2588 * initiates the popup-context credential flow; "Not now" records a 30-day2589 * decline for the domain so we don't re-show on every page reload.2590 */2591export function showPasskeyRegistrationOffer(args: {2592  rpId: string;2593  rpName?: string;2594  userName?: string;2595  userDisplayName?: string;2596}): void {2597  const domain = location.hostname.replace(/^www\./, "");2598  const displayName = args.rpName || domain;25992600  const host = document.createElement("div");2601  host.setAttribute("data-peach-passkey-offer", "1");2602  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2603  const shadow = host.attachShadow({ mode: "closed" });26042605  const style = document.createElement("style");2606  style.textContent = `2607    :host { all: initial; }2608    .offer-wrap {2609      position: fixed;2610      top: 16px;2611      right: 16px;2612      width: 320px;2613      pointer-events: auto;2614      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2615    }2616    @keyframes o-in {2617      from { opacity: 0; transform: translateY(-6px); }2618      to   { opacity: 1; transform: translateY(0); }2619    }2620    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2621    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2622    .offer {2623      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2624      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2625      border-radius: 12px;2626      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2627      padding: 14px 14px 12px;2628      font-family: Inter, sans-serif;2629      position: relative;2630    }2631    .offer-close {2632      position: absolute;2633      top: 8px;2634      right: 8px;2635      width: 18px;2636      height: 18px;2637      border: none;2638      background: transparent;2639      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2640      cursor: pointer;2641      font-size: 14px;2642      line-height: 1;2643      padding: 0;2644    }2645    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2646    .offer-header {2647      display: flex;2648      align-items: center;2649      gap: 7px;2650      margin-bottom: 8px;2651      padding-bottom: 8px;2652      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2653    }2654    .offer-domain {2655      font-size: 12px;2656      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2657      font-family: "IBM Plex Mono", monospace;2658      overflow: hidden;2659      text-overflow: ellipsis;2660      white-space: nowrap;2661    }2662    .offer-title {2663      font-size: 13px;2664      font-weight: 500;2665      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2666      margin-bottom: 4px;2667    }2668    .offer-subtitle {2669      font-size: 11px;2670      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2671      line-height: 1.45;2672      margin-bottom: 12px;2673    }2674    .offer-btn {2675      display: block;2676      width: 100%;2677      padding: 8px 0;2678      border-radius: 7px;2679      border: none;2680      cursor: pointer;2681      font-size: 12px;2682      font-family: Inter, sans-serif;2683      font-weight: 500;2684      transition: opacity 100ms;2685      margin-bottom: 6px;2686      text-align: center;2687    }2688    .offer-btn:last-child { margin-bottom: 0; }2689    .offer-btn--accent { background: ${accentHex}; color: #fff; }2690    .offer-btn--accent:hover { opacity: 0.88; }2691    .offer-btn--ghost {2692      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2693      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2694    }2695    .offer-btn--ghost:hover { opacity: 0.75; }2696  `;2697  shadow.appendChild(style);26982699  const wrap = document.createElement("div");2700  wrap.className = "offer-wrap";2701  shadow.appendChild(wrap);27022703  const offer = document.createElement("div");2704  offer.className = "offer";2705  wrap.appendChild(offer);27062707  const closeBtn = document.createElement("button");2708  closeBtn.className = "offer-close";2709  closeBtn.type = "button";2710  closeBtn.setAttribute("aria-label", "Dismiss");2711  closeBtn.textContent = "✕";2712  offer.appendChild(closeBtn);27132714  const header = document.createElement("div");2715  header.className = "offer-header";2716  const icon = document.createElement("span");2717  icon.innerHTML = peachIconSvg();2718  const domainEl = document.createElement("span");2719  domainEl.className = "offer-domain";2720  domainEl.textContent = domain;2721  header.append(icon, domainEl);2722  offer.appendChild(header);27232724  const title = document.createElement("div");2725  title.className = "offer-title";2726  title.textContent = "This site supports passkeys.";2727  offer.appendChild(title);27282729  const subtitle = document.createElement("div");2730  subtitle.className = "offer-subtitle";2731  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2732  offer.appendChild(subtitle);27332734  const saveBtn = document.createElement("button");2735  saveBtn.className = "offer-btn offer-btn--accent";2736  saveBtn.type = "button";2737  saveBtn.textContent = "Save passkey to Peach";2738  offer.appendChild(saveBtn);27392740  const laterBtn = document.createElement("button");2741  laterBtn.className = "offer-btn offer-btn--ghost";2742  laterBtn.type = "button";2743  laterBtn.textContent = "Not now";2744  offer.appendChild(laterBtn);27452746  function dismiss(decline: boolean) {2747    if (decline) {2748      chrome.runtime.sendMessage({2749        type: "PASSKEY_OFFER_DECLINE",2750        payload: { domain },2751      }).catch(() => {});2752    }2753    wrap.classList.add("is-exiting");2754    setTimeout(() => host.remove(), 130);2755  }27562757  saveBtn.addEventListener("click", () => {2758    chrome.runtime.sendMessage({2759      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2760      payload: {2761        rpId: args.rpId,2762        rpName: args.rpName ?? displayName,2763        userName: args.userName ?? "user",2764        userDisplayName: args.userDisplayName,2765      },2766    }).catch(() => {});2767    dismiss(false);2768  });2769  laterBtn.addEventListener("click", () => dismiss(true));2770  closeBtn.addEventListener("click", () => dismiss(true));27712772  document.body.appendChild(host);2773}27742775/**2776 * State 11 — passkey available indicator. Shown when the user lands on a2777 * domain for which they already have a stored passkey. Tells them where to2778 * find it (the entry already shows in the vault list); the "Sign in with2779 * passkey" button opens the popup so they can use the platform authenticator2780 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2781 * the actual sign-in transparently, so this banner is informational only.2782 */2783export function showPasskeyAvailable(args: {2784  rpId: string;2785  userName: string;2786  fromBrowser?: "chrome" | "firefox";2787  currentBrowser?: "chrome" | "firefox" | "unknown";2788}): void {2789  const domain = location.hostname.replace(/^www\./, "");2790  const crossBrowser =2791    args.fromBrowser &&2792    args.currentBrowser &&2793    args.currentBrowser !== "unknown" &&2794    args.fromBrowser !== args.currentBrowser;27952796  const host = document.createElement("div");2797  host.setAttribute("data-peach-passkey-available", "1");2798  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2799  const shadow = host.attachShadow({ mode: "closed" });28002801  const style = document.createElement("style");2802  style.textContent = `2803    :host { all: initial; }2804    .avail-wrap {2805      position: fixed;2806      top: 16px;2807      right: 16px;2808      width: 320px;2809      pointer-events: auto;2810      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;2811    }2812    @keyframes a-in {2813      from { opacity: 0; transform: translateY(-6px); }2814      to   { opacity: 1; transform: translateY(0); }2815    }2816    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }2817    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }2818    .avail {2819      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2820      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2821      border-radius: 12px;2822      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2823      padding: 14px 14px 12px;2824      font-family: Inter, sans-serif;2825      position: relative;2826    }2827    .avail-close {2828      position: absolute;2829      top: 8px;2830      right: 8px;2831      width: 18px;2832      height: 18px;2833      border: none;2834      background: transparent;2835      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2836      cursor: pointer;2837      font-size: 14px;2838      line-height: 1;2839      padding: 0;2840    }2841    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2842    .avail-header {2843      display: flex;2844      align-items: center;2845      gap: 7px;2846      margin-bottom: 8px;2847      padding-bottom: 8px;2848      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2849    }2850    .avail-domain {2851      font-size: 12px;2852      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2853      font-family: "IBM Plex Mono", monospace;2854    }2855    .avail-label {2856      font-size: 9px;2857      letter-spacing: 0.16em;2858      text-transform: uppercase;2859      color: ${accentHex};2860      margin-bottom: 4px;2861    }2862    .avail-user {2863      font-size: 13px;2864      font-weight: 500;2865      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2866      margin-bottom: 12px;2867      overflow: hidden;2868      text-overflow: ellipsis;2869      white-space: nowrap;2870    }2871    .avail-cross {2872      font-size: 11px;2873      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2874      line-height: 1.45;2875      margin-bottom: 12px;2876      padding: 8px;2877      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};2878      border-radius: 6px;2879    }2880    .avail-btn {2881      display: block;2882      width: 100%;2883      padding: 8px 0;2884      border-radius: 7px;2885      border: none;2886      cursor: pointer;2887      font-size: 12px;2888      font-family: Inter, sans-serif;2889      font-weight: 500;2890      transition: opacity 100ms;2891      margin-bottom: 6px;2892      text-align: center;2893    }2894    .avail-btn:last-child { margin-bottom: 0; }2895    .avail-btn--accent { background: ${accentHex}; color: #fff; }2896    .avail-btn--accent:hover { opacity: 0.88; }2897    .avail-btn--ghost {2898      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2899      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2900    }2901    .avail-btn--ghost:hover { opacity: 0.75; }2902  `;2903  shadow.appendChild(style);29042905  const wrap = document.createElement("div");2906  wrap.className = "avail-wrap";2907  shadow.appendChild(wrap);29082909  const avail = document.createElement("div");2910  avail.className = "avail";2911  wrap.appendChild(avail);29122913  const closeBtn = document.createElement("button");2914  closeBtn.className = "avail-close";2915  closeBtn.type = "button";2916  closeBtn.setAttribute("aria-label", "Dismiss");2917  closeBtn.textContent = "✕";2918  avail.appendChild(closeBtn);29192920  const header = document.createElement("div");2921  header.className = "avail-header";2922  const icon = document.createElement("span");2923  icon.innerHTML = peachIconSvg();2924  const domainEl = document.createElement("span");2925  domainEl.className = "avail-domain";2926  domainEl.textContent = domain;2927  header.append(icon, domainEl);2928  avail.appendChild(header);29292930  const label = document.createElement("div");2931  label.className = "avail-label";2932  label.textContent = "PASSKEY";2933  avail.appendChild(label);29342935  const user = document.createElement("div");2936  user.className = "avail-user";2937  user.textContent = args.userName;2938  avail.appendChild(user);29392940  if (crossBrowser) {2941    const cross = document.createElement("div");2942    cross.className = "avail-cross";2943    cross.textContent =2944      args.fromBrowser === "chrome"2945        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."2946        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";2947    avail.appendChild(cross);2948  }29492950  const signInBtn = document.createElement("button");2951  signInBtn.className = "avail-btn avail-btn--accent";2952  signInBtn.type = "button";2953  signInBtn.textContent = "Sign in with passkey";2954  avail.appendChild(signInBtn);29552956  const passwordBtn = document.createElement("button");2957  passwordBtn.className = "avail-btn avail-btn--ghost";2958  passwordBtn.type = "button";2959  passwordBtn.textContent = "Use password instead";2960  avail.appendChild(passwordBtn);29612962  function dismiss() {2963    wrap.classList.add("is-exiting");2964    setTimeout(() => host.remove(), 130);2965  }29662967  signInBtn.addEventListener("click", () => {2968    // On Chrome: the user clicking the page's own Sign-in button is what2969    //   triggers webAuthenticationProxy → existing background flow handles it.2970    //   Our button just dismisses since the page itself drives auth.2971    // On Firefox: cross-browser passkeys can't be used, so we just dismiss2972    //   and surface the entry for manual reference (popup view).2973    dismiss();2974    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});2975  });2976  passwordBtn.addEventListener("click", dismiss);2977  closeBtn.addEventListener("click", dismiss);29782979  document.body.appendChild(host);2980}29812982/**2983 * State 7 — card silver platter. Single-card focused fill view rendered2984 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the2985 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes2986 * so card and login flows render identically. Multi-card list view is a2987 * follow-up; today this picks the first card.2988 */2989export function showCardSelector(2990  anchorEl: HTMLInputElement,2991  cards: CardSelectorEntry[],2992  options: CardSelectorOptions2993): () => void {2994  if (cards.length === 0) return () => {};2995  const card = cards[0]!;29962997  const host = document.createElement("div");2998  host.style.cssText = "position: absolute; z-index: 2147483647;";2999  host.style.setProperty("--peach-accent", accentHex);3000  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3001  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3002  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3003  const shadow = host.attachShadow({ mode: "closed" });30043005  const style = shadow.appendChild(document.createElement("style"));3006  style.textContent = SELECTOR_STYLES;30073008  const rect = anchorEl.getBoundingClientRect();3009  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3010  host.style.left = `${rect.left + window.scrollX}px`;3011  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;30123013  const container = shadow.appendChild(document.createElement("div"));3014  container.className = "peach-inline-popup";3015  container.setAttribute("data-theme", popupTheme);30163017  // Domain header — eyebrow communicates the card context, not the site3018  const domHdr = document.createElement("div");3019  domHdr.className = "domain-header";3020  const eyebrow = document.createElement("div");3021  eyebrow.className = "domain-eyebrow";3022  eyebrow.textContent = "Pay with Peach";3023  const domName = document.createElement("div");3024  domName.className = "domain-name";3025  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3026  domHdr.append(eyebrow, domName);3027  container.appendChild(domHdr);30283029  const platter = document.createElement("div");3030  platter.className = "card-platter";30313032  if (card.network && card.network !== "unknown") {3033    const net = document.createElement("div");3034    net.className = "cp-network";3035    net.textContent = card.network;3036    platter.appendChild(net);3037  }30383039  const nick = document.createElement("div");3040  nick.className = "cp-nickname";3041  nick.textContent = card.title;3042  platter.appendChild(nick);30433044  if (card.last4) {3045    const l4 = document.createElement("div");3046    l4.className = "cp-last4";3047    l4.textContent = `•••• ${card.last4}`;3048    platter.appendChild(l4);3049  }30503051  const meta = document.createElement("div");3052  meta.className = "cp-meta";3053  if (card.cardholderName) {3054    const name = document.createElement("span");3055    name.textContent = card.cardholderName;3056    meta.appendChild(name);3057  }3058  if (card.expMonth && card.expYear) {3059    if (card.cardholderName) {3060      const sep = document.createElement("span");3061      sep.className = "cp-meta-sep";3062      sep.textContent = "·";3063      meta.appendChild(sep);3064    }3065    const exp = document.createElement("span");3066    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3067    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3068    meta.appendChild(exp);3069  }3070  if (meta.childElementCount > 0) platter.appendChild(meta);30713072  const fillWrap = document.createElement("div");3073  fillWrap.className = "cp-fill-wrap";3074  const fillBtn = document.createElement("button");3075  fillBtn.className = "sp-fill-btn";3076  fillBtn.type = "button";3077  fillBtn.textContent = "Fill card details";3078  fillBtn.addEventListener("click", async () => {3079    if (fillBtn.disabled) return;3080    fillBtn.disabled = true;3081    fillBtn.classList.add("filled");3082    fillBtn.innerHTML = checkSvgStr();3083    const resp = await chrome.runtime.sendMessage({3084      type: "GET_ENTRY_FOR_FILL",3085      payload: { id: card.id },3086    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3087    if (resp?.ok && resp.data) options.onFill(resp.data);3088    setTimeout(() => dismiss(), 400);3089  });3090  fillWrap.appendChild(fillBtn);3091  platter.appendChild(fillWrap);30923093  // Secondary actions — copy number, copy CVC, dismiss3094  const actions = document.createElement("div");3095  actions.className = "sp-actions";30963097  function flashBtn(b: HTMLButtonElement) {3098    b.classList.add("flashed");3099    setTimeout(() => b.classList.remove("flashed"), 700);3100  }31013102  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3103    const resp = await chrome.runtime.sendMessage({3104      type: "GET_ENTRY_FOR_FILL",3105      payload: { id: card.id },3106    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3107    return resp?.ok && resp.data ? resp.data : null;3108  }31093110  const copyNum = document.createElement("button");3111  copyNum.className = "sp-action-btn";3112  copyNum.type = "button";3113  copyNum.title = "Copy card number";3114  copyNum.textContent = "Copy number";3115  copyNum.addEventListener("click", async (e) => {3116    e.stopPropagation();3117    const full = await fetchFullCard();3118    if (!full?.cardNumber) return;3119    let alreadyWritten = false;3120    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}3121    await chrome.runtime.sendMessage({3122      type: "COPY",3123      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3124    }).catch(() => {});3125    flashBtn(copyNum);3126  });3127  actions.appendChild(copyNum);31283129  const copyCvc = document.createElement("button");3130  copyCvc.className = "sp-action-btn";3131  copyCvc.type = "button";3132  copyCvc.title = "Copy CVC";3133  copyCvc.textContent = "Copy CVC";3134  copyCvc.addEventListener("click", async (e) => {3135    e.stopPropagation();3136    const full = await fetchFullCard();3137    if (!full?.cvc) return;3138    let alreadyWritten = false;3139    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}3140    await chrome.runtime.sendMessage({3141      type: "COPY",3142      payload: { text: full.cvc, label: "CVC", alreadyWritten },3143    }).catch(() => {});3144    flashBtn(copyCvc);3145  });3146  actions.appendChild(copyCvc);31473148  const closeBtn = document.createElement("button");3149  closeBtn.className = "sp-action-btn";3150  closeBtn.type = "button";3151  closeBtn.title = "Dismiss";3152  closeBtn.textContent = "✕";3153  closeBtn.addEventListener("click", (e) => {3154    e.stopPropagation();3155    dismiss(true);3156  });3157  actions.appendChild(closeBtn);31583159  platter.appendChild(actions);3160  container.appendChild(platter);31613162  document.body.appendChild(host);3163  function updatePosition() {3164    const r = anchorEl.getBoundingClientRect();3165    host.style.top = `${r.bottom + window.scrollY + 5}px`;3166    host.style.left = `${r.left + window.scrollX}px`;3167  }3168  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);31693170  function onKeyDown(e: KeyboardEvent) {3171    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3172  }3173  document.addEventListener("keydown", onKeyDown);31743175  let exitScheduled = false;3176  function dismiss(userAction = false) {3177    if (exitScheduled) return;3178    exitScheduled = true;3179    stopObserving();3180    document.removeEventListener("click", outsideClick, { capture: true });3181    document.removeEventListener("keydown", onKeyDown);3182    if (userAction) options.onDismiss?.();3183    container.classList.add("is-exiting");3184    setTimeout(() => host.remove(), 130);3185  }31863187  function outsideClick(ev: MouseEvent) {3188    const path = ev.composedPath();3189    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3190  }3191  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);31923193  return dismiss;3194}