inject.ts

129.7 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  @keyframes identity-suggest-in {1092    from { opacity: 0; transform: translateY(-4px); }1093    to   { opacity: 1; transform: none; }1094  }1095  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1096    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1097  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1098  .identity-collapse-btn {1099    margin-left: auto; background: transparent; border: none; cursor: pointer;1100    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1101    line-height: 0; border-radius: 3px;1102    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1103  }1104  .identity-collapse-btn:hover { color: var(--peach-text); }1105  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1106  .identity-rows { display: grid; grid-template-rows: 1fr;1107    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1108  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1109  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1110    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1111  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1112  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1113  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1114  .identity-filter-pill {1115    padding: 2px 7px; border-radius: 999px;1116    border: 1px solid var(--peach-input-border);1117    background: transparent; color: var(--peach-text-muted);1118    font-family: "IBM Plex Mono", monospace; font-size: 9px;1119    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1120  }1121  .identity-filter-pill.is-on {1122    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1123    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1124    color: var(--peach-accent);1125  }1126  .identity-suggest-row {1127    display: flex; align-items: center; gap: 5px;1128    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1129    background: transparent; cursor: pointer; text-align: left;1130    transition: background 80ms;1131  }1132  .identity-suggest-row:hover { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); }1133  .identity-suggest-val {1134    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1135    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1136  }1137  .identity-suggest-type {1138    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1139    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1140  }1141  .identity-suggest-type--email {1142    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1143    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1144  }1145  .identity-suggest-type--username {1146    color: var(--peach-text-muted);1147    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1148  }1149  .identity-suggest-meta {1150    font-family: "IBM Plex Mono", monospace; font-size: 9px;1151    color: var(--peach-text-muted); flex-shrink: 0;1152  }1153  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1154  .pwgen-pill {1155    padding: 3px 8px; border-radius: 999px;1156    border: 1px solid var(--peach-input-border);1157    background: transparent; color: var(--peach-text-muted);1158    font-family: "IBM Plex Mono", monospace; font-size: 9px;1159    letter-spacing: 0.06em; cursor: pointer;1160    transition: all 130ms ease;1161  }1162  .pwgen-pill.is-on {1163    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1164    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1165    color: var(--peach-accent);1166  }1167  .pwgen-pill:not(.is-on):hover {1168    color: var(--peach-text-dim);1169    border-color: var(--peach-text-muted);1170  }1171  .pwgen-policy-hint {1172    font-size: 10px; color: var(--peach-text-muted);1173    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1174    line-height: 1.3;1175  }1176  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11771178  /* ── Save offer (after password filled) ───────────────────── */1179  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1180  .save-offer-title {1181    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1182  }1183  .save-offer-row {1184    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1185    border-radius: 7px; background: var(--peach-input-bg);1186    border: 1px solid var(--peach-input-border);1187  }1188  .save-offer-lbl {1189    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1190    font-family: "IBM Plex Mono", monospace;1191  }1192  .save-offer-val {1193    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1194    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1195  }1196  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1197  .save-offer-save {1198    flex: 1; padding: 9px; border-radius: 8px; border: none;1199    background: var(--peach-accent); color: #fff; font-size: 13px;1200    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1201  }1202  .save-offer-save:hover { filter: brightness(1.08); }1203  .save-offer-skip {1204    flex: 1; padding: 9px; border-radius: 8px; border: none;1205    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1206    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1207    font-family: Inter, sans-serif; transition: background 100ms ease;1208  }1209  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1210`;12111212export function showAutofillSelector(1213  anchorEl: HTMLInputElement,1214  entries: SelectorEntry[],1215  onSelect: (id: string) => void,1216  options: SelectorOptions = {}1217): () => void {1218  const host = document.createElement("div");1219  host.style.cssText = "position: absolute; z-index: 2147483647;";1220  host.style.setProperty("--peach-accent", accentHex);1221  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1222  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1223  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1224  const shadow = host.attachShadow({ mode: "closed" });12251226  const style = shadow.appendChild(document.createElement("style"));1227  style.textContent = SELECTOR_STYLES;12281229  const rect = anchorEl.getBoundingClientRect();1230  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1231  host.style.left = `${rect.left + window.scrollX}px`;1232  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1233  // wide single-input fields (e.g. centered email input on signup pages).1234  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;12351236  const container = shadow.appendChild(document.createElement("div"));1237  container.className = "peach-inline-popup";1238  container.setAttribute("data-theme", popupTheme);12391240  const searchableEntries = options.searchableEntries ?? [];1241  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12421243  let query = "";1244  let focusedIndex = -1;1245  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1246  let searchInput: HTMLInputElement | null = null;1247  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1248  // setInterval. Add to this list — don't fan out the dismiss function.1249  const cleanupHooks: Array<() => void> = [];12501251  // Pre-capture the anchor field value for username prefill1252  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1253  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1254  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";12551256  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1257    const seen = new Set<string>();1258    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1259  }12601261  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1262    const q = value.trim().toLowerCase();1263    const deduped = uniqueEntries(source);1264    if (!q) return deduped.slice(0, 8);1265    return deduped.filter(e =>1266      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1267    ).slice(0, 12);1268  }12691270  function activeEntries(): SelectorEntry[] {1271    // When user is typing a search, filter across all known entries (domain matches + vault)1272    if (query.trim()) {1273      const merged = uniqueEntries([...entries, ...searchableEntries]);1274      return filterEntries(merged, query);1275    }1276    // Default: show domain matches; fall back to vault search when no matches1277    if (entries.length > 0) return entries;1278    return filterEntries(searchableEntries, "").slice(0, 8);1279  }12801281  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1282    const icon = document.createElement("div");1283    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1284    if (isNew) {1285      icon.innerHTML = plusSvgStr();1286    } else {1287      // Use the generic key glyph for all entries in the page-injected selector.1288      // Avoids disclosing vault domains to any third party and avoids needing1289      // to expose the browser favicon API to page context via web_accessible_resources.1290      void url;1291      icon.innerHTML = keySvgStr();1292    }1293    return icon;1294  }12951296  function renderIdentityHelper() {1297    container.innerHTML = "";1298    const identities = options.savedIdentities ?? [];12991300    // Header: "NEW ACCOUNT" + domain name1301    const hdr = container.appendChild(document.createElement("div"));1302    hdr.className = "domain-header";1303    const eyebrow = hdr.appendChild(document.createElement("div"));1304    eyebrow.className = "domain-eyebrow";1305    eyebrow.textContent = "NEW ACCOUNT";1306    const domName = hdr.appendChild(document.createElement("div"));1307    domName.className = "domain-name";1308    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13091310    // Identity rows1311    const list = container.appendChild(document.createElement("div"));1312    list.className = "identity-list";1313    for (const id of identities) {1314      const row = list.appendChild(document.createElement("div"));1315      row.className = "peach-identity-row";1316      row.setAttribute("tabindex", "-1");1317      const val = row.appendChild(document.createElement("div"));1318      val.className = "peach-identity-value";1319      val.textContent = id.value;1320      const meta = row.appendChild(document.createElement("div"));1321      meta.className = "peach-identity-meta";1322      meta.textContent = `used ${id.useCount}×`;1323      row.addEventListener("click", () => {1324        options.onFillFields?.(id.value, "");1325        renderGenerator(id.value);1326      });1327    }13281329    // Divider before "Use a different email…"1330    if (identities.length > 0) {1331      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1332    }13331334    // "Use a different email…" expandable row1335    const altRow = container.appendChild(document.createElement("div"));1336    altRow.className = "identity-alt-row";1337    altRow.textContent = "+ Use a different email…";13381339    const altInputWrap = container.appendChild(document.createElement("div"));1340    altInputWrap.className = "identity-alt-input-wrap";1341    const altInput = altInputWrap.appendChild(document.createElement("input"));1342    altInput.className = "identity-alt-input";1343    altInput.type = "email";1344    altInput.placeholder = "[email protected]";1345    altInput.setAttribute("autocomplete", "off");1346    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1347    altConfirm.className = "identity-alt-confirm";1348    altConfirm.type = "button";1349    altConfirm.textContent = "✓";13501351    function fillCustomEmail() {1352      const v = altInput.value.trim();1353      if (!v) return;1354      options.onFillFields?.(v, "");1355      renderGenerator(v);1356    }13571358    altRow.addEventListener("click", () => {1359      altRow.style.display = "none";1360      altInputWrap.classList.add("open");1361      altInput.focus();1362    });1363    altConfirm.addEventListener("click", fillCustomEmail);1364    altInput.addEventListener("keydown", (e) => {1365      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1366    });1367  }13681369  function renderGenerator(filledEmail: string) {1370    container.innerHTML = "";1371    const sitePolicy = detectPasswordPolicy();13721373    const wrap = container.appendChild(document.createElement("div"));1374    wrap.className = "gen-view";13751376    // Header: domain + NEW ACCOUNT1377    const hdrRow = wrap.appendChild(document.createElement("div"));1378    hdrRow.className = "domain-header";1379    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1380    eyebrow2.className = "domain-eyebrow";1381    eyebrow2.textContent = "NEW ACCOUNT";1382    const domName2 = hdrRow.appendChild(document.createElement("div"));1383    domName2.className = "domain-name";1384    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13851386    // Confirmed email row1387    const conf = wrap.appendChild(document.createElement("div"));1388    conf.className = "gen-confirmed";1389    const confCheck = conf.appendChild(document.createElement("span"));1390    confCheck.className = "gen-confirmed-check";1391    confCheck.textContent = "✓";1392    const confVal = conf.appendChild(document.createElement("div"));1393    confVal.className = "gen-confirmed-val";1394    confVal.textContent = filledEmail;13951396    const lbl = wrap.appendChild(document.createElement("div"));1397    lbl.className = "gen-label";1398    lbl.textContent = "Generate a password";13991400    let currentPw = "";1401    const smartGen = createSmartGenerator({1402      policy: sitePolicy,1403      onChange: (pw) => { currentPw = pw; },1404    });1405    wrap.appendChild(smartGen.root);14061407    const fillBtn = wrap.appendChild(document.createElement("button"));1408    fillBtn.className = "gen-fill-btn";1409    fillBtn.type = "button";1410    fillBtn.textContent = "Copy & fill";1411    fillBtn.addEventListener("click", () => {1412      if (!currentPw) return;1413      options.onFillFields?.("", currentPw);1414      renderSaveOffer(filledEmail, currentPw);1415    });1416  }14171418  function renderSaveOffer(filledEmail: string, filledPassword: string) {1419    container.innerHTML = "";1420    const domain = options.domain ?? location.hostname.replace(/^www\./, "");14211422    const wrap = container.appendChild(document.createElement("div"));1423    wrap.className = "save-offer";14241425    const title = wrap.appendChild(document.createElement("div"));1426    title.className = "save-offer-title";1427    title.textContent = "Save this login to Peach?";14281429    function detailRow(label: string, value: string) {1430      const row = wrap.appendChild(document.createElement("div"));1431      row.className = "save-offer-row";1432      const lbl = row.appendChild(document.createElement("div"));1433      lbl.className = "save-offer-lbl";1434      lbl.textContent = label;1435      const val = row.appendChild(document.createElement("div"));1436      val.className = "save-offer-val";1437      val.textContent = value;1438    }14391440    detailRow("site", domain);1441    detailRow("email", filledEmail);1442    detailRow("password", "••••••••••••••••");14431444    const btns = wrap.appendChild(document.createElement("div"));1445    btns.className = "save-offer-btns";14461447    const saveBtn = btns.appendChild(document.createElement("button"));1448    saveBtn.className = "save-offer-save";1449    saveBtn.type = "button";1450    saveBtn.textContent = "Save";1451    saveBtn.addEventListener("click", async () => {1452      saveBtn.disabled = true;1453      saveBtn.textContent = "Saving…";1454      try {1455        const res = await chrome.runtime.sendMessage({1456          type: "ADD_ENTRY",1457          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1458        });1459        if ((res as { ok?: boolean }).ok) {1460          showSuccess(sTitle);1461        } else {1462          saveBtn.disabled = false;1463          saveBtn.textContent = "Save";1464        }1465      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1466    });14671468    const skipBtn = btns.appendChild(document.createElement("button"));1469    skipBtn.className = "save-offer-skip";1470    skipBtn.type = "button";1471    skipBtn.textContent = "Not now";1472    skipBtn.addEventListener("click", () => { dismiss(true); });1473  }14741475  function renderList() {1476    container.innerHTML = "";1477    focusedIndex = -1;1478    searchInput = null;14791480    const current = activeEntries();14811482    // Domain header (always show) — eyebrow + domain on the left,1483    // a "+" shortcut to the create form on the right so the user is never1484    // trapped in the search list when they want to make a new entry.1485    const domHdr = document.createElement("div");1486    domHdr.className = "domain-header";1487    const headText = document.createElement("div");1488    headText.className = "domain-header-text";1489    const eyebrow = document.createElement("div");1490    eyebrow.className = "domain-eyebrow";1491    eyebrow.textContent = options.isSignup1492      ? "Sign up as"1493      : entries.length > 0 ? "Saved for this site" : "No saved login";1494    const domName = document.createElement("div");1495    domName.className = "domain-name";1496    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1497    headText.append(eyebrow, domName);1498    domHdr.appendChild(headText);14991500    if (!options.isSignup) {1501      const addBtn = document.createElement("button");1502      addBtn.className = "domain-add-btn";1503      addBtn.type = "button";1504      addBtn.setAttribute("aria-label", "Create new entry");1505      addBtn.title = "Create new entry";1506      addBtn.textContent = "+";1507      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1508      domHdr.appendChild(addBtn);1509    }15101511    container.appendChild(domHdr);15121513    // Search — always show so user can find entries beyond the domain matches1514    const sw = document.createElement("div"); sw.className = "search-wrap";1515    searchInput = document.createElement("input");1516    searchInput.className = "search";1517    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1518    searchInput.value = query;1519    searchInput.addEventListener("input", () => {1520      query = searchInput?.value ?? "";1521      renderList();1522      searchInput?.focus();1523      searchInput?.setSelectionRange(query.length, query.length);1524    });1525    sw.appendChild(searchInput);1526    container.appendChild(sw);15271528    // Results1529    const results = document.createElement("div");1530    results.className = "results";1531    container.appendChild(results);15321533    if (current.length === 0 && entries.length > 0) {1534      // Show a hint but don't render empty entries1535    }15361537    for (let i = 0; i < current.length; i++) {1538      const e = current[i]!;1539      const entryEl = document.createElement("div");1540      entryEl.className = "entry";1541      entryEl.dataset.id = e.id;1542      entryEl.dataset.index = String(i);1543      entryEl.setAttribute("tabindex", "-1");15441545      entryEl.appendChild(makeEntryIcon(e.url));15461547      const info = document.createElement("div"); info.className = "entry-info";1548      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1549      const subEl = document.createElement("div"); subEl.className = "entry-sub";1550      const domain = e.url ? getDomainFromUrl(e.url) : "";1551      subEl.textContent = domain || e.username || "";1552      info.append(titleEl, subEl);1553      entryEl.appendChild(info);15541555      if (e.hasTotp) {1556        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1557        entryEl.appendChild(badge);1558      }1559      if (e.hasPasskey) {1560        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1561        entryEl.appendChild(badge);1562      }15631564      entryEl.addEventListener("click", () => {1565        if (options.isSignup && options.onFillFields) {1566          // Signup mode: clicking a saved identity fills the username field1567          options.onFillFields(e.username ?? "", "");1568          dismiss();1569        } else {1570          onSelect(e.id);1571          dismiss();1572        }1573      });1574      results.appendChild(entryEl);1575    }15761577    // Divider before "New entry"1578    if (current.length > 0) {1579      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1580    }15811582    // "New entry" row — always present1583    const newEl = document.createElement("div");1584    newEl.className = "entry";1585    newEl.setAttribute("tabindex", "-1");1586    newEl.appendChild(makeEntryIcon(undefined, true));15871588    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1589    const newTitle = document.createElement("div");1590    newTitle.className = "entry-title is-new";1591    newTitle.textContent = `New entry for ${sTitle}`;1592    const newSub = document.createElement("div");1593    newSub.className = "entry-sub";1594    newSub.textContent = sOrigin;1595    newInfo.append(newTitle, newSub);1596    newEl.appendChild(newInfo);1597    newEl.addEventListener("click", showCreateForm);1598    results.appendChild(newEl);15991600    // Focus search if present1601    if (searchInput) {1602      requestAnimationFrame(() => searchInput?.focus());1603    }1604  }16051606  function setFocused(idx: number) {1607    const all = container.querySelectorAll<HTMLElement>(".entry");1608    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1609    focusedIndex = idx;1610    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1611  }16121613  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[]): void {1614    if (!identities.length) return;1615    let activeFilter: "all" | "username" | "email" = "all";1616    let collapsed = false;16171618    const list = g.appendChild(document.createElement("div"));1619    list.className = "identity-suggest-list";1620    list.style.display = "none";16211622    // Filter pill row + collapse toggle1623    const filterRow = list.appendChild(document.createElement("div"));1624    filterRow.className = "identity-filter-row";1625    function makePill(label: string, value: "all" | "username" | "email") {1626      const b = filterRow.appendChild(document.createElement("button"));1627      b.type = "button"; b.className = "identity-filter-pill"; b.textContent = label;1628      b.addEventListener("mousedown", (e) => {1629        e.preventDefault();1630        activeFilter = value;1631        filterRow.querySelectorAll(".identity-filter-pill").forEach(p => p.classList.remove("is-on"));1632        b.classList.add("is-on");1633        render();1634      });1635      if (value === "all") b.classList.add("is-on");1636      return b;1637    }1638    makePill("all", "all");1639    makePill("user", "username");1640    makePill("email", "email");16411642    const collapseBtn = filterRow.appendChild(document.createElement("button"));1643    collapseBtn.type = "button";1644    collapseBtn.className = "identity-collapse-btn";1645    collapseBtn.innerHTML = `<svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 1L5 5L9 1"/></svg>`;1646    collapseBtn.addEventListener("mousedown", (e) => {1647      e.preventDefault();1648      collapsed = !collapsed;1649      collapseBtn.classList.toggle("is-collapsed", collapsed);1650      rowsWrapper.classList.toggle("is-collapsed", collapsed);1651    });16521653    const rowsWrapper = list.appendChild(document.createElement("div"));1654    rowsWrapper.className = "identity-rows";1655    const rows = rowsWrapper.appendChild(document.createElement("div"));1656    rows.className = "identity-rows-inner";16571658    function render() {1659      const q = inp.value.toLowerCase();1660      const filtered = identities1661        .filter(s => (activeFilter === "all" || s.type === activeFilter) && (!q || s.value.toLowerCase().includes(q)))1662        .slice(0, 8);1663      rows.innerHTML = "";1664      // Keep the list visible when the filter produces no results — hide only1665      // when there are genuinely no identities to show (handled by the caller).1666      if (!filtered.length) return;1667      for (const s of filtered) {1668        const row = rows.appendChild(document.createElement("button"));1669        row.type = "button"; row.className = "identity-suggest-row";1670        const val = row.appendChild(document.createElement("span"));1671        val.className = "identity-suggest-val"; val.textContent = s.value;1672        const badge = row.appendChild(document.createElement("span"));1673        badge.className = `identity-suggest-type identity-suggest-type--${s.type}`;1674        badge.textContent = s.type === "email" ? "@" : "u";1675        const meta = row.appendChild(document.createElement("span"));1676        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1677        row.addEventListener("mousedown", (e) => {1678          e.preventDefault();1679          inp.value = s.value;1680          list.style.display = "none";1681        });1682      }1683      list.style.display = "";1684    }1685    inp.addEventListener("focus", render);1686    inp.addEventListener("input", render);1687    inp.addEventListener("blur", () => setTimeout(() => { list.style.display = "none"; }, 150));1688  }16891690  async function showCreateForm() {1691    currentMode = "create";1692    container.innerHTML = "";16931694    // Guard: the service worker may lock the vault between when the selector1695    // opens and when the user clicks "New entry". Show the inline unlock form1696    // instead of silently failing on save.1697    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1698    if (!statusRes?.unlocked) {1699      renderLocked();1700      return;1701    }17021703    // Detect page password policy once for this form — reused on every1704    // regenerate click so the user always gets a compliant password.1705    const sitePolicy = detectPasswordPolicy();17061707    // Fetch identities on-demand — they're passed in signup context but not1708    // in login/search context where the user still clicks "New entry".1709    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1710    if (!formIdentities.length) {1711      try {1712        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1713        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1714      } catch { /* silent fallback */ }1715    }17161717    const wrap = document.createElement("div");1718    wrap.className = "create-form-wrap";17191720    // Header1721    const head = document.createElement("div"); head.className = "create-head";1722    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1723    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>`;1724    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1725    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1726    head.append(backBtn, lbl);17271728    // Body1729    const body = document.createElement("div"); body.className = "create-body";17301731    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1732      const g = document.createElement("div"); g.className = "f-group";1733      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1734      const inp = document.createElement("input"); inp.className = "f-input";1735      g.append(l, inp); return { g, inp };1736    }17371738    // Title1739    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1740    body.appendChild(tg.g);17411742    // URL1743    const ug = fGroup("website");1744    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1745    if (loginSubdomain) {1746      const h = document.createElement("div"); h.className = "url-hint";1747      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1748    }1749    body.appendChild(ug.g);17501751    // Username — pre-fill from anchor if it doesn't look like an email1752    const xg = fGroup("username");1753    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1754    xg.inp.placeholder = "johndoe";1755    xg.inp.setAttribute("autocomplete", "off");1756    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities);1757    body.appendChild(xg.g);17581759    // Email — pre-fill from anchor if it looks like an email1760    const eg = fGroup("email");1761    (eg.inp as HTMLInputElement).type = "email";1762    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1763    eg.inp.placeholder = "[email protected]";1764    eg.inp.setAttribute("autocomplete", "off");1765    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities);1766    body.appendChild(eg.g);17671768    // Password — full smart generator with charset pills + length slider +1769    // policy hint. Mirrors the main UI's compact generator so users get the1770    // same controls inline as in the popup.1771    const pg = fGroup("password");1772    let currentPassword = prePassword || "";1773    const smartGen = createSmartGenerator({1774      policy: sitePolicy,1775      initialPassword: prePassword || undefined,1776      onChange: (pw) => { currentPassword = pw; },1777    });1778    pg.g.appendChild(smartGen.root);1779    body.appendChild(pg.g);17801781    // Save1782    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1783    saveBtn.textContent = "Save entry";1784    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1785    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1786    saveBtn.addEventListener("click", async () => {1787      const title = tg.inp.value.trim();1788      const pw = currentPassword.trim();1789      const username = xg.inp.value.trim();1790      const email = eg.inp.value.trim();1791      if (!title) {1792        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1793        showFormError("Entry needs a title");1794        return;1795      }1796      if (!pw) {1797        showFormError("Entry needs a password — tap regen to make one");1798        return;1799      }1800      errEl.style.display = "none";1801      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1802      try {1803        const res = await chrome.runtime.sendMessage({1804          type: "ADD_ENTRY",1805          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1806        });1807        if ((res as { ok?: boolean }).ok) {1808          // Fill the detected form. onFillFields uses whichever identity the1809          // page anchored on — the vault captures both username and email.1810          options.onFillFields?.(username || email, pw);1811          showSuccess(title);1812        } else {1813          const errMsg = (res as { error?: string }).error === "vault locked"1814            ? "Vault locked — open Peach to save"1815            : "Could not save entry";1816          showFormError(errMsg);1817          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1818        }1819      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1820    });1821    body.appendChild(saveBtn);1822    body.appendChild(errEl);18231824    wrap.append(head, body);1825    container.appendChild(wrap);1826    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1827  }18281829  function showSuccess(title: string) {1830    currentMode = "success";1831    container.innerHTML = "";1832    const wrap = document.createElement("div"); wrap.className = "success-wrap";1833    const ring = document.createElement("div"); ring.className = "success-ring";1834    ring.innerHTML = checkSvgStr();1835    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1836    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1837    wrap.append(ring, t, s);1838    container.appendChild(wrap);1839    setTimeout(() => dismiss(), 1600);1840  }18411842  function flashActionBtn(btn: HTMLButtonElement) {1843    btn.classList.add("flashed");1844    setTimeout(() => btn.classList.remove("flashed"), 700);1845  }18461847  function renderSilverPlatter(entry: SelectorEntry) {1848    container.innerHTML = "";1849    searchInput = null;1850    focusedIndex = -1;1851    currentMode = "silver-platter";18521853    const domHdr = document.createElement("div");1854    domHdr.className = "domain-header";1855    const headText = document.createElement("div");1856    headText.className = "domain-header-text";1857    const eyebrow = document.createElement("div");1858    eyebrow.className = "domain-eyebrow";1859    eyebrow.textContent = "Saved for this site";1860    const domName = document.createElement("div");1861    domName.className = "domain-name";1862    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1863    headText.append(eyebrow, domName);1864    domHdr.appendChild(headText);1865    if (!options.isSignup) {1866      const addBtn = document.createElement("button");1867      addBtn.className = "domain-add-btn";1868      addBtn.type = "button";1869      addBtn.setAttribute("aria-label", "Create new entry");1870      addBtn.title = "Create new entry";1871      addBtn.textContent = "+";1872      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1873      domHdr.appendChild(addBtn);1874    }1875    container.appendChild(domHdr);18761877    const platter = document.createElement("div");1878    platter.className = "silver-platter";18791880    const titleEl = document.createElement("div");1881    titleEl.className = "sp-title";1882    titleEl.textContent = entry.title;1883    platter.appendChild(titleEl);18841885    if (entry.email) {1886      const emailEl = document.createElement("div");1887      emailEl.className = "sp-identity-row";1888      const emailLbl = document.createElement("span");1889      emailLbl.className = "sp-identity-label";1890      emailLbl.textContent = "email";1891      const emailVal = document.createElement("span");1892      emailVal.className = "sp-username";1893      emailVal.textContent = entry.email;1894      emailEl.append(emailLbl, emailVal);1895      platter.appendChild(emailEl);1896    }18971898    if (entry.username) {1899      const userEl = document.createElement("div");1900      userEl.className = "sp-identity-row";1901      const userLbl = document.createElement("span");1902      userLbl.className = "sp-identity-label";1903      userLbl.textContent = entry.username.includes("@") ? "email" : "username";1904      const userVal = document.createElement("span");1905      userVal.className = "sp-username";1906      userVal.textContent = entry.username;1907      userEl.append(userLbl, userVal);1908      platter.appendChild(userEl);1909    }19101911    const fillBtn = document.createElement("button");1912    fillBtn.className = "sp-fill-btn";1913    fillBtn.type = "button";1914    fillBtn.textContent = "Fill credentials";1915    fillBtn.addEventListener("click", () => {1916      if (fillBtn.disabled) return;1917      fillBtn.disabled = true;1918      fillBtn.classList.add("filled");1919      fillBtn.innerHTML = checkSvgStr();1920      // Fire the fill, then exit via the standard exit animation. The fill1921      // itself is async (handled in index.ts) — by 400ms the form is filled1922      // and the popup begins its exit. Total dwell from click to host1923      // removal: 400ms + 130ms (exit animation) = 530ms.1924      onSelect(entry.id);1925      setTimeout(() => dismiss(), 400);1926    });1927    platter.appendChild(fillBtn);19281929    const actions = document.createElement("div");1930    actions.className = "sp-actions";19311932    if (entry.email) {1933      const copyEmail = document.createElement("button");1934      copyEmail.className = "sp-action-btn";1935      copyEmail.type = "button";1936      copyEmail.title = "Copy email";1937      copyEmail.textContent = "Copy email";1938      copyEmail.addEventListener("click", async (e) => {1939        e.stopPropagation();1940        let alreadyWritten = false;1941        try { await navigator.clipboard.writeText(entry.email!); alreadyWritten = true; } catch {}1942        await chrome.runtime.sendMessage({1943          type: "COPY",1944          payload: { text: entry.email, label: "Email", alreadyWritten },1945        }).catch(() => {});1946        flashActionBtn(copyEmail);1947      });1948      actions.appendChild(copyEmail);1949    }19501951    const copyU = document.createElement("button");1952    copyU.className = "sp-action-btn";1953    copyU.type = "button";1954    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";1955    copyU.title = copyULabel;1956    copyU.textContent = copyULabel;1957    copyU.disabled = !entry.username;1958    copyU.addEventListener("click", async (e) => {1959      e.stopPropagation();1960      if (!entry.username) return;1961      let alreadyWritten = false;1962      try { await navigator.clipboard.writeText(entry.username); alreadyWritten = true; } catch {}1963      await chrome.runtime.sendMessage({1964        type: "COPY",1965        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },1966      }).catch(() => {});1967      flashActionBtn(copyU);1968    });1969    actions.appendChild(copyU);19701971    const copyP = document.createElement("button");1972    copyP.className = "sp-action-btn";1973    copyP.type = "button";1974    copyP.title = "Copy password";1975    copyP.textContent = "Copy password";1976    copyP.addEventListener("click", async (e) => {1977      e.stopPropagation();1978      const resp = await chrome.runtime.sendMessage({1979        type: "GET_ENTRY_FOR_FILL",1980        payload: { id: entry.id },1981      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;1982      if (!resp?.ok || !resp.data?.password) return;1983      let alreadyWritten = false;1984      try { await navigator.clipboard.writeText(resp.data.password); alreadyWritten = true; } catch {}1985      await chrome.runtime.sendMessage({1986        type: "COPY",1987        payload: { text: resp.data.password, label: "Password", alreadyWritten },1988      }).catch(() => {});1989      flashActionBtn(copyP);1990    });1991    actions.appendChild(copyP);19921993    let trayEl: HTMLDivElement | null = null;1994    let trayInterval: ReturnType<typeof setInterval> | null = null;19951996    function closeTray() {1997      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }1998      trayEl?.remove();1999      trayEl = null;2000    }2001    // Register so dismiss() will close the tray and clear the interval2002    // even if the user dismisses without explicitly closing the tray.2003    cleanupHooks.push(closeTray);20042005    async function openTOTPTray() {2006      // Fetch the entry to get the TOTP secret. The selector summary doesn't2007      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2008      // the message-passing surface minimal per Projects.md §5.2).2009      const resp = await chrome.runtime.sendMessage({2010        type: "GET_ENTRY_FOR_FILL",2011        payload: { id: entry.id },2012      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2013      const secret = resp?.ok ? resp.data?.totp : undefined;2014      if (!secret) return;20152016      trayEl = document.createElement("div");2017      trayEl.className = "sp-tray";20182019      const label = document.createElement("span");2020      label.className = "sp-tray-label";2021      label.textContent = "2FA";2022      trayEl.appendChild(label);20232024      const codeEl = document.createElement("div");2025      codeEl.className = "sp-totp-code";2026      trayEl.appendChild(codeEl);20272028      const ringNs = "http://www.w3.org/2000/svg";2029      const ring = document.createElementNS(ringNs, "svg");2030      ring.setAttribute("class", "sp-totp-ring");2031      ring.setAttribute("viewBox", "0 0 24 24");2032      const trackC = document.createElementNS(ringNs, "circle");2033      trackC.setAttribute("class", "ring-track");2034      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2035      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2036      const fillC = document.createElementNS(ringNs, "circle");2037      fillC.setAttribute("class", "ring-fill");2038      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2039      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2040      fillC.setAttribute("stroke-linecap", "round");2041      fillC.setAttribute("stroke-dasharray", "62.83");2042      ring.append(trackC, fillC);2043      trayEl.appendChild(ring);20442045      const copyBtn = document.createElement("button");2046      copyBtn.className = "sp-totp-copy";2047      copyBtn.type = "button";2048      copyBtn.textContent = "Copy";2049      trayEl.appendChild(copyBtn);20502051      function refresh() {2052        const { code, remaining } = generateTOTP(secret!);2053        // Group as "847 291" — easier to read than "847291"2054        codeEl.textContent = code.length === 62055          ? `${code.slice(0, 3)} ${code.slice(3)}`2056          : code;2057        // Ring fills counter-clockwise as time elapses: dashoffset goes from2058        // 0 (full ring) to 62.83 (empty) over the 30s window.2059        const fraction = (30 - remaining) / 30;2060        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2061      }2062      refresh();2063      trayInterval = setInterval(refresh, 1000);20642065      copyBtn.addEventListener("click", async (e) => {2066        e.stopPropagation();2067        const { code } = generateTOTP(secret!);2068        let alreadyWritten = false;2069        try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}2070        await chrome.runtime.sendMessage({2071          type: "COPY",2072          payload: { text: code, label: "TOTP", alreadyWritten },2073        }).catch(() => {});2074        copyBtn.textContent = "Copied";2075        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2076      });20772078      platter.appendChild(trayEl);2079    }20802081    const editBtn = document.createElement("button");2082    editBtn.className = "sp-action-btn sp-action-edit";2083    editBtn.type = "button";2084    editBtn.title = "Edit entry";2085    editBtn.textContent = "Edit";2086    editBtn.addEventListener("click", (e) => {2087      e.stopPropagation();2088      closeTray();2089      void renderInlineEdit(entry);2090    });2091    actions.appendChild(editBtn);20922093    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2094    // "···" toggle was zero-savings (the toggle button took the same space2095    // the "2FA" label needed) and made the code one extra click away.2096    if (entry.hasTotp) void openTOTPTray();20972098    platter.appendChild(actions);2099    container.appendChild(platter);2100  }21012102  /**2103   * Inline-popup edit mode. Swaps the silver platter for an editable form2104   * over the same shadow-DOM surface so the user never leaves the page.2105   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2106   * with the new fields. Cancel returns without writing.2107   */2108  async function renderInlineEdit(summary: SelectorEntry) {2109    container.innerHTML = "";2110    const wrap = document.createElement("div");2111    wrap.className = "create-form-wrap";21122113    const head = document.createElement("div");2114    head.className = "create-head";2115    const back = document.createElement("button");2116    back.className = "back-btn";2117    back.type = "button";2118    back.title = "Cancel";2119    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>`;2120    back.addEventListener("click", () => renderSilverPlatter(summary));2121    head.appendChild(back);2122    const headLbl = document.createElement("div");2123    headLbl.className = "create-label";2124    headLbl.textContent = "Edit entry";2125    head.appendChild(headLbl);2126    wrap.appendChild(head);21272128    const body = document.createElement("div");2129    body.className = "create-body";21302131    // Loading shimmer while we fetch the full entry2132    const loading = document.createElement("div");2133    loading.className = "empty-hint";2134    loading.textContent = "loading…";2135    body.appendChild(loading);2136    wrap.appendChild(body);2137    container.appendChild(wrap);21382139    const res = (await chrome.runtime.sendMessage({2140      type: "GET_ENTRY_FOR_FILL",2141      payload: { id: summary.id },2142    }).catch(() => null)) as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;21432144    if (!res || !res.ok || !res.data) {2145      loading.textContent = "couldn't load this entry. try again from the popup.";2146      return;2147    }2148    body.innerHTML = "";21492150    function field(label: string, value: string, type: "text" | "password" = "text"): HTMLInputElement {2151      const group = document.createElement("div");2152      group.className = "f-group";2153      const lbl = document.createElement("div");2154      lbl.className = "f-label";2155      lbl.textContent = label;2156      const input = document.createElement("input");2157      input.className = "f-input";2158      input.type = type;2159      input.value = value;2160      input.autocomplete = "off";2161      group.append(lbl, input);2162      body.appendChild(group);2163      return input;2164    }21652166    const titleInput = field("title", res.data.title ?? "");2167    const urlInput = field("url", res.data.url ?? "");2168    urlInput.classList.add("url-f");2169    const usernameLabel = (res.data.username ?? "").includes("@") ? "email" : "username";2170    const usernameInput = field(usernameLabel, res.data.username ?? "");2171    const emailInput = field("email", res.data.email ?? "");21722173    // Password row with reveal toggle2174    const pwGroup = document.createElement("div");2175    pwGroup.className = "f-group";2176    const pwLbl = document.createElement("div");2177    pwLbl.className = "f-label";2178    pwLbl.textContent = "password";2179    const pwRow = document.createElement("div");2180    pwRow.className = "f-row";2181    const pwInput = document.createElement("input");2182    pwInput.className = "f-input";2183    pwInput.type = "password";2184    pwInput.value = res.data.password ?? "";2185    pwInput.autocomplete = "new-password";2186    const revealBtn = document.createElement("button");2187    revealBtn.className = "gen-btn";2188    revealBtn.type = "button";2189    revealBtn.textContent = "show";2190    revealBtn.addEventListener("click", () => {2191      const reveal = pwInput.type === "password";2192      pwInput.type = reveal ? "text" : "password";2193      revealBtn.textContent = reveal ? "hide" : "show";2194    });2195    pwRow.append(pwInput, revealBtn);2196    pwGroup.append(pwLbl, pwRow);2197    body.appendChild(pwGroup);21982199    const totpInput = field("2fa secret", res.data.totp ?? "");22002201    // Notes2202    const notesGroup = document.createElement("div");2203    notesGroup.className = "f-group";2204    const notesLbl = document.createElement("div");2205    notesLbl.className = "f-label";2206    notesLbl.textContent = "notes";2207    const notesInput = document.createElement("textarea");2208    notesInput.className = "f-input";2209    notesInput.rows = 3;2210    notesInput.value = res.data.notes ?? "";2211    notesInput.style.fontFamily = "Inter, sans-serif";2212    notesInput.style.resize = "vertical";2213    notesGroup.append(notesLbl, notesInput);2214    body.appendChild(notesGroup);22152216    // Save / Cancel row2217    const actionsRow = document.createElement("div");2218    actionsRow.className = "f-row";2219    const saveBtn = document.createElement("button");2220    saveBtn.className = "save-btn";2221    saveBtn.type = "button";2222    saveBtn.textContent = "Save changes";2223    saveBtn.style.flex = "1";2224    const cancelBtn = document.createElement("button");2225    cancelBtn.className = "gen-btn";2226    cancelBtn.type = "button";2227    cancelBtn.textContent = "cancel";2228    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2229    actionsRow.append(saveBtn, cancelBtn);2230    body.appendChild(actionsRow);22312232    saveBtn.addEventListener("click", async () => {2233      saveBtn.disabled = true;2234      const originalLabel = saveBtn.textContent;2235      saveBtn.textContent = "Saving…";2236      const patch: Record<string, unknown> = {2237        title: titleInput.value.trim(),2238        url: urlInput.value.trim(),2239        username: usernameInput.value.trim(),2240        email: emailInput.value.trim() || undefined,2241        password: pwInput.value,2242        totp: totpInput.value.trim(),2243        notes: notesInput.value,2244      };2245      const updateRes = (await chrome.runtime.sendMessage({2246        type: "UPDATE_ENTRY",2247        payload: { id: summary.id, patch },2248      }).catch(() => null)) as { ok: boolean; error?: string } | null;2249      if (!updateRes?.ok) {2250        saveBtn.disabled = false;2251        saveBtn.textContent = originalLabel;2252        const err = document.createElement("div");2253        err.className = "empty-hint";2254        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2255        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2256        body.appendChild(err);2257        setTimeout(() => err.remove(), 3000);2258        return;2259      }2260      // Refresh the platter with updated summary fields2261      const refreshed: SelectorEntry = {2262        id: summary.id,2263        title: patch.title as string,2264        username: patch.username as string,2265        email: patch.email as string | undefined,2266        url: patch.url as string,2267        hasTotp: Boolean(patch.totp),2268        hasPasskey: summary.hasPasskey,2269      };2270      renderSilverPlatter(refreshed);2271    });22722273    queueMicrotask(() => titleInput.focus());2274  }22752276  function renderLocked() {2277    container.innerHTML = "";22782279    // Domain header (same as list view)2280    const domHdr = document.createElement("div");2281    domHdr.className = "domain-header";2282    const eyebrow = document.createElement("div");2283    eyebrow.className = "domain-eyebrow";2284    eyebrow.textContent = "vault locked";2285    const domName = document.createElement("div");2286    domName.className = "domain-name";2287    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2288    domHdr.append(eyebrow, domName);2289    container.appendChild(domHdr);22902291    const wrap = document.createElement("div");2292    wrap.className = "locked-wrap";22932294    // Icon + label row2295    const head = document.createElement("div"); head.className = "locked-head";2296    const icon = document.createElement("div"); icon.className = "locked-icon";2297    icon.innerHTML = keySvgStr();2298    const title = document.createElement("div"); title.className = "locked-title";2299    title.textContent = "unlock to autofill";2300    head.append(icon, title);23012302    // Password input2303    const pwInp = document.createElement("input");2304    pwInp.className = "locked-input";2305    pwInp.type = "password";2306    pwInp.placeholder = "master password";2307    pwInp.setAttribute("autocomplete", "current-password");23082309    // Error line (hidden initially)2310    const errEl = document.createElement("div");2311    errEl.className = "locked-error";2312    errEl.style.display = "none";23132314    // Unlock button2315    const unlockBtn = document.createElement("button");2316    unlockBtn.className = "locked-btn";2317    unlockBtn.type = "button";2318    unlockBtn.textContent = "unlock";23192320    async function tryUnlock() {2321      const pw = pwInp.value.trim();2322      if (!pw) { pwInp.focus(); return; }2323      unlockBtn.disabled = true;2324      unlockBtn.textContent = "unlocking…";2325      errEl.style.display = "none";2326      try {2327        const res = await chrome.runtime.sendMessage({2328          type: "UNLOCK",2329          payload: { password: pw },2330        });2331        if ((res as { ok?: boolean }).ok) {2332          dismiss();2333          options.onUnlocked?.();2334        } else {2335          errEl.textContent = "incorrect password";2336          errEl.style.display = "block";2337          pwInp.value = "";2338          pwInp.focus();2339          unlockBtn.disabled = false;2340          unlockBtn.textContent = "unlock";2341        }2342      } catch {2343        errEl.textContent = "could not reach Peach";2344        errEl.style.display = "block";2345        unlockBtn.disabled = false;2346        unlockBtn.textContent = "unlock";2347      }2348    }23492350    pwInp.addEventListener("keydown", (e) => {2351      e.stopPropagation();2352      if (e.key === "Enter") void tryUnlock();2353    });2354    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2355    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2356    unlockBtn.addEventListener("click", () => void tryUnlock());23572358    wrap.append(head, pwInp, errEl, unlockBtn);2359    container.appendChild(wrap);23602361    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2362    // the page reclaims focus from our Shadow DOM input before the user can2363    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2364    // Instead: intercept keystrokes at the document capture phase — this runs2365    // before any page handler regardless of which element technically has2366    // OS focus — and route them into our input.2367    const captureKeydown = (e: KeyboardEvent) => {2368      if (!host.isConnected) {2369        document.removeEventListener("keydown", captureKeydown, true);2370        return;2371      }2372      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2373      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2374      // Intercept before page handlers and give our input focus.2375      e.stopImmediatePropagation();2376      if (e.key === "Escape") { dismiss(true); return; }2377      if (e.key === "Enter") { void tryUnlock(); return; }2378      // For all other printable/editing keys, ensure our input has focus so2379      // the browser delivers the keystroke there naturally.2380      if (document.activeElement !== host) {2381        pwInp.focus({ preventScroll: true });2382      }2383    };2384    captureKeydownRef = captureKeydown;2385    document.addEventListener("keydown", captureKeydown, true);23862387    // Best-effort focus on open — may be overridden by page focus trap,2388    // but the capture listener above handles typing regardless.2389    pwInp.focus({ preventScroll: true });2390    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2391  }23922393  function handleKeyDown(e: KeyboardEvent) {2394    if (options.locked) {2395      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2396      return;2397    }2398    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2399      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2400      return;2401    }2402    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2403    const count = allEntryEls.length;2404    if (document.activeElement === searchInput) {2405      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2406      if (count === 0) return;2407      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2408    }2409    if (count === 0) return;2410    switch (e.key) {2411      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2412      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2413      case "Enter": {2414        if (focusedIndex >= 0) {2415          const el = allEntryEls[focusedIndex] as HTMLElement;2416          const id = el.dataset.id;2417          if (id) { onSelect(id); dismiss(); }2418          else if (el.classList.contains("is-new") || !id) {2419            // "New entry" row (last item, no data-id)2420            showCreateForm();2421          }2422        }2423        break;2424      }2425      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2426    }2427  }24282429  document.addEventListener("keydown", handleKeyDown);24302431  document.body.appendChild(host);24322433  function updatePosition() {2434    const r = anchorEl.getBoundingClientRect();2435    host.style.top = `${r.bottom + window.scrollY + 5}px`;2436    host.style.left = `${r.left + window.scrollX}px`;2437  }2438  // These bindings are referenced from renderLocked()/dismiss() — they MUST2439  // be initialized before renderLocked() runs, or the synchronous assignment2440  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2441  // and throws ReferenceError. The throw lands after the popup is rendered2442  // but before showAutofillSelector returns its dismiss handle, leaving an2443  // orphan host in the DOM (which is what caused the locked-popup stacking2444  // and missing autofocus on every click).2445  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2446  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);24472448  if (options.locked) {2449    renderLocked();2450  } else if (options.isSignup && options.savedIdentities) {2451    // State 10: identity helper — signup form detected, show derived2452    // identity list (emails then usernames) instead of vault entry list.2453    renderIdentityHelper();2454  } else if (entries.length === 1 && !options.isSignup) {2455    // Silver platter (State 1): single domain match → focused fill view.2456    // Multi-match goes through renderList instead.2457    renderSilverPlatter(entries[0]!);2458  } else {2459    renderList();2460  }24612462  let exitScheduled = false;2463  function dismiss(userAction = false) {2464    // Idempotent: dismiss() can be called from multiple paths (Escape,2465    // outside click, entry select, fill success, host page nav). The exit2466    // animation must only play once and host.remove() must run exactly once.2467    if (exitScheduled) return;2468    exitScheduled = true;2469    // Detach listeners synchronously so nothing can re-trigger during the2470    // 130ms exit window (a focusin firing here would race against the2471    // dismiss-lock work in Pass 2).2472    stopObserving();2473    document.removeEventListener("click", outsideClick, { capture: true });2474    document.removeEventListener("keydown", handleKeyDown);2475    if (captureKeydownRef) {2476      document.removeEventListener("keydown", captureKeydownRef, true);2477      captureKeydownRef = null;2478    }2479    for (const cleanup of cleanupHooks) {2480      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2481    }2482    if (userAction) options.onDismiss?.();2483    container.classList.add("is-exiting");2484    setTimeout(() => host.remove(), 130);2485  }24862487  function outsideClick(ev: MouseEvent) {2488    const path = ev.composedPath();2489    // Never dismiss when clicking the anchor field itself — that click is2490    // what triggered the selector to open, and the user may click the field2491    // again to re-focus it without intending to close the selector.2492    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2493  }2494  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2495  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);24962497  return dismiss;2498}24992500export interface CardSelectorEntry {2501  id: string;2502  title: string;2503  cardholderName?: string;2504  last4?: string;2505  expMonth?: string;2506  expYear?: string;2507  network?: import("../shared/types").CardNetwork;2508}25092510interface CardSelectorOptions {2511  domain?: string;2512  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2513  onFill: (entry: import("../shared/types").VaultEntry) => void;2514  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2515  onDismiss?: () => void;2516}25172518/**2519 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2520 * passkey create or get. Renders as a fixed-position floating popup (no2521 * field anchor needed — passkeys don't require a focused input). Uses the2522 * same theme tokens and entrance animation as all other inline popup states.2523 */2524export function showPasskeyProGate(): void {2525  const domain = location.hostname.replace(/^www\./, "");25262527  const host = document.createElement("div");2528  host.setAttribute("data-peach-passkey-gate", "1");2529  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2530  const shadow = host.attachShadow({ mode: "closed" });25312532  const style = document.createElement("style");2533  style.textContent = `2534    :host { all: initial; }2535    .gate-wrap {2536      position: fixed;2537      top: 50%;2538      left: 50%;2539      transform: translate(-50%, -50%);2540      width: 280px;2541      pointer-events: auto;2542      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2543    }2544    @keyframes g-in {2545      from { opacity:0; transform: translate(-50%,-52%); }2546      to   { opacity:1; transform: translate(-50%,-50%); }2547    }2548    .gate-wrap.is-exiting {2549      animation: g-out 130ms ease-in forwards;2550    }2551    @keyframes g-out {2552      to { opacity:0; transform: translate(-50%,-52%); }2553    }2554    .gate {2555      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2556      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2557      border-radius: 12px;2558      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2559      padding: 16px;2560      font-family: Inter, sans-serif;2561    }2562    .gate-header {2563      display: flex;2564      align-items: center;2565      gap: 7px;2566      margin-bottom: 12px;2567      padding-bottom: 10px;2568      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2569    }2570    .gate-domain {2571      font-size: 12px;2572      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2573      font-family: "IBM Plex Mono", monospace;2574      overflow: hidden;2575      text-overflow: ellipsis;2576      white-space: nowrap;2577    }2578    .gate-title {2579      font-size: 14px;2580      font-weight: 500;2581      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2582      margin-bottom: 6px;2583    }2584    .gate-subtitle {2585      font-size: 12px;2586      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2587      line-height: 1.5;2588      margin-bottom: 14px;2589    }2590    .gate-btn {2591      display: block;2592      width: 100%;2593      padding: 9px 0;2594      border-radius: 8px;2595      border: none;2596      cursor: pointer;2597      font-size: 13px;2598      font-family: Inter, sans-serif;2599      font-weight: 500;2600      transition: opacity 100ms;2601      margin-bottom: 7px;2602      text-align: center;2603    }2604    .gate-btn:last-child { margin-bottom: 0; }2605    .gate-btn--accent {2606      background: ${accentHex};2607      color: #fff;2608    }2609    .gate-btn--accent:hover { opacity: 0.88; }2610    .gate-btn--ghost {2611      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2612      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2613    }2614    .gate-btn--ghost:hover { opacity: 0.75; }2615    .backdrop {2616      position: fixed;2617      inset: 0;2618      pointer-events: auto;2619    }2620  `;2621  shadow.appendChild(style);26222623  const backdrop = document.createElement("div");2624  backdrop.className = "backdrop";2625  shadow.appendChild(backdrop);26262627  const wrap = document.createElement("div");2628  wrap.className = "gate-wrap";2629  shadow.appendChild(wrap);26302631  const gate = document.createElement("div");2632  gate.className = "gate";2633  wrap.appendChild(gate);26342635  // Header: peach icon + domain2636  const header = document.createElement("div");2637  header.className = "gate-header";2638  const icon = document.createElement("span");2639  icon.innerHTML = peachIconSvg();2640  const domainEl = document.createElement("span");2641  domainEl.className = "gate-domain";2642  domainEl.textContent = domain;2643  header.append(icon, domainEl);2644  gate.appendChild(header);26452646  const title = document.createElement("div");2647  title.className = "gate-title";2648  title.textContent = "Passkeys are part of Peach Pro.";2649  gate.appendChild(title);26502651  const subtitle = document.createElement("div");2652  subtitle.className = "gate-subtitle";2653  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2654  gate.appendChild(subtitle);26552656  const upgradeBtn = document.createElement("button");2657  upgradeBtn.className = "gate-btn gate-btn--accent";2658  upgradeBtn.type = "button";2659  upgradeBtn.textContent = "Upgrade to Pro";2660  gate.appendChild(upgradeBtn);26612662  const laterBtn = document.createElement("button");2663  laterBtn.className = "gate-btn gate-btn--ghost";2664  laterBtn.type = "button";2665  laterBtn.textContent = "Not right now";2666  gate.appendChild(laterBtn);26672668  function dismiss() {2669    wrap.classList.add("is-exiting");2670    setTimeout(() => host.remove(), 130);2671  }26722673  upgradeBtn.addEventListener("click", () => {2674    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2675    dismiss();2676  });2677  laterBtn.addEventListener("click", dismiss);2678  backdrop.addEventListener("click", dismiss);26792680  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2681    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2682  });26832684  document.body.appendChild(host);2685}26862687/**2688 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2689 * detector sees the page invoke navigator.credentials.create(); content/index.ts2690 * checks vault + decline state then calls this. "Save passkey to Peach"2691 * initiates the popup-context credential flow; "Not now" records a 30-day2692 * decline for the domain so we don't re-show on every page reload.2693 */2694export function showPasskeyRegistrationOffer(args: {2695  rpId: string;2696  rpName?: string;2697  userName?: string;2698  userDisplayName?: string;2699}): void {2700  const domain = location.hostname.replace(/^www\./, "");2701  const displayName = args.rpName || domain;27022703  const host = document.createElement("div");2704  host.setAttribute("data-peach-passkey-offer", "1");2705  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2706  const shadow = host.attachShadow({ mode: "closed" });27072708  const style = document.createElement("style");2709  style.textContent = `2710    :host { all: initial; }2711    .offer-wrap {2712      position: fixed;2713      top: 16px;2714      right: 16px;2715      width: 320px;2716      pointer-events: auto;2717      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2718    }2719    @keyframes o-in {2720      from { opacity: 0; transform: translateY(-6px); }2721      to   { opacity: 1; transform: translateY(0); }2722    }2723    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2724    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2725    .offer {2726      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2727      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2728      border-radius: 12px;2729      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2730      padding: 14px 14px 12px;2731      font-family: Inter, sans-serif;2732      position: relative;2733    }2734    .offer-close {2735      position: absolute;2736      top: 8px;2737      right: 8px;2738      width: 18px;2739      height: 18px;2740      border: none;2741      background: transparent;2742      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2743      cursor: pointer;2744      font-size: 14px;2745      line-height: 1;2746      padding: 0;2747    }2748    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2749    .offer-header {2750      display: flex;2751      align-items: center;2752      gap: 7px;2753      margin-bottom: 8px;2754      padding-bottom: 8px;2755      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2756    }2757    .offer-domain {2758      font-size: 12px;2759      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2760      font-family: "IBM Plex Mono", monospace;2761      overflow: hidden;2762      text-overflow: ellipsis;2763      white-space: nowrap;2764    }2765    .offer-title {2766      font-size: 13px;2767      font-weight: 500;2768      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2769      margin-bottom: 4px;2770    }2771    .offer-subtitle {2772      font-size: 11px;2773      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2774      line-height: 1.45;2775      margin-bottom: 12px;2776    }2777    .offer-btn {2778      display: block;2779      width: 100%;2780      padding: 8px 0;2781      border-radius: 7px;2782      border: none;2783      cursor: pointer;2784      font-size: 12px;2785      font-family: Inter, sans-serif;2786      font-weight: 500;2787      transition: opacity 100ms;2788      margin-bottom: 6px;2789      text-align: center;2790    }2791    .offer-btn:last-child { margin-bottom: 0; }2792    .offer-btn--accent { background: ${accentHex}; color: #fff; }2793    .offer-btn--accent:hover { opacity: 0.88; }2794    .offer-btn--ghost {2795      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2796      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2797    }2798    .offer-btn--ghost:hover { opacity: 0.75; }2799  `;2800  shadow.appendChild(style);28012802  const wrap = document.createElement("div");2803  wrap.className = "offer-wrap";2804  shadow.appendChild(wrap);28052806  const offer = document.createElement("div");2807  offer.className = "offer";2808  wrap.appendChild(offer);28092810  const closeBtn = document.createElement("button");2811  closeBtn.className = "offer-close";2812  closeBtn.type = "button";2813  closeBtn.setAttribute("aria-label", "Dismiss");2814  closeBtn.textContent = "✕";2815  offer.appendChild(closeBtn);28162817  const header = document.createElement("div");2818  header.className = "offer-header";2819  const icon = document.createElement("span");2820  icon.innerHTML = peachIconSvg();2821  const domainEl = document.createElement("span");2822  domainEl.className = "offer-domain";2823  domainEl.textContent = domain;2824  header.append(icon, domainEl);2825  offer.appendChild(header);28262827  const title = document.createElement("div");2828  title.className = "offer-title";2829  title.textContent = "This site supports passkeys.";2830  offer.appendChild(title);28312832  const subtitle = document.createElement("div");2833  subtitle.className = "offer-subtitle";2834  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2835  offer.appendChild(subtitle);28362837  const saveBtn = document.createElement("button");2838  saveBtn.className = "offer-btn offer-btn--accent";2839  saveBtn.type = "button";2840  saveBtn.textContent = "Save passkey to Peach";2841  offer.appendChild(saveBtn);28422843  const laterBtn = document.createElement("button");2844  laterBtn.className = "offer-btn offer-btn--ghost";2845  laterBtn.type = "button";2846  laterBtn.textContent = "Not now";2847  offer.appendChild(laterBtn);28482849  function dismiss(decline: boolean) {2850    if (decline) {2851      chrome.runtime.sendMessage({2852        type: "PASSKEY_OFFER_DECLINE",2853        payload: { domain },2854      }).catch(() => {});2855    }2856    wrap.classList.add("is-exiting");2857    setTimeout(() => host.remove(), 130);2858  }28592860  saveBtn.addEventListener("click", () => {2861    chrome.runtime.sendMessage({2862      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2863      payload: {2864        rpId: args.rpId,2865        rpName: args.rpName ?? displayName,2866        userName: args.userName ?? "user",2867        userDisplayName: args.userDisplayName,2868      },2869    }).catch(() => {});2870    dismiss(false);2871  });2872  laterBtn.addEventListener("click", () => dismiss(true));2873  closeBtn.addEventListener("click", () => dismiss(true));28742875  document.body.appendChild(host);2876}28772878/**2879 * State 11 — passkey available indicator. Shown when the user lands on a2880 * domain for which they already have a stored passkey. Tells them where to2881 * find it (the entry already shows in the vault list); the "Sign in with2882 * passkey" button opens the popup so they can use the platform authenticator2883 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2884 * the actual sign-in transparently, so this banner is informational only.2885 */2886export function showPasskeyAvailable(args: {2887  rpId: string;2888  userName: string;2889  fromBrowser?: "chrome" | "firefox";2890  currentBrowser?: "chrome" | "firefox" | "unknown";2891}): void {2892  const domain = location.hostname.replace(/^www\./, "");2893  const crossBrowser =2894    args.fromBrowser &&2895    args.currentBrowser &&2896    args.currentBrowser !== "unknown" &&2897    args.fromBrowser !== args.currentBrowser;28982899  const host = document.createElement("div");2900  host.setAttribute("data-peach-passkey-available", "1");2901  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2902  const shadow = host.attachShadow({ mode: "closed" });29032904  const style = document.createElement("style");2905  style.textContent = `2906    :host { all: initial; }2907    .avail-wrap {2908      position: fixed;2909      top: 16px;2910      right: 16px;2911      width: 320px;2912      pointer-events: auto;2913      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;2914    }2915    @keyframes a-in {2916      from { opacity: 0; transform: translateY(-6px); }2917      to   { opacity: 1; transform: translateY(0); }2918    }2919    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }2920    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }2921    .avail {2922      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2923      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2924      border-radius: 12px;2925      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2926      padding: 14px 14px 12px;2927      font-family: Inter, sans-serif;2928      position: relative;2929    }2930    .avail-close {2931      position: absolute;2932      top: 8px;2933      right: 8px;2934      width: 18px;2935      height: 18px;2936      border: none;2937      background: transparent;2938      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2939      cursor: pointer;2940      font-size: 14px;2941      line-height: 1;2942      padding: 0;2943    }2944    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2945    .avail-header {2946      display: flex;2947      align-items: center;2948      gap: 7px;2949      margin-bottom: 8px;2950      padding-bottom: 8px;2951      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2952    }2953    .avail-domain {2954      font-size: 12px;2955      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2956      font-family: "IBM Plex Mono", monospace;2957    }2958    .avail-label {2959      font-size: 9px;2960      letter-spacing: 0.16em;2961      text-transform: uppercase;2962      color: ${accentHex};2963      margin-bottom: 4px;2964    }2965    .avail-user {2966      font-size: 13px;2967      font-weight: 500;2968      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2969      margin-bottom: 12px;2970      overflow: hidden;2971      text-overflow: ellipsis;2972      white-space: nowrap;2973    }2974    .avail-cross {2975      font-size: 11px;2976      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2977      line-height: 1.45;2978      margin-bottom: 12px;2979      padding: 8px;2980      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};2981      border-radius: 6px;2982    }2983    .avail-btn {2984      display: block;2985      width: 100%;2986      padding: 8px 0;2987      border-radius: 7px;2988      border: none;2989      cursor: pointer;2990      font-size: 12px;2991      font-family: Inter, sans-serif;2992      font-weight: 500;2993      transition: opacity 100ms;2994      margin-bottom: 6px;2995      text-align: center;2996    }2997    .avail-btn:last-child { margin-bottom: 0; }2998    .avail-btn--accent { background: ${accentHex}; color: #fff; }2999    .avail-btn--accent:hover { opacity: 0.88; }3000    .avail-btn--ghost {3001      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3002      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3003    }3004    .avail-btn--ghost:hover { opacity: 0.75; }3005  `;3006  shadow.appendChild(style);30073008  const wrap = document.createElement("div");3009  wrap.className = "avail-wrap";3010  shadow.appendChild(wrap);30113012  const avail = document.createElement("div");3013  avail.className = "avail";3014  wrap.appendChild(avail);30153016  const closeBtn = document.createElement("button");3017  closeBtn.className = "avail-close";3018  closeBtn.type = "button";3019  closeBtn.setAttribute("aria-label", "Dismiss");3020  closeBtn.textContent = "✕";3021  avail.appendChild(closeBtn);30223023  const header = document.createElement("div");3024  header.className = "avail-header";3025  const icon = document.createElement("span");3026  icon.innerHTML = peachIconSvg();3027  const domainEl = document.createElement("span");3028  domainEl.className = "avail-domain";3029  domainEl.textContent = domain;3030  header.append(icon, domainEl);3031  avail.appendChild(header);30323033  const label = document.createElement("div");3034  label.className = "avail-label";3035  label.textContent = "PASSKEY";3036  avail.appendChild(label);30373038  const user = document.createElement("div");3039  user.className = "avail-user";3040  user.textContent = args.userName;3041  avail.appendChild(user);30423043  if (crossBrowser) {3044    const cross = document.createElement("div");3045    cross.className = "avail-cross";3046    cross.textContent =3047      args.fromBrowser === "chrome"3048        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3049        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3050    avail.appendChild(cross);3051  }30523053  const signInBtn = document.createElement("button");3054  signInBtn.className = "avail-btn avail-btn--accent";3055  signInBtn.type = "button";3056  signInBtn.textContent = "Sign in with passkey";3057  avail.appendChild(signInBtn);30583059  const passwordBtn = document.createElement("button");3060  passwordBtn.className = "avail-btn avail-btn--ghost";3061  passwordBtn.type = "button";3062  passwordBtn.textContent = "Use password instead";3063  avail.appendChild(passwordBtn);30643065  function dismiss() {3066    wrap.classList.add("is-exiting");3067    setTimeout(() => host.remove(), 130);3068  }30693070  signInBtn.addEventListener("click", () => {3071    // On Chrome: the user clicking the page's own Sign-in button is what3072    //   triggers webAuthenticationProxy → existing background flow handles it.3073    //   Our button just dismisses since the page itself drives auth.3074    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3075    //   and surface the entry for manual reference (popup view).3076    dismiss();3077    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3078  });3079  passwordBtn.addEventListener("click", dismiss);3080  closeBtn.addEventListener("click", dismiss);30813082  document.body.appendChild(host);3083}30843085/**3086 * State 7 — card silver platter. Single-card focused fill view rendered3087 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3088 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3089 * so card and login flows render identically. Multi-card list view is a3090 * follow-up; today this picks the first card.3091 */3092export function showCardSelector(3093  anchorEl: HTMLInputElement,3094  cards: CardSelectorEntry[],3095  options: CardSelectorOptions3096): () => void {3097  if (cards.length === 0) return () => {};3098  const card = cards[0]!;30993100  const host = document.createElement("div");3101  host.style.cssText = "position: absolute; z-index: 2147483647;";3102  host.style.setProperty("--peach-accent", accentHex);3103  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3104  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3105  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3106  const shadow = host.attachShadow({ mode: "closed" });31073108  const style = shadow.appendChild(document.createElement("style"));3109  style.textContent = SELECTOR_STYLES;31103111  const rect = anchorEl.getBoundingClientRect();3112  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3113  host.style.left = `${rect.left + window.scrollX}px`;3114  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;31153116  const container = shadow.appendChild(document.createElement("div"));3117  container.className = "peach-inline-popup";3118  container.setAttribute("data-theme", popupTheme);31193120  // Domain header — eyebrow communicates the card context, not the site3121  const domHdr = document.createElement("div");3122  domHdr.className = "domain-header";3123  const eyebrow = document.createElement("div");3124  eyebrow.className = "domain-eyebrow";3125  eyebrow.textContent = "Pay with Peach";3126  const domName = document.createElement("div");3127  domName.className = "domain-name";3128  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3129  domHdr.append(eyebrow, domName);3130  container.appendChild(domHdr);31313132  const platter = document.createElement("div");3133  platter.className = "card-platter";31343135  if (card.network && card.network !== "unknown") {3136    const net = document.createElement("div");3137    net.className = "cp-network";3138    net.textContent = card.network;3139    platter.appendChild(net);3140  }31413142  const nick = document.createElement("div");3143  nick.className = "cp-nickname";3144  nick.textContent = card.title;3145  platter.appendChild(nick);31463147  if (card.last4) {3148    const l4 = document.createElement("div");3149    l4.className = "cp-last4";3150    l4.textContent = `•••• ${card.last4}`;3151    platter.appendChild(l4);3152  }31533154  const meta = document.createElement("div");3155  meta.className = "cp-meta";3156  if (card.cardholderName) {3157    const name = document.createElement("span");3158    name.textContent = card.cardholderName;3159    meta.appendChild(name);3160  }3161  if (card.expMonth && card.expYear) {3162    if (card.cardholderName) {3163      const sep = document.createElement("span");3164      sep.className = "cp-meta-sep";3165      sep.textContent = "·";3166      meta.appendChild(sep);3167    }3168    const exp = document.createElement("span");3169    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3170    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3171    meta.appendChild(exp);3172  }3173  if (meta.childElementCount > 0) platter.appendChild(meta);31743175  const fillWrap = document.createElement("div");3176  fillWrap.className = "cp-fill-wrap";3177  const fillBtn = document.createElement("button");3178  fillBtn.className = "sp-fill-btn";3179  fillBtn.type = "button";3180  fillBtn.textContent = "Fill card details";3181  fillBtn.addEventListener("click", async () => {3182    if (fillBtn.disabled) return;3183    fillBtn.disabled = true;3184    fillBtn.classList.add("filled");3185    fillBtn.innerHTML = checkSvgStr();3186    const resp = await chrome.runtime.sendMessage({3187      type: "GET_ENTRY_FOR_FILL",3188      payload: { id: card.id },3189    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3190    if (resp?.ok && resp.data) options.onFill(resp.data);3191    setTimeout(() => dismiss(), 400);3192  });3193  fillWrap.appendChild(fillBtn);3194  platter.appendChild(fillWrap);31953196  // Secondary actions — copy number, copy CVC, dismiss3197  const actions = document.createElement("div");3198  actions.className = "sp-actions";31993200  function flashBtn(b: HTMLButtonElement) {3201    b.classList.add("flashed");3202    setTimeout(() => b.classList.remove("flashed"), 700);3203  }32043205  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3206    const resp = await chrome.runtime.sendMessage({3207      type: "GET_ENTRY_FOR_FILL",3208      payload: { id: card.id },3209    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3210    return resp?.ok && resp.data ? resp.data : null;3211  }32123213  const copyNum = document.createElement("button");3214  copyNum.className = "sp-action-btn";3215  copyNum.type = "button";3216  copyNum.title = "Copy card number";3217  copyNum.textContent = "Copy number";3218  copyNum.addEventListener("click", async (e) => {3219    e.stopPropagation();3220    const full = await fetchFullCard();3221    if (!full?.cardNumber) return;3222    let alreadyWritten = false;3223    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}3224    await chrome.runtime.sendMessage({3225      type: "COPY",3226      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3227    }).catch(() => {});3228    flashBtn(copyNum);3229  });3230  actions.appendChild(copyNum);32313232  const copyCvc = document.createElement("button");3233  copyCvc.className = "sp-action-btn";3234  copyCvc.type = "button";3235  copyCvc.title = "Copy CVC";3236  copyCvc.textContent = "Copy CVC";3237  copyCvc.addEventListener("click", async (e) => {3238    e.stopPropagation();3239    const full = await fetchFullCard();3240    if (!full?.cvc) return;3241    let alreadyWritten = false;3242    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}3243    await chrome.runtime.sendMessage({3244      type: "COPY",3245      payload: { text: full.cvc, label: "CVC", alreadyWritten },3246    }).catch(() => {});3247    flashBtn(copyCvc);3248  });3249  actions.appendChild(copyCvc);32503251  const closeBtn = document.createElement("button");3252  closeBtn.className = "sp-action-btn";3253  closeBtn.type = "button";3254  closeBtn.title = "Dismiss";3255  closeBtn.textContent = "✕";3256  closeBtn.addEventListener("click", (e) => {3257    e.stopPropagation();3258    dismiss(true);3259  });3260  actions.appendChild(closeBtn);32613262  platter.appendChild(actions);3263  container.appendChild(platter);32643265  document.body.appendChild(host);3266  function updatePosition() {3267    const r = anchorEl.getBoundingClientRect();3268    host.style.top = `${r.bottom + window.scrollY + 5}px`;3269    host.style.left = `${r.left + window.scrollX}px`;3270  }3271  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);32723273  function onKeyDown(e: KeyboardEvent) {3274    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3275  }3276  document.addEventListener("keydown", onKeyDown);32773278  let exitScheduled = false;3279  function dismiss(userAction = false) {3280    if (exitScheduled) return;3281    exitScheduled = true;3282    stopObserving();3283    document.removeEventListener("click", outsideClick, { capture: true });3284    document.removeEventListener("keydown", onKeyDown);3285    if (userAction) options.onDismiss?.();3286    container.classList.add("is-exiting");3287    setTimeout(() => host.remove(), 130);3288  }32893290  function outsideClick(ev: MouseEvent) {3291    const path = ev.composedPath();3292    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3293  }3294  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);32953296  return dismiss;3297}