inject.ts

130.4 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, idRes] = await Promise.all([2140      chrome.runtime.sendMessage({2141        type: "GET_ENTRY_FOR_FILL",2142        payload: { id: summary.id },2143      }).catch(() => null),2144      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2145    ]);2146    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2147    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];21482149    if (!entryRes || !entryRes.ok || !entryRes.data) {2150      loading.textContent = "couldn't load this entry. try again from the popup.";2151      return;2152    }2153    body.innerHTML = "";21542155    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2156      const group = document.createElement("div");2157      group.className = "f-group";2158      const lbl = document.createElement("div");2159      lbl.className = "f-label";2160      lbl.textContent = label;2161      const input = document.createElement("input");2162      input.className = "f-input";2163      input.type = type;2164      input.value = value;2165      input.autocomplete = "off";2166      group.append(lbl, input);2167      body.appendChild(group);2168      return { g: group, inp: input };2169    }21702171    const titleInput = field("title", entryRes.data.title ?? "").inp;2172    const urlInput = field("url", entryRes.data.url ?? "").inp;2173    urlInput.classList.add("url-f");2174    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2175    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2176    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities);2177    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2178    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities);21792180    // Password row with reveal toggle2181    const pwGroup = document.createElement("div");2182    pwGroup.className = "f-group";2183    const pwLbl = document.createElement("div");2184    pwLbl.className = "f-label";2185    pwLbl.textContent = "password";2186    const pwRow = document.createElement("div");2187    pwRow.className = "f-row";2188    const pwInput = document.createElement("input");2189    pwInput.className = "f-input";2190    pwInput.type = "password";2191    pwInput.value = entryRes.data.password ?? "";2192    pwInput.autocomplete = "new-password";2193    const revealBtn = document.createElement("button");2194    revealBtn.className = "gen-btn";2195    revealBtn.type = "button";2196    revealBtn.textContent = "show";2197    revealBtn.addEventListener("click", () => {2198      const reveal = pwInput.type === "password";2199      pwInput.type = reveal ? "text" : "password";2200      revealBtn.textContent = reveal ? "hide" : "show";2201    });2202    pwRow.append(pwInput, revealBtn);2203    pwGroup.append(pwLbl, pwRow);2204    body.appendChild(pwGroup);22052206    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;22072208    // Notes2209    const notesGroup = document.createElement("div");2210    notesGroup.className = "f-group";2211    const notesLbl = document.createElement("div");2212    notesLbl.className = "f-label";2213    notesLbl.textContent = "notes";2214    const notesInput = document.createElement("textarea");2215    notesInput.className = "f-input";2216    notesInput.rows = 3;2217    notesInput.value = entryRes.data.notes ?? "";2218    notesInput.style.fontFamily = "Inter, sans-serif";2219    notesInput.style.resize = "vertical";2220    notesGroup.append(notesLbl, notesInput);2221    body.appendChild(notesGroup);22222223    // Save / Cancel row2224    const actionsRow = document.createElement("div");2225    actionsRow.className = "f-row";2226    const saveBtn = document.createElement("button");2227    saveBtn.className = "save-btn";2228    saveBtn.type = "button";2229    saveBtn.textContent = "Save changes";2230    saveBtn.style.flex = "1";2231    const cancelBtn = document.createElement("button");2232    cancelBtn.className = "gen-btn";2233    cancelBtn.type = "button";2234    cancelBtn.textContent = "cancel";2235    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2236    actionsRow.append(saveBtn, cancelBtn);2237    body.appendChild(actionsRow);22382239    saveBtn.addEventListener("click", async () => {2240      saveBtn.disabled = true;2241      const originalLabel = saveBtn.textContent;2242      saveBtn.textContent = "Saving…";2243      const patch: Record<string, unknown> = {2244        title: titleInput.value.trim(),2245        url: urlInput.value.trim(),2246        username: usernameInput.value.trim(),2247        email: emailInput.value.trim() || undefined,2248        password: pwInput.value,2249        totp: totpInput.value.trim(),2250        notes: notesInput.value,2251      };2252      const updateRes = (await chrome.runtime.sendMessage({2253        type: "UPDATE_ENTRY",2254        payload: { id: summary.id, patch },2255      }).catch(() => null)) as { ok: boolean; error?: string } | null;2256      if (!updateRes?.ok) {2257        saveBtn.disabled = false;2258        saveBtn.textContent = originalLabel;2259        const err = document.createElement("div");2260        err.className = "empty-hint";2261        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2262        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2263        body.appendChild(err);2264        setTimeout(() => err.remove(), 3000);2265        return;2266      }2267      // Refresh the platter with updated summary fields2268      const refreshed: SelectorEntry = {2269        id: summary.id,2270        title: patch.title as string,2271        username: patch.username as string,2272        email: patch.email as string | undefined,2273        url: patch.url as string,2274        hasTotp: Boolean(patch.totp),2275        hasPasskey: summary.hasPasskey,2276      };2277      renderSilverPlatter(refreshed);2278    });22792280    queueMicrotask(() => titleInput.focus());2281  }22822283  function renderLocked() {2284    container.innerHTML = "";22852286    // Domain header (same as list view)2287    const domHdr = document.createElement("div");2288    domHdr.className = "domain-header";2289    const eyebrow = document.createElement("div");2290    eyebrow.className = "domain-eyebrow";2291    eyebrow.textContent = "vault locked";2292    const domName = document.createElement("div");2293    domName.className = "domain-name";2294    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2295    domHdr.append(eyebrow, domName);2296    container.appendChild(domHdr);22972298    const wrap = document.createElement("div");2299    wrap.className = "locked-wrap";23002301    // Icon + label row2302    const head = document.createElement("div"); head.className = "locked-head";2303    const icon = document.createElement("div"); icon.className = "locked-icon";2304    icon.innerHTML = keySvgStr();2305    const title = document.createElement("div"); title.className = "locked-title";2306    title.textContent = "unlock to autofill";2307    head.append(icon, title);23082309    // Password input2310    const pwInp = document.createElement("input");2311    pwInp.className = "locked-input";2312    pwInp.type = "password";2313    pwInp.placeholder = "master password";2314    pwInp.setAttribute("autocomplete", "current-password");23152316    // Error line (hidden initially)2317    const errEl = document.createElement("div");2318    errEl.className = "locked-error";2319    errEl.style.display = "none";23202321    // Unlock button2322    const unlockBtn = document.createElement("button");2323    unlockBtn.className = "locked-btn";2324    unlockBtn.type = "button";2325    unlockBtn.textContent = "unlock";23262327    async function tryUnlock() {2328      const pw = pwInp.value.trim();2329      if (!pw) { pwInp.focus(); return; }2330      unlockBtn.disabled = true;2331      unlockBtn.textContent = "unlocking…";2332      errEl.style.display = "none";2333      try {2334        const res = await chrome.runtime.sendMessage({2335          type: "UNLOCK",2336          payload: { password: pw },2337        });2338        if ((res as { ok?: boolean }).ok) {2339          dismiss();2340          options.onUnlocked?.();2341        } else {2342          errEl.textContent = "incorrect password";2343          errEl.style.display = "block";2344          pwInp.value = "";2345          pwInp.focus();2346          unlockBtn.disabled = false;2347          unlockBtn.textContent = "unlock";2348        }2349      } catch {2350        errEl.textContent = "could not reach Peach";2351        errEl.style.display = "block";2352        unlockBtn.disabled = false;2353        unlockBtn.textContent = "unlock";2354      }2355    }23562357    pwInp.addEventListener("keydown", (e) => {2358      e.stopPropagation();2359      if (e.key === "Enter") void tryUnlock();2360    });2361    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2362    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2363    unlockBtn.addEventListener("click", () => void tryUnlock());23642365    wrap.append(head, pwInp, errEl, unlockBtn);2366    container.appendChild(wrap);23672368    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2369    // the page reclaims focus from our Shadow DOM input before the user can2370    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2371    // Instead: intercept keystrokes at the document capture phase — this runs2372    // before any page handler regardless of which element technically has2373    // OS focus — and route them into our input.2374    const captureKeydown = (e: KeyboardEvent) => {2375      if (!host.isConnected) {2376        document.removeEventListener("keydown", captureKeydown, true);2377        return;2378      }2379      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2380      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2381      // Intercept before page handlers and give our input focus.2382      e.stopImmediatePropagation();2383      if (e.key === "Escape") { dismiss(true); return; }2384      if (e.key === "Enter") { void tryUnlock(); return; }2385      // For all other printable/editing keys, ensure our input has focus so2386      // the browser delivers the keystroke there naturally.2387      if (document.activeElement !== host) {2388        pwInp.focus({ preventScroll: true });2389      }2390    };2391    captureKeydownRef = captureKeydown;2392    document.addEventListener("keydown", captureKeydown, true);23932394    // Best-effort focus on open — may be overridden by page focus trap,2395    // but the capture listener above handles typing regardless.2396    pwInp.focus({ preventScroll: true });2397    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2398  }23992400  function handleKeyDown(e: KeyboardEvent) {2401    if (options.locked) {2402      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2403      return;2404    }2405    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2406      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2407      return;2408    }2409    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2410    const count = allEntryEls.length;2411    if (document.activeElement === searchInput) {2412      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2413      if (count === 0) return;2414      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2415    }2416    if (count === 0) return;2417    switch (e.key) {2418      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2419      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2420      case "Enter": {2421        if (focusedIndex >= 0) {2422          const el = allEntryEls[focusedIndex] as HTMLElement;2423          const id = el.dataset.id;2424          if (id) { onSelect(id); dismiss(); }2425          else if (el.classList.contains("is-new") || !id) {2426            // "New entry" row (last item, no data-id)2427            showCreateForm();2428          }2429        }2430        break;2431      }2432      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2433    }2434  }24352436  document.addEventListener("keydown", handleKeyDown);24372438  document.body.appendChild(host);24392440  function updatePosition() {2441    const r = anchorEl.getBoundingClientRect();2442    host.style.top = `${r.bottom + window.scrollY + 5}px`;2443    host.style.left = `${r.left + window.scrollX}px`;2444  }2445  // These bindings are referenced from renderLocked()/dismiss() — they MUST2446  // be initialized before renderLocked() runs, or the synchronous assignment2447  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2448  // and throws ReferenceError. The throw lands after the popup is rendered2449  // but before showAutofillSelector returns its dismiss handle, leaving an2450  // orphan host in the DOM (which is what caused the locked-popup stacking2451  // and missing autofocus on every click).2452  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2453  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);24542455  if (options.locked) {2456    renderLocked();2457  } else if (options.isSignup && options.savedIdentities) {2458    // State 10: identity helper — signup form detected, show derived2459    // identity list (emails then usernames) instead of vault entry list.2460    renderIdentityHelper();2461  } else if (entries.length === 1 && !options.isSignup) {2462    // Silver platter (State 1): single domain match → focused fill view.2463    // Multi-match goes through renderList instead.2464    renderSilverPlatter(entries[0]!);2465  } else {2466    renderList();2467  }24682469  let exitScheduled = false;2470  function dismiss(userAction = false) {2471    // Idempotent: dismiss() can be called from multiple paths (Escape,2472    // outside click, entry select, fill success, host page nav). The exit2473    // animation must only play once and host.remove() must run exactly once.2474    if (exitScheduled) return;2475    exitScheduled = true;2476    // Detach listeners synchronously so nothing can re-trigger during the2477    // 130ms exit window (a focusin firing here would race against the2478    // dismiss-lock work in Pass 2).2479    stopObserving();2480    document.removeEventListener("click", outsideClick, { capture: true });2481    document.removeEventListener("keydown", handleKeyDown);2482    if (captureKeydownRef) {2483      document.removeEventListener("keydown", captureKeydownRef, true);2484      captureKeydownRef = null;2485    }2486    for (const cleanup of cleanupHooks) {2487      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2488    }2489    if (userAction) options.onDismiss?.();2490    container.classList.add("is-exiting");2491    setTimeout(() => host.remove(), 130);2492  }24932494  function outsideClick(ev: MouseEvent) {2495    const path = ev.composedPath();2496    // Never dismiss when clicking the anchor field itself — that click is2497    // what triggered the selector to open, and the user may click the field2498    // again to re-focus it without intending to close the selector.2499    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2500  }2501  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2502  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);25032504  return dismiss;2505}25062507export interface CardSelectorEntry {2508  id: string;2509  title: string;2510  cardholderName?: string;2511  last4?: string;2512  expMonth?: string;2513  expYear?: string;2514  network?: import("../shared/types").CardNetwork;2515}25162517interface CardSelectorOptions {2518  domain?: string;2519  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2520  onFill: (entry: import("../shared/types").VaultEntry) => void;2521  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2522  onDismiss?: () => void;2523}25242525/**2526 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2527 * passkey create or get. Renders as a fixed-position floating popup (no2528 * field anchor needed — passkeys don't require a focused input). Uses the2529 * same theme tokens and entrance animation as all other inline popup states.2530 */2531export function showPasskeyProGate(): void {2532  const domain = location.hostname.replace(/^www\./, "");25332534  const host = document.createElement("div");2535  host.setAttribute("data-peach-passkey-gate", "1");2536  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2537  const shadow = host.attachShadow({ mode: "closed" });25382539  const style = document.createElement("style");2540  style.textContent = `2541    :host { all: initial; }2542    .gate-wrap {2543      position: fixed;2544      top: 50%;2545      left: 50%;2546      transform: translate(-50%, -50%);2547      width: 280px;2548      pointer-events: auto;2549      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2550    }2551    @keyframes g-in {2552      from { opacity:0; transform: translate(-50%,-52%); }2553      to   { opacity:1; transform: translate(-50%,-50%); }2554    }2555    .gate-wrap.is-exiting {2556      animation: g-out 130ms ease-in forwards;2557    }2558    @keyframes g-out {2559      to { opacity:0; transform: translate(-50%,-52%); }2560    }2561    .gate {2562      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2563      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2564      border-radius: 12px;2565      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2566      padding: 16px;2567      font-family: Inter, sans-serif;2568    }2569    .gate-header {2570      display: flex;2571      align-items: center;2572      gap: 7px;2573      margin-bottom: 12px;2574      padding-bottom: 10px;2575      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2576    }2577    .gate-domain {2578      font-size: 12px;2579      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2580      font-family: "IBM Plex Mono", monospace;2581      overflow: hidden;2582      text-overflow: ellipsis;2583      white-space: nowrap;2584    }2585    .gate-title {2586      font-size: 14px;2587      font-weight: 500;2588      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2589      margin-bottom: 6px;2590    }2591    .gate-subtitle {2592      font-size: 12px;2593      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2594      line-height: 1.5;2595      margin-bottom: 14px;2596    }2597    .gate-btn {2598      display: block;2599      width: 100%;2600      padding: 9px 0;2601      border-radius: 8px;2602      border: none;2603      cursor: pointer;2604      font-size: 13px;2605      font-family: Inter, sans-serif;2606      font-weight: 500;2607      transition: opacity 100ms;2608      margin-bottom: 7px;2609      text-align: center;2610    }2611    .gate-btn:last-child { margin-bottom: 0; }2612    .gate-btn--accent {2613      background: ${accentHex};2614      color: #fff;2615    }2616    .gate-btn--accent:hover { opacity: 0.88; }2617    .gate-btn--ghost {2618      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2619      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2620    }2621    .gate-btn--ghost:hover { opacity: 0.75; }2622    .backdrop {2623      position: fixed;2624      inset: 0;2625      pointer-events: auto;2626    }2627  `;2628  shadow.appendChild(style);26292630  const backdrop = document.createElement("div");2631  backdrop.className = "backdrop";2632  shadow.appendChild(backdrop);26332634  const wrap = document.createElement("div");2635  wrap.className = "gate-wrap";2636  shadow.appendChild(wrap);26372638  const gate = document.createElement("div");2639  gate.className = "gate";2640  wrap.appendChild(gate);26412642  // Header: peach icon + domain2643  const header = document.createElement("div");2644  header.className = "gate-header";2645  const icon = document.createElement("span");2646  icon.innerHTML = peachIconSvg();2647  const domainEl = document.createElement("span");2648  domainEl.className = "gate-domain";2649  domainEl.textContent = domain;2650  header.append(icon, domainEl);2651  gate.appendChild(header);26522653  const title = document.createElement("div");2654  title.className = "gate-title";2655  title.textContent = "Passkeys are part of Peach Pro.";2656  gate.appendChild(title);26572658  const subtitle = document.createElement("div");2659  subtitle.className = "gate-subtitle";2660  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2661  gate.appendChild(subtitle);26622663  const upgradeBtn = document.createElement("button");2664  upgradeBtn.className = "gate-btn gate-btn--accent";2665  upgradeBtn.type = "button";2666  upgradeBtn.textContent = "Upgrade to Pro";2667  gate.appendChild(upgradeBtn);26682669  const laterBtn = document.createElement("button");2670  laterBtn.className = "gate-btn gate-btn--ghost";2671  laterBtn.type = "button";2672  laterBtn.textContent = "Not right now";2673  gate.appendChild(laterBtn);26742675  function dismiss() {2676    wrap.classList.add("is-exiting");2677    setTimeout(() => host.remove(), 130);2678  }26792680  upgradeBtn.addEventListener("click", () => {2681    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2682    dismiss();2683  });2684  laterBtn.addEventListener("click", dismiss);2685  backdrop.addEventListener("click", dismiss);26862687  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2688    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2689  });26902691  document.body.appendChild(host);2692}26932694/**2695 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2696 * detector sees the page invoke navigator.credentials.create(); content/index.ts2697 * checks vault + decline state then calls this. "Save passkey to Peach"2698 * initiates the popup-context credential flow; "Not now" records a 30-day2699 * decline for the domain so we don't re-show on every page reload.2700 */2701export function showPasskeyRegistrationOffer(args: {2702  rpId: string;2703  rpName?: string;2704  userName?: string;2705  userDisplayName?: string;2706}): void {2707  const domain = location.hostname.replace(/^www\./, "");2708  const displayName = args.rpName || domain;27092710  const host = document.createElement("div");2711  host.setAttribute("data-peach-passkey-offer", "1");2712  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2713  const shadow = host.attachShadow({ mode: "closed" });27142715  const style = document.createElement("style");2716  style.textContent = `2717    :host { all: initial; }2718    .offer-wrap {2719      position: fixed;2720      top: 16px;2721      right: 16px;2722      width: 320px;2723      pointer-events: auto;2724      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2725    }2726    @keyframes o-in {2727      from { opacity: 0; transform: translateY(-6px); }2728      to   { opacity: 1; transform: translateY(0); }2729    }2730    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2731    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2732    .offer {2733      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2734      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2735      border-radius: 12px;2736      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2737      padding: 14px 14px 12px;2738      font-family: Inter, sans-serif;2739      position: relative;2740    }2741    .offer-close {2742      position: absolute;2743      top: 8px;2744      right: 8px;2745      width: 18px;2746      height: 18px;2747      border: none;2748      background: transparent;2749      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2750      cursor: pointer;2751      font-size: 14px;2752      line-height: 1;2753      padding: 0;2754    }2755    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2756    .offer-header {2757      display: flex;2758      align-items: center;2759      gap: 7px;2760      margin-bottom: 8px;2761      padding-bottom: 8px;2762      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2763    }2764    .offer-domain {2765      font-size: 12px;2766      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2767      font-family: "IBM Plex Mono", monospace;2768      overflow: hidden;2769      text-overflow: ellipsis;2770      white-space: nowrap;2771    }2772    .offer-title {2773      font-size: 13px;2774      font-weight: 500;2775      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2776      margin-bottom: 4px;2777    }2778    .offer-subtitle {2779      font-size: 11px;2780      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2781      line-height: 1.45;2782      margin-bottom: 12px;2783    }2784    .offer-btn {2785      display: block;2786      width: 100%;2787      padding: 8px 0;2788      border-radius: 7px;2789      border: none;2790      cursor: pointer;2791      font-size: 12px;2792      font-family: Inter, sans-serif;2793      font-weight: 500;2794      transition: opacity 100ms;2795      margin-bottom: 6px;2796      text-align: center;2797    }2798    .offer-btn:last-child { margin-bottom: 0; }2799    .offer-btn--accent { background: ${accentHex}; color: #fff; }2800    .offer-btn--accent:hover { opacity: 0.88; }2801    .offer-btn--ghost {2802      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2803      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2804    }2805    .offer-btn--ghost:hover { opacity: 0.75; }2806  `;2807  shadow.appendChild(style);28082809  const wrap = document.createElement("div");2810  wrap.className = "offer-wrap";2811  shadow.appendChild(wrap);28122813  const offer = document.createElement("div");2814  offer.className = "offer";2815  wrap.appendChild(offer);28162817  const closeBtn = document.createElement("button");2818  closeBtn.className = "offer-close";2819  closeBtn.type = "button";2820  closeBtn.setAttribute("aria-label", "Dismiss");2821  closeBtn.textContent = "✕";2822  offer.appendChild(closeBtn);28232824  const header = document.createElement("div");2825  header.className = "offer-header";2826  const icon = document.createElement("span");2827  icon.innerHTML = peachIconSvg();2828  const domainEl = document.createElement("span");2829  domainEl.className = "offer-domain";2830  domainEl.textContent = domain;2831  header.append(icon, domainEl);2832  offer.appendChild(header);28332834  const title = document.createElement("div");2835  title.className = "offer-title";2836  title.textContent = "This site supports passkeys.";2837  offer.appendChild(title);28382839  const subtitle = document.createElement("div");2840  subtitle.className = "offer-subtitle";2841  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2842  offer.appendChild(subtitle);28432844  const saveBtn = document.createElement("button");2845  saveBtn.className = "offer-btn offer-btn--accent";2846  saveBtn.type = "button";2847  saveBtn.textContent = "Save passkey to Peach";2848  offer.appendChild(saveBtn);28492850  const laterBtn = document.createElement("button");2851  laterBtn.className = "offer-btn offer-btn--ghost";2852  laterBtn.type = "button";2853  laterBtn.textContent = "Not now";2854  offer.appendChild(laterBtn);28552856  function dismiss(decline: boolean) {2857    if (decline) {2858      chrome.runtime.sendMessage({2859        type: "PASSKEY_OFFER_DECLINE",2860        payload: { domain },2861      }).catch(() => {});2862    }2863    wrap.classList.add("is-exiting");2864    setTimeout(() => host.remove(), 130);2865  }28662867  saveBtn.addEventListener("click", () => {2868    chrome.runtime.sendMessage({2869      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2870      payload: {2871        rpId: args.rpId,2872        rpName: args.rpName ?? displayName,2873        userName: args.userName ?? "user",2874        userDisplayName: args.userDisplayName,2875      },2876    }).catch(() => {});2877    dismiss(false);2878  });2879  laterBtn.addEventListener("click", () => dismiss(true));2880  closeBtn.addEventListener("click", () => dismiss(true));28812882  document.body.appendChild(host);2883}28842885/**2886 * State 11 — passkey available indicator. Shown when the user lands on a2887 * domain for which they already have a stored passkey. Tells them where to2888 * find it (the entry already shows in the vault list); the "Sign in with2889 * passkey" button opens the popup so they can use the platform authenticator2890 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2891 * the actual sign-in transparently, so this banner is informational only.2892 */2893export function showPasskeyAvailable(args: {2894  rpId: string;2895  userName: string;2896  fromBrowser?: "chrome" | "firefox";2897  currentBrowser?: "chrome" | "firefox" | "unknown";2898}): void {2899  const domain = location.hostname.replace(/^www\./, "");2900  const crossBrowser =2901    args.fromBrowser &&2902    args.currentBrowser &&2903    args.currentBrowser !== "unknown" &&2904    args.fromBrowser !== args.currentBrowser;29052906  const host = document.createElement("div");2907  host.setAttribute("data-peach-passkey-available", "1");2908  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2909  const shadow = host.attachShadow({ mode: "closed" });29102911  const style = document.createElement("style");2912  style.textContent = `2913    :host { all: initial; }2914    .avail-wrap {2915      position: fixed;2916      top: 16px;2917      right: 16px;2918      width: 320px;2919      pointer-events: auto;2920      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;2921    }2922    @keyframes a-in {2923      from { opacity: 0; transform: translateY(-6px); }2924      to   { opacity: 1; transform: translateY(0); }2925    }2926    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }2927    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }2928    .avail {2929      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2930      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2931      border-radius: 12px;2932      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2933      padding: 14px 14px 12px;2934      font-family: Inter, sans-serif;2935      position: relative;2936    }2937    .avail-close {2938      position: absolute;2939      top: 8px;2940      right: 8px;2941      width: 18px;2942      height: 18px;2943      border: none;2944      background: transparent;2945      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2946      cursor: pointer;2947      font-size: 14px;2948      line-height: 1;2949      padding: 0;2950    }2951    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2952    .avail-header {2953      display: flex;2954      align-items: center;2955      gap: 7px;2956      margin-bottom: 8px;2957      padding-bottom: 8px;2958      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2959    }2960    .avail-domain {2961      font-size: 12px;2962      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2963      font-family: "IBM Plex Mono", monospace;2964    }2965    .avail-label {2966      font-size: 9px;2967      letter-spacing: 0.16em;2968      text-transform: uppercase;2969      color: ${accentHex};2970      margin-bottom: 4px;2971    }2972    .avail-user {2973      font-size: 13px;2974      font-weight: 500;2975      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2976      margin-bottom: 12px;2977      overflow: hidden;2978      text-overflow: ellipsis;2979      white-space: nowrap;2980    }2981    .avail-cross {2982      font-size: 11px;2983      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2984      line-height: 1.45;2985      margin-bottom: 12px;2986      padding: 8px;2987      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};2988      border-radius: 6px;2989    }2990    .avail-btn {2991      display: block;2992      width: 100%;2993      padding: 8px 0;2994      border-radius: 7px;2995      border: none;2996      cursor: pointer;2997      font-size: 12px;2998      font-family: Inter, sans-serif;2999      font-weight: 500;3000      transition: opacity 100ms;3001      margin-bottom: 6px;3002      text-align: center;3003    }3004    .avail-btn:last-child { margin-bottom: 0; }3005    .avail-btn--accent { background: ${accentHex}; color: #fff; }3006    .avail-btn--accent:hover { opacity: 0.88; }3007    .avail-btn--ghost {3008      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3009      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3010    }3011    .avail-btn--ghost:hover { opacity: 0.75; }3012  `;3013  shadow.appendChild(style);30143015  const wrap = document.createElement("div");3016  wrap.className = "avail-wrap";3017  shadow.appendChild(wrap);30183019  const avail = document.createElement("div");3020  avail.className = "avail";3021  wrap.appendChild(avail);30223023  const closeBtn = document.createElement("button");3024  closeBtn.className = "avail-close";3025  closeBtn.type = "button";3026  closeBtn.setAttribute("aria-label", "Dismiss");3027  closeBtn.textContent = "✕";3028  avail.appendChild(closeBtn);30293030  const header = document.createElement("div");3031  header.className = "avail-header";3032  const icon = document.createElement("span");3033  icon.innerHTML = peachIconSvg();3034  const domainEl = document.createElement("span");3035  domainEl.className = "avail-domain";3036  domainEl.textContent = domain;3037  header.append(icon, domainEl);3038  avail.appendChild(header);30393040  const label = document.createElement("div");3041  label.className = "avail-label";3042  label.textContent = "PASSKEY";3043  avail.appendChild(label);30443045  const user = document.createElement("div");3046  user.className = "avail-user";3047  user.textContent = args.userName;3048  avail.appendChild(user);30493050  if (crossBrowser) {3051    const cross = document.createElement("div");3052    cross.className = "avail-cross";3053    cross.textContent =3054      args.fromBrowser === "chrome"3055        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3056        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3057    avail.appendChild(cross);3058  }30593060  const signInBtn = document.createElement("button");3061  signInBtn.className = "avail-btn avail-btn--accent";3062  signInBtn.type = "button";3063  signInBtn.textContent = "Sign in with passkey";3064  avail.appendChild(signInBtn);30653066  const passwordBtn = document.createElement("button");3067  passwordBtn.className = "avail-btn avail-btn--ghost";3068  passwordBtn.type = "button";3069  passwordBtn.textContent = "Use password instead";3070  avail.appendChild(passwordBtn);30713072  function dismiss() {3073    wrap.classList.add("is-exiting");3074    setTimeout(() => host.remove(), 130);3075  }30763077  signInBtn.addEventListener("click", () => {3078    // On Chrome: the user clicking the page's own Sign-in button is what3079    //   triggers webAuthenticationProxy → existing background flow handles it.3080    //   Our button just dismisses since the page itself drives auth.3081    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3082    //   and surface the entry for manual reference (popup view).3083    dismiss();3084    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3085  });3086  passwordBtn.addEventListener("click", dismiss);3087  closeBtn.addEventListener("click", dismiss);30883089  document.body.appendChild(host);3090}30913092/**3093 * State 7 — card silver platter. Single-card focused fill view rendered3094 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3095 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3096 * so card and login flows render identically. Multi-card list view is a3097 * follow-up; today this picks the first card.3098 */3099export function showCardSelector(3100  anchorEl: HTMLInputElement,3101  cards: CardSelectorEntry[],3102  options: CardSelectorOptions3103): () => void {3104  if (cards.length === 0) return () => {};3105  const card = cards[0]!;31063107  const host = document.createElement("div");3108  host.style.cssText = "position: absolute; z-index: 2147483647;";3109  host.style.setProperty("--peach-accent", accentHex);3110  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3111  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3112  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3113  const shadow = host.attachShadow({ mode: "closed" });31143115  const style = shadow.appendChild(document.createElement("style"));3116  style.textContent = SELECTOR_STYLES;31173118  const rect = anchorEl.getBoundingClientRect();3119  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3120  host.style.left = `${rect.left + window.scrollX}px`;3121  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;31223123  const container = shadow.appendChild(document.createElement("div"));3124  container.className = "peach-inline-popup";3125  container.setAttribute("data-theme", popupTheme);31263127  // Domain header — eyebrow communicates the card context, not the site3128  const domHdr = document.createElement("div");3129  domHdr.className = "domain-header";3130  const eyebrow = document.createElement("div");3131  eyebrow.className = "domain-eyebrow";3132  eyebrow.textContent = "Pay with Peach";3133  const domName = document.createElement("div");3134  domName.className = "domain-name";3135  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3136  domHdr.append(eyebrow, domName);3137  container.appendChild(domHdr);31383139  const platter = document.createElement("div");3140  platter.className = "card-platter";31413142  if (card.network && card.network !== "unknown") {3143    const net = document.createElement("div");3144    net.className = "cp-network";3145    net.textContent = card.network;3146    platter.appendChild(net);3147  }31483149  const nick = document.createElement("div");3150  nick.className = "cp-nickname";3151  nick.textContent = card.title;3152  platter.appendChild(nick);31533154  if (card.last4) {3155    const l4 = document.createElement("div");3156    l4.className = "cp-last4";3157    l4.textContent = `•••• ${card.last4}`;3158    platter.appendChild(l4);3159  }31603161  const meta = document.createElement("div");3162  meta.className = "cp-meta";3163  if (card.cardholderName) {3164    const name = document.createElement("span");3165    name.textContent = card.cardholderName;3166    meta.appendChild(name);3167  }3168  if (card.expMonth && card.expYear) {3169    if (card.cardholderName) {3170      const sep = document.createElement("span");3171      sep.className = "cp-meta-sep";3172      sep.textContent = "·";3173      meta.appendChild(sep);3174    }3175    const exp = document.createElement("span");3176    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3177    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3178    meta.appendChild(exp);3179  }3180  if (meta.childElementCount > 0) platter.appendChild(meta);31813182  const fillWrap = document.createElement("div");3183  fillWrap.className = "cp-fill-wrap";3184  const fillBtn = document.createElement("button");3185  fillBtn.className = "sp-fill-btn";3186  fillBtn.type = "button";3187  fillBtn.textContent = "Fill card details";3188  fillBtn.addEventListener("click", async () => {3189    if (fillBtn.disabled) return;3190    fillBtn.disabled = true;3191    fillBtn.classList.add("filled");3192    fillBtn.innerHTML = checkSvgStr();3193    const resp = await chrome.runtime.sendMessage({3194      type: "GET_ENTRY_FOR_FILL",3195      payload: { id: card.id },3196    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3197    if (resp?.ok && resp.data) options.onFill(resp.data);3198    setTimeout(() => dismiss(), 400);3199  });3200  fillWrap.appendChild(fillBtn);3201  platter.appendChild(fillWrap);32023203  // Secondary actions — copy number, copy CVC, dismiss3204  const actions = document.createElement("div");3205  actions.className = "sp-actions";32063207  function flashBtn(b: HTMLButtonElement) {3208    b.classList.add("flashed");3209    setTimeout(() => b.classList.remove("flashed"), 700);3210  }32113212  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3213    const resp = await chrome.runtime.sendMessage({3214      type: "GET_ENTRY_FOR_FILL",3215      payload: { id: card.id },3216    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3217    return resp?.ok && resp.data ? resp.data : null;3218  }32193220  const copyNum = document.createElement("button");3221  copyNum.className = "sp-action-btn";3222  copyNum.type = "button";3223  copyNum.title = "Copy card number";3224  copyNum.textContent = "Copy number";3225  copyNum.addEventListener("click", async (e) => {3226    e.stopPropagation();3227    const full = await fetchFullCard();3228    if (!full?.cardNumber) return;3229    let alreadyWritten = false;3230    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}3231    await chrome.runtime.sendMessage({3232      type: "COPY",3233      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3234    }).catch(() => {});3235    flashBtn(copyNum);3236  });3237  actions.appendChild(copyNum);32383239  const copyCvc = document.createElement("button");3240  copyCvc.className = "sp-action-btn";3241  copyCvc.type = "button";3242  copyCvc.title = "Copy CVC";3243  copyCvc.textContent = "Copy CVC";3244  copyCvc.addEventListener("click", async (e) => {3245    e.stopPropagation();3246    const full = await fetchFullCard();3247    if (!full?.cvc) return;3248    let alreadyWritten = false;3249    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}3250    await chrome.runtime.sendMessage({3251      type: "COPY",3252      payload: { text: full.cvc, label: "CVC", alreadyWritten },3253    }).catch(() => {});3254    flashBtn(copyCvc);3255  });3256  actions.appendChild(copyCvc);32573258  const closeBtn = document.createElement("button");3259  closeBtn.className = "sp-action-btn";3260  closeBtn.type = "button";3261  closeBtn.title = "Dismiss";3262  closeBtn.textContent = "✕";3263  closeBtn.addEventListener("click", (e) => {3264    e.stopPropagation();3265    dismiss(true);3266  });3267  actions.appendChild(closeBtn);32683269  platter.appendChild(actions);3270  container.appendChild(platter);32713272  document.body.appendChild(host);3273  function updatePosition() {3274    const r = anchorEl.getBoundingClientRect();3275    host.style.top = `${r.bottom + window.scrollY + 5}px`;3276    host.style.left = `${r.left + window.scrollX}px`;3277  }3278  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);32793280  function onKeyDown(e: KeyboardEvent) {3281    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3282  }3283  document.addEventListener("keydown", onKeyDown);32843285  let exitScheduled = false;3286  function dismiss(userAction = false) {3287    if (exitScheduled) return;3288    exitScheduled = true;3289    stopObserving();3290    document.removeEventListener("click", outsideClick, { capture: true });3291    document.removeEventListener("keydown", onKeyDown);3292    if (userAction) options.onDismiss?.();3293    container.classList.add("is-exiting");3294    setTimeout(() => host.remove(), 130);3295  }32963297  function outsideClick(ev: MouseEvent) {3298    const path = ev.composedPath();3299    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3300  }3301  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33023303  return dismiss;3304}