inject.ts

133.5 KB · raw

1/**2 * inject.ts — autofill icon + selector overlay, injected into pages.3 *4 * Runs as a content script. Injects the Peach icon next to detected login5 * fields, anchors it via event-driven positioning (no perpetual rAF — see6 * Projects.md §4.7), and renders the inline autofill selector in a shadow7 * DOM. Never holds decrypted vault data directly: all entry lookups go8 * through `chrome.runtime.sendMessage`, and only the minimum fields needed9 * to fill come back across the boundary.10 */1112import { ACCENT_COLORS, type PasswordPolicy, type SavedIdentity } from "../shared/types";13import { 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    transition: height 220ms cubic-bezier(0.16,1,0.3,1);540  }541  /* Light theme: shadow against a light page is too strong otherwise — drop both542     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */543  .peach-inline-popup[data-theme="light"] {544    box-shadow:545      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),546      0 2px 12px rgba(0,0,0,0.12);547  }548  .peach-inline-popup.is-exiting {549    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;550    pointer-events: none;551  }552553  @keyframes peach-enter {554    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }555    65%  { opacity: 1; filter: blur(0); }556    100% { opacity: 1; transform: translateY(0) scale(1); }557  }558  @keyframes peach-exit {559    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }560    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }561  }562  @keyframes peach-slide-in {563    from { opacity: 0; transform: translateX(12px); }564    to   { opacity: 1; transform: translateX(0); }565  }566  @keyframes peach-slide-back {567    from { opacity: 0; transform: translateX(-12px); }568    to   { opacity: 1; transform: translateX(0); }569  }570  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }571  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }572573  /* Domain header */574  .domain-header {575    padding: 9px 13px 7px;576    border-bottom: 1px solid var(--peach-border);577    display: flex; align-items: center; justify-content: space-between;578    gap: 8px;579  }580  .domain-header-text {581    display: flex; flex-direction: column; gap: 2px;582    min-width: 0; flex: 1;583  }584  .domain-eyebrow {585    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;586    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;587  }588  .domain-name {589    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);590    font-family: "IBM Plex Mono", monospace;591    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;592  }593  .domain-add-btn {594    flex-shrink: 0;595    width: 22px; height: 22px;596    display: inline-flex; align-items: center; justify-content: center;597    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);598    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);599    border-radius: 6px;600    color: var(--peach-accent);601    cursor: pointer; padding: 0;602    transition: background 120ms, border-color 120ms, transform 80ms;603    font-family: "IBM Plex Mono", monospace;604    font-size: 14px; line-height: 1;605  }606  .domain-add-btn:hover {607    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);608    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);609    transform: scale(1.06);610  }611  .domain-add-btn:active { transform: scale(0.96); }612613  /* Search */614  .search-wrap {615    padding: 9px 12px 7px;616    border-bottom: 1px solid var(--peach-border);617  }618  .search {619    width: 100%; background: var(--peach-input-bg);620    border: 1px solid var(--peach-input-border);621    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;622    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;623    transition: border-color 120ms, box-shadow 120ms;624  }625  .search:focus {626    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);627    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);628  }629  .search::placeholder { color: var(--peach-text-muted); }630631  /* Results */632  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }633  .results::-webkit-scrollbar { display: none; }634635  /* Entry rows */636  .entry {637    display: flex; align-items: center; padding: 8px 12px;638    cursor: pointer; border-bottom: 1px solid var(--peach-border);639    transition: background 70ms; position: relative; outline: none;640  }641  .entry:last-child { border-bottom: none; }642  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }643  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }644  .entry.focused::before {645    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;646    width: 2px; border-radius: 2px;647    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);648  }649650  .entry-icon {651    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;652    background: var(--peach-input-bg); border: 1px solid var(--peach-border);653    display: flex; align-items: center; justify-content: center;654    overflow: hidden; margin-right: 10px;655  }656  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }657  .entry-icon.is-new {658    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);659    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);660    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);661  }662663  .entry-info { flex: 1; min-width: 0; }664  .entry-title {665    font-size: 12.5px; color: var(--peach-text);666    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;667    line-height: 1.3;668  }669  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }670  .entry-sub {671    font-size: 10px; color: var(--peach-text-dim);672    font-family: "IBM Plex Mono", monospace;673    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;674    margin-top: 1px;675  }676677  .totp-badge {678    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;679    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);680    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);681    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;682  }683  .passkey-badge {684    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;685    border-radius: 4px;686    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);687    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);688    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);689    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;690  }691692  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }693694  .empty-hint {695    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);696    font-family: "IBM Plex Mono", monospace;697  }698699  /* Create form */700  .create-form-wrap {701    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;702  }703  .create-head {704    display: flex; align-items: center; gap: 8px;705    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);706  }707  .back-btn {708    background: transparent; border: none; cursor: pointer;709    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;710    display: flex; align-items: center; line-height: 0;711    transition: color 100ms, background 100ms;712  }713  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }714  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }715  /* minmax(0, 1fr) caps the grid track at the popup width — without it,716     long monospace content (e.g. a 60-char generated password) would717     auto-size the track wider than the popup and overflow the right edge. */718  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }719  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }720  .f-label {721    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;722    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;723  }724  .f-input {725    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);726    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;727    font-size: 11px; font-family: "IBM Plex Mono", monospace;728    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;729  }730  .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); }731  .f-input::placeholder { color: var(--peach-text-muted); }732  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }733  .f-row { display: flex; gap: 6px; }734  .f-row .f-input { flex: 1; min-width: 0; }735  .gen-btn {736    padding: 0 10px; border-radius: 7px; border: none;737    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);738    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);739    font-size: 10px; font-family: "IBM Plex Mono", monospace;740    cursor: pointer; white-space: nowrap; flex-shrink: 0;741    display: flex; align-items: center; gap: 4px;742    transition: background 100ms;743  }744  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }745  .save-btn {746    width: 100%; padding: 8px; border-radius: 8px; border: none;747    background: var(--peach-accent); color: #fff; font-size: 12px;748    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;749    transition: background 120ms, box-shadow 120ms, transform 80ms;750    letter-spacing: 0.01em;751  }752  .save-btn:hover {753    background: color-mix(in srgb, var(--peach-accent) 82%, #000);754    box-shadow: 0 4px 20px var(--peach-glow, transparent);755  }756  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }757  .url-hint {758    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);759    font-family: "IBM Plex Mono", monospace; font-style: italic;760  }761762  /* Success */763  .success-wrap {764    display: flex; flex-direction: column; align-items: center;765    padding: 24px 16px 20px; gap: 8px;766    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;767  }768  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }769  .success-ring {770    width: 40px; height: 40px; border-radius: 50%;771    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);772    display: flex; align-items: center; justify-content: center;773  }774  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }775  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }776777  /* Silver platter (State 1 — single match) */778  .silver-platter {779    padding: 14px 14px 12px;780    display: flex; flex-direction: column; gap: 6px;781  }782  .sp-title {783    font-size: 14px; font-weight: 500; color: var(--peach-text);784    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;785    line-height: 1.25;786  }787  .sp-identity-row {788    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;789  }790  .sp-identity-label {791    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;792    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;793  }794  .sp-username {795    font-size: 12px; color: var(--peach-text-dim);796    font-family: "IBM Plex Mono", monospace;797    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;798    margin-bottom: 0;799  }800  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }801  .sp-fill-btn {802    width: 100%; padding: 11px; border-radius: 9px; border: none;803    background: var(--peach-accent); color: #fff;804    font-size: 13px; font-weight: 500; cursor: pointer;805    font-family: Inter, sans-serif; letter-spacing: 0.01em;806    display: flex; align-items: center; justify-content: center; min-height: 38px;807    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;808  }809  .sp-fill-btn:hover {810    filter: brightness(1.1);811    box-shadow: 0 4px 20px var(--peach-glow, transparent);812    transform: translateY(-1px);813  }814  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }815  .sp-fill-btn.filled {816    background: #16a34a; transform: none; filter: none;817    box-shadow: 0 4px 16px rgba(22,163,74,0.35);818    cursor: default;819  }820  .sp-fill-btn:disabled { cursor: default; }821  .sp-actions {822    display: flex; gap: 4px; justify-content: space-between; align-items: center;823    margin-top: 4px;824  }825  .sp-action-btn {826    flex: 1; height: 28px; border: none; border-radius: 6px;827    background: transparent; color: var(--peach-text-dim);828    font-size: 12px; cursor: pointer;829    transition: background 120ms ease, color 120ms ease;830    font-family: Inter, sans-serif; letter-spacing: 0.04em;831    display: inline-flex; align-items: center; justify-content: center; gap: 4px;832    white-space: nowrap; overflow: hidden;833  }834  .sp-action-btn:hover:not(:disabled) {835    background: color-mix(in srgb, var(--peach-text) 5%, transparent);836    color: var(--peach-text);837  }838  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }839  .sp-action-btn.flashed {840    color: var(--peach-accent);841    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);842  }843844  /* TOTP tray — shown below the silver-platter secondary actions */845  .sp-tray {846    margin-top: 8px;847    padding: 10px 12px;848    border-radius: 9px;849    background: var(--peach-input-bg);850    border: 1px solid var(--peach-input-border);851    display: flex; align-items: center; gap: 12px;852    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;853  }854  .sp-tray-label {855    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;856    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;857    flex-shrink: 0;858  }859  .sp-totp-code {860    font-size: 18px; font-weight: 500;861    color: var(--peach-text);862    font-family: "IBM Plex Mono", monospace;863    letter-spacing: 0.12em;864    flex: 1;865    text-align: center;866  }867  .sp-totp-ring {868    width: 22px; height: 22px; flex-shrink: 0;869  }870  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }871  .sp-totp-ring .ring-fill {872    stroke: var(--peach-accent);873    transition: stroke-dashoffset 1s linear;874    transform: rotate(-90deg);875    transform-origin: center;876  }877  .sp-totp-copy {878    background: transparent; border: none; cursor: pointer;879    padding: 4px 8px; border-radius: 5px;880    color: var(--peach-text-dim); font-size: 11px;881    font-family: Inter, sans-serif;882    transition: background 120ms, color 120ms;883  }884  .sp-totp-copy:hover {885    background: color-mix(in srgb, var(--peach-text) 5%, transparent);886    color: var(--peach-text);887  }888889  /* Card silver platter (State 7) — reuses .sp-* primary action classes */890  .card-platter {891    padding: 12px 14px 10px;892    display: flex; flex-direction: column; gap: 4px;893  }894  .cp-network {895    font-size: 10px; font-weight: 600;896    color: var(--peach-accent);897    letter-spacing: 0.08em; text-transform: uppercase;898    font-family: Inter, sans-serif;899  }900  .cp-nickname {901    font-size: 14px; font-weight: 500; color: var(--peach-text);902    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;903    line-height: 1.2;904  }905  .cp-last4 {906    font-size: 12px; color: var(--peach-text-dim);907    font-family: "IBM Plex Mono", monospace;908    letter-spacing: 0.04em;909    margin-top: 2px;910  }911  .cp-meta {912    font-size: 11px; color: var(--peach-text-dim);913    font-family: "IBM Plex Mono", monospace;914    margin-top: 2px;915    display: flex; gap: 10px; align-items: center;916  }917  .cp-meta-sep { opacity: 0.5; }918  .cp-fill-wrap { margin-top: 10px; }919920  /* Locked state */921  .locked-wrap {922    display: flex; flex-direction: column; align-items: stretch;923    padding: 14px 13px 13px; gap: 9px;924  }925  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }926  .locked-icon {927    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;928    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);929    display: flex; align-items: center; justify-content: center;930  }931  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }932  .locked-input {933    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);934    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;935    font-size: 11px; font-family: "IBM Plex Mono", monospace;936    outline: none; transition: border-color 120ms, box-shadow 120ms;937  }938  .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); }939  .locked-input::placeholder { color: var(--peach-text-muted); }940  .locked-btn {941    width: 100%; padding: 8px; border-radius: 8px; border: none;942    background: var(--peach-accent); color: #fff; font-size: 12px;943    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;944    transition: background 120ms;945    letter-spacing: 0.01em;946    box-shadow: 0 2px 16px var(--peach-glow, transparent);947    animation: peach-pulse-glow 2.4s ease-in-out infinite;948  }949  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }950  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }951  .locked-error {952    font-size: 10px; color: rgba(220,80,60,0.85);953    font-family: "IBM Plex Mono", monospace;954  }955956  @keyframes peach-pulse-glow {957    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }958    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),959                            0 0 48px var(--peach-glow, transparent); }960  }961962  /* ── State 10: identity helper ─────────────────────────────── */963  .identity-list {964    max-height: 192px; overflow-y: auto; padding: 4px 0;965    scrollbar-width: none;966  }967  .identity-list::-webkit-scrollbar { display: none; }968  .peach-identity-row {969    display: flex; align-items: center; gap: 10px;970    padding: 9px 12px; cursor: pointer; border-radius: 8px;971    transition: background 100ms ease;972  }973  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }974  .peach-identity-value {975    font-family: "IBM Plex Mono", monospace; font-size: 13px;976    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;977  }978  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }979  .identity-alt-row {980    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;981    border-radius: 8px; transition: background 100ms ease;982    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;983  }984  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }985  .identity-escape-row {986    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;987    border-radius: 8px; transition: background 100ms ease; outline: none;988    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;989    margin-top: 2px;990  }991  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }992  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }993  .identity-alt-input-wrap.open { display: flex; }994  .identity-alt-input {995    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;996    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);997    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;998    outline: none; transition: border-color 120ms;999  }1000  .identity-alt-input:focus {1001    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1002    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1003  }1004  .identity-alt-confirm {1005    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1006    background: var(--peach-accent); color: #fff; font-size: 12px;1007    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1008  }1009  /* ── Generator view (after identity picked) ────────────────── */1010  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1011  .gen-confirmed {1012    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1013    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1014    border-radius: 8px;1015  }1016  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1017  .gen-confirmed-val {1018    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1019    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1020  }1021  .gen-label {1022    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1023    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1024  }1025  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1026  .gen-pw-val {1027    flex: 1; padding: 8px 10px; border-radius: 7px;1028    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1029    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1030    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1031  }1032  .gen-regen-btn {1033    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1034    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1035    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1036    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1037  }1038  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1039  .gen-fill-btn {1040    padding: 10px; border-radius: 8px; border: none;1041    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1042    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1043    transition: filter 120ms ease, transform 80ms ease;1044  }1045  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1046  .gen-fill-btn:active { transform: translateY(0); }10471048  /* ── Smart password generator (parity with main UI compact mode) ─── */1049  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1050  .pwgen-display-row {1051    display: flex; align-items: center; gap: 6px;1052    padding: 8px 10px; border-radius: 7px;1053    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1054  }1055  .pwgen-output {1056    flex: 1; min-width: 0; width: 0;1057    font-family: "IBM Plex Mono", monospace; font-size: 12px;1058    color: var(--peach-text);1059    background: transparent; border: none; outline: none; padding: 0;1060  }1061  .pwgen-icon-btn {1062    flex-shrink: 0;1063    width: 26px; height: 26px;1064    display: inline-flex; align-items: center; justify-content: center;1065    background: transparent; border: 1px solid var(--peach-input-border);1066    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1067    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1068  }1069  .pwgen-icon-btn:hover {1070    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1071    color: var(--peach-accent);1072    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1073  }1074  .pwgen-icon-btn.is-copied {1075    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1076    color: var(--peach-accent);1077    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1078  }1079  .pwgen-controls-row {1080    display: flex; align-items: center; gap: 8px;1081    flex-wrap: wrap;1082  }1083  .pwgen-slider {1084    flex: 1; min-width: 110px;1085    accent-color: var(--peach-accent);1086    cursor: pointer; height: 2px; background: transparent;1087  }1088  .pwgen-len-num {1089    font-family: "IBM Plex Mono", monospace; font-size: 11px;1090    color: var(--peach-accent); min-width: 22px; text-align: right;1091  }1092  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1093  .pwgen-len-input {1094    font-family: "IBM Plex Mono", monospace; font-size: 11px;1095    color: var(--peach-accent); width: 28px; text-align: right;1096    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1097    outline: none; padding: 0; min-width: 22px;1098  }1099  @keyframes identity-suggest-in {1100    from { opacity: 0; transform: translateY(-4px); }1101    to   { opacity: 1; transform: none; }1102  }1103  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1104    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1105  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1106  .identity-collapse-btn {1107    margin-left: auto; background: transparent; border: none; cursor: pointer;1108    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1109    line-height: 0; border-radius: 3px;1110    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1111  }1112  .identity-collapse-btn:hover { color: var(--peach-text); }1113  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1114  .identity-rows { display: grid; grid-template-rows: 1fr;1115    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1116  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1117  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1118    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1119  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1120  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1121  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1122  .identity-filter-pill {1123    padding: 2px 7px; border-radius: 999px;1124    border: 1px solid var(--peach-input-border);1125    background: transparent; color: var(--peach-text-muted);1126    font-family: "IBM Plex Mono", monospace; font-size: 9px;1127    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1128  }1129  .identity-filter-pill.is-on {1130    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1131    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1132    color: var(--peach-accent);1133  }1134  .identity-suggest-row {1135    display: flex; align-items: center; gap: 5px;1136    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1137    background: transparent; cursor: pointer; text-align: left;1138    transition: background 80ms;1139  }1140  .identity-suggest-row:hover,1141  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1142  .identity-suggest-val {1143    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1144    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1145  }1146  .identity-suggest-type {1147    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1148    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1149  }1150  .identity-suggest-type--email {1151    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1152    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1153  }1154  .identity-suggest-type--username {1155    color: var(--peach-text-muted);1156    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1157  }1158  .identity-suggest-meta {1159    font-family: "IBM Plex Mono", monospace; font-size: 9px;1160    color: var(--peach-text-muted); flex-shrink: 0;1161  }1162  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1163  .pwgen-pill {1164    padding: 3px 8px; border-radius: 999px;1165    border: 1px solid var(--peach-input-border);1166    background: transparent; color: var(--peach-text-muted);1167    font-family: "IBM Plex Mono", monospace; font-size: 9px;1168    letter-spacing: 0.06em; cursor: pointer;1169    transition: all 130ms ease;1170  }1171  .pwgen-pill.is-on {1172    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1173    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1174    color: var(--peach-accent);1175  }1176  .pwgen-pill:not(.is-on):hover {1177    color: var(--peach-text-dim);1178    border-color: var(--peach-text-muted);1179  }1180  .pwgen-policy-hint {1181    font-size: 10px; color: var(--peach-text-muted);1182    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1183    line-height: 1.3;1184  }1185  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11861187  /* ── Save offer (after password filled) ───────────────────── */1188  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1189  .save-offer-title {1190    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1191  }1192  .save-offer-row {1193    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1194    border-radius: 7px; background: var(--peach-input-bg);1195    border: 1px solid var(--peach-input-border);1196  }1197  .save-offer-lbl {1198    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1199    font-family: "IBM Plex Mono", monospace;1200  }1201  .save-offer-val {1202    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1203    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1204  }1205  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1206  .save-offer-save {1207    flex: 1; padding: 9px; border-radius: 8px; border: none;1208    background: var(--peach-accent); color: #fff; font-size: 13px;1209    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1210  }1211  .save-offer-save:hover { filter: brightness(1.08); }1212  .save-offer-skip {1213    flex: 1; padding: 9px; border-radius: 8px; border: none;1214    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1215    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1216    font-family: Inter, sans-serif; transition: background 100ms ease;1217  }1218  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1219`;12201221export function showAutofillSelector(1222  anchorEl: HTMLInputElement,1223  entries: SelectorEntry[],1224  onSelect: (id: string) => void,1225  options: SelectorOptions = {}1226): () => void {1227  const host = document.createElement("div");1228  host.style.cssText = "position: absolute; z-index: 2147483647;";1229  host.style.setProperty("--peach-accent", accentHex);1230  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1231  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1232  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1233  const shadow = host.attachShadow({ mode: "closed" });12341235  const style = shadow.appendChild(document.createElement("style"));1236  style.textContent = SELECTOR_STYLES;12371238  const rect = anchorEl.getBoundingClientRect();1239  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1240  host.style.left = `${rect.left + window.scrollX}px`;1241  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1242  // wide single-input fields (e.g. centered email input on signup pages).1243  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;12441245  const container = shadow.appendChild(document.createElement("div"));1246  container.className = "peach-inline-popup";1247  container.setAttribute("data-theme", popupTheme);12481249  const searchableEntries = options.searchableEntries ?? [];1250  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12511252  let query = "";1253  let focusedIndex = -1;1254  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1255  let searchInput: HTMLInputElement | null = null;1256  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1257  // setInterval. Add to this list — don't fan out the dismiss function.1258  const cleanupHooks: Array<() => void> = [];12591260  // Smooth height transitions whenever content changes height.1261  // ResizeObserver fires on natural height changes; we freeze the old height,1262  // then animate to the new one so the surface never jumps.1263  {1264    let prevH = 0;1265    let blocked = false;1266    const heightRo = new ResizeObserver(([entry]) => {1267      if (blocked) return;1268      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1269      if (prevH > 0 && Math.abs(h - prevH) > 1) {1270        blocked = true;1271        container.style.height = `${prevH}px`;1272        requestAnimationFrame(() => requestAnimationFrame(() => {1273          container.style.height = `${h}px`;1274          prevH = h;1275          const onEnd = (e: TransitionEvent) => {1276            if (e.propertyName !== "height") return;1277            container.style.height = "";1278            blocked = false;1279            container.removeEventListener("transitionend", onEnd);1280          };1281          container.addEventListener("transitionend", onEnd);1282        }));1283      } else {1284        prevH = h;1285      }1286    });1287    heightRo.observe(container);1288    cleanupHooks.push(() => heightRo.disconnect());1289  }12901291  // Pre-capture the anchor field value for username prefill1292  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1293  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1294  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";12951296  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1297    const seen = new Set<string>();1298    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1299  }13001301  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1302    const q = value.trim().toLowerCase();1303    const deduped = uniqueEntries(source);1304    if (!q) return deduped.slice(0, 8);1305    return deduped.filter(e =>1306      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1307    ).slice(0, 12);1308  }13091310  function activeEntries(): SelectorEntry[] {1311    // When user is typing a search, filter across all known entries (domain matches + vault)1312    if (query.trim()) {1313      const merged = uniqueEntries([...entries, ...searchableEntries]);1314      return filterEntries(merged, query);1315    }1316    // Default: show domain matches; fall back to vault search when no matches1317    if (entries.length > 0) return entries;1318    return filterEntries(searchableEntries, "").slice(0, 8);1319  }13201321  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1322    const icon = document.createElement("div");1323    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1324    if (isNew) {1325      icon.innerHTML = plusSvgStr();1326    } else {1327      // Use the generic key glyph for all entries in the page-injected selector.1328      // Avoids disclosing vault domains to any third party and avoids needing1329      // to expose the browser favicon API to page context via web_accessible_resources.1330      void url;1331      icon.innerHTML = keySvgStr();1332    }1333    return icon;1334  }13351336  function renderIdentityHelper() {1337    container.innerHTML = "";1338    const identities = options.savedIdentities ?? [];13391340    // Header: "NEW ACCOUNT" + domain name1341    const hdr = container.appendChild(document.createElement("div"));1342    hdr.className = "domain-header";1343    const eyebrow = hdr.appendChild(document.createElement("div"));1344    eyebrow.className = "domain-eyebrow";1345    eyebrow.textContent = "NEW ACCOUNT";1346    const domName = hdr.appendChild(document.createElement("div"));1347    domName.className = "domain-name";1348    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13491350    // Identity rows1351    const list = container.appendChild(document.createElement("div"));1352    list.className = "identity-list";1353    for (const id of identities) {1354      const row = list.appendChild(document.createElement("div"));1355      row.className = "peach-identity-row";1356      row.setAttribute("tabindex", "-1");1357      const val = row.appendChild(document.createElement("div"));1358      val.className = "peach-identity-value";1359      val.textContent = id.value;1360      const meta = row.appendChild(document.createElement("div"));1361      meta.className = "peach-identity-meta";1362      meta.textContent = `used ${id.useCount}×`;1363      row.addEventListener("click", () => {1364        options.onFillFields?.(id.value, "");1365        renderGenerator(id.value);1366      });1367    }13681369    // Divider before "Use a different email…"1370    if (identities.length > 0) {1371      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1372    }13731374    // "Use a different email…" expandable row1375    const altRow = container.appendChild(document.createElement("div"));1376    altRow.className = "identity-alt-row";1377    altRow.textContent = "+ Use a different email…";13781379    const altInputWrap = container.appendChild(document.createElement("div"));1380    altInputWrap.className = "identity-alt-input-wrap";1381    const altInput = altInputWrap.appendChild(document.createElement("input"));1382    altInput.className = "identity-alt-input";1383    altInput.type = "email";1384    altInput.placeholder = "[email protected]";1385    altInput.setAttribute("autocomplete", "off");1386    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1387    altConfirm.className = "identity-alt-confirm";1388    altConfirm.type = "button";1389    altConfirm.textContent = "✓";13901391    function fillCustomEmail() {1392      const v = altInput.value.trim();1393      if (!v) return;1394      options.onFillFields?.(v, "");1395      renderGenerator(v);1396    }13971398    altRow.addEventListener("click", () => {1399      altRow.style.display = "none";1400      altInputWrap.classList.add("open");1401      altInput.focus();1402    });1403    altConfirm.addEventListener("click", fillCustomEmail);1404    altInput.addEventListener("keydown", (e) => {1405      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1406    });14071408    // Escape hatch: user already has a vault entry for this site but it1409    // wasn't detected (different domain, old entry, etc.). Tapping this1410    // switches to the full searchable list so they can find and fill it;1411    // selecting an entry there will trigger the remember-site toast if1412    // the domain isn't already associated.1413    if ((options.searchableEntries?.length ?? 0) > 0) {1414      const escapeRow = container.appendChild(document.createElement("div"));1415      escapeRow.className = "identity-escape-row";1416      escapeRow.textContent = "I already have an account →";1417      escapeRow.setAttribute("tabindex", "0");1418      escapeRow.addEventListener("click", () => renderList());1419      escapeRow.addEventListener("keydown", (e) => {1420        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1421      });1422    }1423  }14241425  function renderGenerator(filledEmail: string) {1426    container.innerHTML = "";1427    const sitePolicy = detectPasswordPolicy();14281429    const wrap = container.appendChild(document.createElement("div"));1430    wrap.className = "gen-view";14311432    // Header: domain + NEW ACCOUNT1433    const hdrRow = wrap.appendChild(document.createElement("div"));1434    hdrRow.className = "domain-header";1435    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1436    eyebrow2.className = "domain-eyebrow";1437    eyebrow2.textContent = "NEW ACCOUNT";1438    const domName2 = hdrRow.appendChild(document.createElement("div"));1439    domName2.className = "domain-name";1440    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14411442    // Confirmed email row1443    const conf = wrap.appendChild(document.createElement("div"));1444    conf.className = "gen-confirmed";1445    const confCheck = conf.appendChild(document.createElement("span"));1446    confCheck.className = "gen-confirmed-check";1447    confCheck.textContent = "✓";1448    const confVal = conf.appendChild(document.createElement("div"));1449    confVal.className = "gen-confirmed-val";1450    confVal.textContent = filledEmail;14511452    const lbl = wrap.appendChild(document.createElement("div"));1453    lbl.className = "gen-label";1454    lbl.textContent = "Generate a password";14551456    let currentPw = "";1457    const smartGen = createSmartGenerator({1458      policy: sitePolicy,1459      onChange: (pw) => { currentPw = pw; },1460    });1461    wrap.appendChild(smartGen.root);14621463    const fillBtn = wrap.appendChild(document.createElement("button"));1464    fillBtn.className = "gen-fill-btn";1465    fillBtn.type = "button";1466    fillBtn.textContent = "Copy & fill";1467    fillBtn.addEventListener("click", () => {1468      if (!currentPw) return;1469      options.onFillFields?.("", currentPw);1470      renderSaveOffer(filledEmail, currentPw);1471    });1472  }14731474  function renderSaveOffer(filledEmail: string, filledPassword: string) {1475    container.innerHTML = "";1476    const domain = options.domain ?? location.hostname.replace(/^www\./, "");14771478    const wrap = container.appendChild(document.createElement("div"));1479    wrap.className = "save-offer";14801481    const title = wrap.appendChild(document.createElement("div"));1482    title.className = "save-offer-title";1483    title.textContent = "Save this login to Peach?";14841485    function detailRow(label: string, value: string) {1486      const row = wrap.appendChild(document.createElement("div"));1487      row.className = "save-offer-row";1488      const lbl = row.appendChild(document.createElement("div"));1489      lbl.className = "save-offer-lbl";1490      lbl.textContent = label;1491      const val = row.appendChild(document.createElement("div"));1492      val.className = "save-offer-val";1493      val.textContent = value;1494    }14951496    detailRow("site", domain);1497    detailRow("email", filledEmail);1498    detailRow("password", "••••••••••••••••");14991500    const btns = wrap.appendChild(document.createElement("div"));1501    btns.className = "save-offer-btns";15021503    const saveBtn = btns.appendChild(document.createElement("button"));1504    saveBtn.className = "save-offer-save";1505    saveBtn.type = "button";1506    saveBtn.textContent = "Save";1507    saveBtn.addEventListener("click", async () => {1508      saveBtn.disabled = true;1509      saveBtn.textContent = "Saving…";1510      try {1511        const res = await chrome.runtime.sendMessage({1512          type: "ADD_ENTRY",1513          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1514        });1515        if ((res as { ok?: boolean }).ok) {1516          showSuccess(sTitle);1517        } else {1518          saveBtn.disabled = false;1519          saveBtn.textContent = "Save";1520        }1521      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1522    });15231524    const skipBtn = btns.appendChild(document.createElement("button"));1525    skipBtn.className = "save-offer-skip";1526    skipBtn.type = "button";1527    skipBtn.textContent = "Not now";1528    skipBtn.addEventListener("click", () => { dismiss(true); });1529  }15301531  function renderList() {1532    container.innerHTML = "";1533    focusedIndex = -1;1534    searchInput = null;15351536    const current = activeEntries();15371538    // Domain header (always show) — eyebrow + domain on the left,1539    // a "+" shortcut to the create form on the right so the user is never1540    // trapped in the search list when they want to make a new entry.1541    const domHdr = document.createElement("div");1542    domHdr.className = "domain-header";1543    const headText = document.createElement("div");1544    headText.className = "domain-header-text";1545    const eyebrow = document.createElement("div");1546    eyebrow.className = "domain-eyebrow";1547    eyebrow.textContent = options.isSignup1548      ? "Sign up as"1549      : entries.length > 0 ? "Saved for this site" : "No saved login";1550    const domName = document.createElement("div");1551    domName.className = "domain-name";1552    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1553    headText.append(eyebrow, domName);1554    domHdr.appendChild(headText);15551556    if (!options.isSignup) {1557      const addBtn = document.createElement("button");1558      addBtn.className = "domain-add-btn";1559      addBtn.type = "button";1560      addBtn.setAttribute("aria-label", "Create new entry");1561      addBtn.title = "Create new entry";1562      addBtn.textContent = "+";1563      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1564      domHdr.appendChild(addBtn);1565    }15661567    container.appendChild(domHdr);15681569    // Search — always show so user can find entries beyond the domain matches1570    const sw = document.createElement("div"); sw.className = "search-wrap";1571    searchInput = document.createElement("input");1572    searchInput.className = "search";1573    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1574    searchInput.value = query;1575    searchInput.addEventListener("input", () => {1576      query = searchInput?.value ?? "";1577      renderList();1578      searchInput?.focus();1579      searchInput?.setSelectionRange(query.length, query.length);1580    });1581    sw.appendChild(searchInput);1582    container.appendChild(sw);15831584    // Results1585    const results = document.createElement("div");1586    results.className = "results";1587    container.appendChild(results);15881589    if (current.length === 0 && entries.length > 0) {1590      // Show a hint but don't render empty entries1591    }15921593    for (let i = 0; i < current.length; i++) {1594      const e = current[i]!;1595      const entryEl = document.createElement("div");1596      entryEl.className = "entry";1597      entryEl.dataset.id = e.id;1598      entryEl.dataset.index = String(i);1599      entryEl.setAttribute("tabindex", "-1");16001601      entryEl.appendChild(makeEntryIcon(e.url));16021603      const info = document.createElement("div"); info.className = "entry-info";1604      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1605      const subEl = document.createElement("div"); subEl.className = "entry-sub";1606      const domain = e.url ? getDomainFromUrl(e.url) : "";1607      subEl.textContent = domain || e.username || "";1608      info.append(titleEl, subEl);1609      entryEl.appendChild(info);16101611      if (e.hasTotp) {1612        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1613        entryEl.appendChild(badge);1614      }1615      if (e.hasPasskey) {1616        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1617        entryEl.appendChild(badge);1618      }16191620      entryEl.addEventListener("click", () => {1621        if (options.isSignup && options.onFillFields) {1622          // Signup mode: clicking a saved identity fills the username field1623          options.onFillFields(e.username ?? "", "");1624          dismiss();1625        } else {1626          onSelect(e.id);1627          dismiss();1628        }1629      });1630      results.appendChild(entryEl);1631    }16321633    // Divider before "New entry"1634    if (current.length > 0) {1635      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1636    }16371638    // "New entry" row — always present1639    const newEl = document.createElement("div");1640    newEl.className = "entry";1641    newEl.setAttribute("tabindex", "-1");1642    newEl.appendChild(makeEntryIcon(undefined, true));16431644    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1645    const newTitle = document.createElement("div");1646    newTitle.className = "entry-title is-new";1647    newTitle.textContent = `New entry for ${sTitle}`;1648    const newSub = document.createElement("div");1649    newSub.className = "entry-sub";1650    newSub.textContent = sOrigin;1651    newInfo.append(newTitle, newSub);1652    newEl.appendChild(newInfo);1653    newEl.addEventListener("click", showCreateForm);1654    results.appendChild(newEl);16551656    // Focus search if present1657    if (searchInput) {1658      requestAnimationFrame(() => searchInput?.focus());1659    }1660  }16611662  function setFocused(idx: number) {1663    const all = container.querySelectorAll<HTMLElement>(".entry");1664    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1665    focusedIndex = idx;1666    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1667  }16681669  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1670    const typed = identities.filter(s => s.type === fieldType);1671    if (!typed.length) return;1672    let collapsed = false;1673    let suppressNextFocus = false;16741675    const list = g.appendChild(document.createElement("div"));1676    list.className = "identity-suggest-list";1677    list.style.display = "none";16781679    // Collapse toggle — sits alone now that filter pills are gone1680    const collapseRow = list.appendChild(document.createElement("div"));1681    collapseRow.className = "identity-filter-row";1682    collapseRow.style.justifyContent = "flex-end";1683    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1684    collapseBtn.type = "button";1685    collapseBtn.className = "identity-collapse-btn";1686    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>`;1687    collapseBtn.addEventListener("mousedown", (e) => {1688      e.preventDefault();1689      collapsed = !collapsed;1690      collapseBtn.classList.toggle("is-collapsed", collapsed);1691      rowsWrapper.classList.toggle("is-collapsed", collapsed);1692    });16931694    const rowsWrapper = list.appendChild(document.createElement("div"));1695    rowsWrapper.className = "identity-rows";1696    const rows = rowsWrapper.appendChild(document.createElement("div"));1697    rows.className = "identity-rows-inner";16981699    function pick(value: string) {1700      inp.value = value;1701      list.style.display = "none";1702      suppressNextFocus = true;1703      inp.focus();1704    }17051706    function render() {1707      const q = inp.value.toLowerCase();1708      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1709      rows.innerHTML = "";1710      if (!filtered.length) { list.style.display = "none"; return; }1711      for (const s of filtered) {1712        const row = rows.appendChild(document.createElement("button"));1713        row.type = "button"; row.className = "identity-suggest-row";1714        const val = row.appendChild(document.createElement("span"));1715        val.className = "identity-suggest-val"; val.textContent = s.value;1716        const meta = row.appendChild(document.createElement("span"));1717        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1718        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1719        row.addEventListener("keydown", (e) => {1720          if (e.key === "ArrowDown") {1721            e.preventDefault();1722            (row.nextElementSibling as HTMLElement | null)?.focus();1723          } else if (e.key === "ArrowUp") {1724            e.preventDefault();1725            const prev = row.previousElementSibling as HTMLElement | null;1726            if (prev) prev.focus();1727            else inp.focus();1728          } else if (e.key === "Enter" || e.key === " ") {1729            e.preventDefault();1730            pick(s.value);1731          } else if (e.key === "Escape") {1732            e.preventDefault();1733            list.style.display = "none";1734            suppressNextFocus = true;1735            inp.focus();1736          }1737        });1738        row.addEventListener("blur", (e) => {1739          const rt = (e as FocusEvent).relatedTarget as Node | null;1740          if (rt && (rt === inp || list.contains(rt))) return;1741          setTimeout(() => { list.style.display = "none"; }, 150);1742        });1743      }1744      list.style.display = "";1745    }17461747    inp.addEventListener("focus", () => {1748      if (suppressNextFocus) { suppressNextFocus = false; return; }1749      render();1750    });1751    inp.addEventListener("input", render);1752    inp.addEventListener("keydown", (e) => {1753      if (list.style.display === "none") return;1754      if (e.key === "ArrowDown" && !collapsed) {1755        e.preventDefault();1756        (rows.firstElementChild as HTMLElement | null)?.focus();1757      } else if (e.key === "Escape") {1758        e.preventDefault();1759        list.style.display = "none";1760      }1761    });1762    inp.addEventListener("blur", (e) => {1763      const rt = (e as FocusEvent).relatedTarget as Node | null;1764      if (rt && list.contains(rt)) return;1765      setTimeout(() => { list.style.display = "none"; }, 150);1766    });1767  }17681769  async function showCreateForm() {1770    currentMode = "create";1771    container.innerHTML = "";17721773    // Guard: the service worker may lock the vault between when the selector1774    // opens and when the user clicks "New entry". Show the inline unlock form1775    // instead of silently failing on save.1776    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1777    if (!statusRes?.unlocked) {1778      renderLocked();1779      return;1780    }17811782    // Detect page password policy once for this form — reused on every1783    // regenerate click so the user always gets a compliant password.1784    const sitePolicy = detectPasswordPolicy();17851786    // Fetch identities on-demand — they're passed in signup context but not1787    // in login/search context where the user still clicks "New entry".1788    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1789    if (!formIdentities.length) {1790      try {1791        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1792        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1793      } catch { /* silent fallback */ }1794    }17951796    const wrap = document.createElement("div");1797    wrap.className = "create-form-wrap";17981799    // Header1800    const head = document.createElement("div"); head.className = "create-head";1801    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1802    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>`;1803    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1804    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1805    head.append(backBtn, lbl);18061807    // Body1808    const body = document.createElement("div"); body.className = "create-body";18091810    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1811      const g = document.createElement("div"); g.className = "f-group";1812      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1813      const inp = document.createElement("input"); inp.className = "f-input";1814      g.append(l, inp); return { g, inp };1815    }18161817    // Title1818    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1819    body.appendChild(tg.g);18201821    // URL1822    const ug = fGroup("website");1823    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1824    if (loginSubdomain) {1825      const h = document.createElement("div"); h.className = "url-hint";1826      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1827    }1828    body.appendChild(ug.g);18291830    // Username — pre-fill from anchor if it doesn't look like an email1831    const xg = fGroup("username");1832    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1833    xg.inp.placeholder = "johndoe";1834    xg.inp.setAttribute("autocomplete", "off");1835    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1836    body.appendChild(xg.g);18371838    // Email — pre-fill from anchor if it looks like an email1839    const eg = fGroup("email");1840    (eg.inp as HTMLInputElement).type = "email";1841    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1842    eg.inp.placeholder = "[email protected]";1843    eg.inp.setAttribute("autocomplete", "off");1844    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1845    body.appendChild(eg.g);18461847    // Password — full smart generator with charset pills + length slider +1848    // policy hint. Mirrors the main UI's compact generator so users get the1849    // same controls inline as in the popup.1850    const pg = fGroup("password");1851    let currentPassword = prePassword || "";1852    const smartGen = createSmartGenerator({1853      policy: sitePolicy,1854      initialPassword: prePassword || undefined,1855      onChange: (pw) => { currentPassword = pw; },1856    });1857    pg.g.appendChild(smartGen.root);1858    body.appendChild(pg.g);18591860    // Save1861    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1862    saveBtn.textContent = "Save entry";1863    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1864    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1865    saveBtn.addEventListener("click", async () => {1866      const title = tg.inp.value.trim();1867      const pw = currentPassword.trim();1868      const username = xg.inp.value.trim();1869      const email = eg.inp.value.trim();1870      if (!title) {1871        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1872        showFormError("Entry needs a title");1873        return;1874      }1875      if (!pw) {1876        showFormError("Entry needs a password — tap regen to make one");1877        return;1878      }1879      errEl.style.display = "none";1880      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1881      try {1882        const res = await chrome.runtime.sendMessage({1883          type: "ADD_ENTRY",1884          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1885        });1886        if ((res as { ok?: boolean }).ok) {1887          // Fill the detected form. onFillFields uses whichever identity the1888          // page anchored on — the vault captures both username and email.1889          options.onFillFields?.(username || email, pw);1890          showSuccess(title);1891        } else {1892          const errMsg = (res as { error?: string }).error === "vault locked"1893            ? "Vault locked — open Peach to save"1894            : "Could not save entry";1895          showFormError(errMsg);1896          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1897        }1898      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1899    });1900    body.appendChild(saveBtn);1901    body.appendChild(errEl);19021903    wrap.append(head, body);1904    container.appendChild(wrap);1905    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1906  }19071908  function showSuccess(title: string) {1909    currentMode = "success";1910    container.innerHTML = "";1911    const wrap = document.createElement("div"); wrap.className = "success-wrap";1912    const ring = document.createElement("div"); ring.className = "success-ring";1913    ring.innerHTML = checkSvgStr();1914    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1915    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1916    wrap.append(ring, t, s);1917    container.appendChild(wrap);1918    setTimeout(() => dismiss(), 1600);1919  }19201921  function flashActionBtn(btn: HTMLButtonElement) {1922    btn.classList.add("flashed");1923    setTimeout(() => btn.classList.remove("flashed"), 700);1924  }19251926  function renderSilverPlatter(entry: SelectorEntry) {1927    container.innerHTML = "";1928    searchInput = null;1929    focusedIndex = -1;1930    currentMode = "silver-platter";19311932    const domHdr = document.createElement("div");1933    domHdr.className = "domain-header";1934    const headText = document.createElement("div");1935    headText.className = "domain-header-text";1936    const eyebrow = document.createElement("div");1937    eyebrow.className = "domain-eyebrow";1938    eyebrow.textContent = "Saved for this site";1939    const domName = document.createElement("div");1940    domName.className = "domain-name";1941    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1942    headText.append(eyebrow, domName);1943    domHdr.appendChild(headText);1944    if (!options.isSignup) {1945      const addBtn = document.createElement("button");1946      addBtn.className = "domain-add-btn";1947      addBtn.type = "button";1948      addBtn.setAttribute("aria-label", "Create new entry");1949      addBtn.title = "Create new entry";1950      addBtn.textContent = "+";1951      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1952      domHdr.appendChild(addBtn);1953    }1954    container.appendChild(domHdr);19551956    const platter = document.createElement("div");1957    platter.className = "silver-platter";19581959    const titleEl = document.createElement("div");1960    titleEl.className = "sp-title";1961    titleEl.textContent = entry.title;1962    platter.appendChild(titleEl);19631964    if (entry.email) {1965      const emailEl = document.createElement("div");1966      emailEl.className = "sp-identity-row";1967      const emailLbl = document.createElement("span");1968      emailLbl.className = "sp-identity-label";1969      emailLbl.textContent = "email";1970      const emailVal = document.createElement("span");1971      emailVal.className = "sp-username";1972      emailVal.textContent = entry.email;1973      emailEl.append(emailLbl, emailVal);1974      platter.appendChild(emailEl);1975    }19761977    if (entry.username) {1978      const userEl = document.createElement("div");1979      userEl.className = "sp-identity-row";1980      const userLbl = document.createElement("span");1981      userLbl.className = "sp-identity-label";1982      userLbl.textContent = entry.username.includes("@") ? "email" : "username";1983      const userVal = document.createElement("span");1984      userVal.className = "sp-username";1985      userVal.textContent = entry.username;1986      userEl.append(userLbl, userVal);1987      platter.appendChild(userEl);1988    }19891990    const fillBtn = document.createElement("button");1991    fillBtn.className = "sp-fill-btn";1992    fillBtn.type = "button";1993    fillBtn.textContent = "Fill credentials";1994    fillBtn.addEventListener("click", () => {1995      if (fillBtn.disabled) return;1996      fillBtn.disabled = true;1997      fillBtn.classList.add("filled");1998      fillBtn.innerHTML = checkSvgStr();1999      // Fire the fill, then exit via the standard exit animation. The fill2000      // itself is async (handled in index.ts) — by 400ms the form is filled2001      // and the popup begins its exit. Total dwell from click to host2002      // removal: 400ms + 130ms (exit animation) = 530ms.2003      onSelect(entry.id);2004      setTimeout(() => dismiss(), 400);2005    });2006    platter.appendChild(fillBtn);20072008    const actions = document.createElement("div");2009    actions.className = "sp-actions";20102011    if (entry.email) {2012      const copyEmail = document.createElement("button");2013      copyEmail.className = "sp-action-btn";2014      copyEmail.type = "button";2015      copyEmail.title = "Copy email";2016      copyEmail.textContent = "Copy email";2017      copyEmail.addEventListener("click", async (e) => {2018        e.stopPropagation();2019        let alreadyWritten = false;2020        try { await navigator.clipboard.writeText(entry.email!); alreadyWritten = true; } catch {}2021        await chrome.runtime.sendMessage({2022          type: "COPY",2023          payload: { text: entry.email, label: "Email", alreadyWritten },2024        }).catch(() => {});2025        flashActionBtn(copyEmail);2026      });2027      actions.appendChild(copyEmail);2028    }20292030    const copyU = document.createElement("button");2031    copyU.className = "sp-action-btn";2032    copyU.type = "button";2033    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";2034    copyU.title = copyULabel;2035    copyU.textContent = copyULabel;2036    copyU.disabled = !entry.username;2037    copyU.addEventListener("click", async (e) => {2038      e.stopPropagation();2039      if (!entry.username) return;2040      let alreadyWritten = false;2041      try { await navigator.clipboard.writeText(entry.username); alreadyWritten = true; } catch {}2042      await chrome.runtime.sendMessage({2043        type: "COPY",2044        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2045      }).catch(() => {});2046      flashActionBtn(copyU);2047    });2048    actions.appendChild(copyU);20492050    const copyP = document.createElement("button");2051    copyP.className = "sp-action-btn";2052    copyP.type = "button";2053    copyP.title = "Copy password";2054    copyP.textContent = "Copy password";2055    copyP.addEventListener("click", async (e) => {2056      e.stopPropagation();2057      const resp = await chrome.runtime.sendMessage({2058        type: "GET_ENTRY_FOR_FILL",2059        payload: { id: entry.id },2060      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2061      if (!resp?.ok || !resp.data?.password) return;2062      let alreadyWritten = false;2063      try { await navigator.clipboard.writeText(resp.data.password); alreadyWritten = true; } catch {}2064      await chrome.runtime.sendMessage({2065        type: "COPY",2066        payload: { text: resp.data.password, label: "Password", alreadyWritten },2067      }).catch(() => {});2068      flashActionBtn(copyP);2069    });2070    actions.appendChild(copyP);20712072    let trayEl: HTMLDivElement | null = null;2073    let trayInterval: ReturnType<typeof setInterval> | null = null;20742075    function closeTray() {2076      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2077      trayEl?.remove();2078      trayEl = null;2079    }2080    // Register so dismiss() will close the tray and clear the interval2081    // even if the user dismisses without explicitly closing the tray.2082    cleanupHooks.push(closeTray);20832084    async function openTOTPTray() {2085      // Fetch the entry to get the TOTP secret. The selector summary doesn't2086      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2087      // the message-passing surface minimal per Projects.md §5.2).2088      const resp = await chrome.runtime.sendMessage({2089        type: "GET_ENTRY_FOR_FILL",2090        payload: { id: entry.id },2091      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2092      const secret = resp?.ok ? resp.data?.totp : undefined;2093      if (!secret) return;20942095      trayEl = document.createElement("div");2096      trayEl.className = "sp-tray";20972098      const label = document.createElement("span");2099      label.className = "sp-tray-label";2100      label.textContent = "2FA";2101      trayEl.appendChild(label);21022103      const codeEl = document.createElement("div");2104      codeEl.className = "sp-totp-code";2105      trayEl.appendChild(codeEl);21062107      const ringNs = "http://www.w3.org/2000/svg";2108      const ring = document.createElementNS(ringNs, "svg");2109      ring.setAttribute("class", "sp-totp-ring");2110      ring.setAttribute("viewBox", "0 0 24 24");2111      const trackC = document.createElementNS(ringNs, "circle");2112      trackC.setAttribute("class", "ring-track");2113      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2114      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2115      const fillC = document.createElementNS(ringNs, "circle");2116      fillC.setAttribute("class", "ring-fill");2117      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2118      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2119      fillC.setAttribute("stroke-linecap", "round");2120      fillC.setAttribute("stroke-dasharray", "62.83");2121      ring.append(trackC, fillC);2122      trayEl.appendChild(ring);21232124      const copyBtn = document.createElement("button");2125      copyBtn.className = "sp-totp-copy";2126      copyBtn.type = "button";2127      copyBtn.textContent = "Copy";2128      trayEl.appendChild(copyBtn);21292130      function refresh() {2131        const { code, remaining } = generateTOTP(secret!);2132        // Group as "847 291" — easier to read than "847291"2133        codeEl.textContent = code.length === 62134          ? `${code.slice(0, 3)} ${code.slice(3)}`2135          : code;2136        // Ring fills counter-clockwise as time elapses: dashoffset goes from2137        // 0 (full ring) to 62.83 (empty) over the 30s window.2138        const fraction = (30 - remaining) / 30;2139        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2140      }2141      refresh();2142      trayInterval = setInterval(refresh, 1000);21432144      copyBtn.addEventListener("click", async (e) => {2145        e.stopPropagation();2146        const { code } = generateTOTP(secret!);2147        let alreadyWritten = false;2148        try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}2149        await chrome.runtime.sendMessage({2150          type: "COPY",2151          payload: { text: code, label: "TOTP", alreadyWritten },2152        }).catch(() => {});2153        copyBtn.textContent = "Copied";2154        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2155      });21562157      platter.appendChild(trayEl);2158    }21592160    const editBtn = document.createElement("button");2161    editBtn.className = "sp-action-btn sp-action-edit";2162    editBtn.type = "button";2163    editBtn.title = "Edit entry";2164    editBtn.textContent = "Edit";2165    editBtn.addEventListener("click", (e) => {2166      e.stopPropagation();2167      closeTray();2168      void renderInlineEdit(entry);2169    });2170    actions.appendChild(editBtn);21712172    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2173    // "···" toggle was zero-savings (the toggle button took the same space2174    // the "2FA" label needed) and made the code one extra click away.2175    if (entry.hasTotp) void openTOTPTray();21762177    platter.appendChild(actions);2178    container.appendChild(platter);2179  }21802181  /**2182   * Inline-popup edit mode. Swaps the silver platter for an editable form2183   * over the same shadow-DOM surface so the user never leaves the page.2184   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2185   * with the new fields. Cancel returns without writing.2186   */2187  async function renderInlineEdit(summary: SelectorEntry) {2188    container.innerHTML = "";2189    const wrap = document.createElement("div");2190    wrap.className = "create-form-wrap";21912192    const head = document.createElement("div");2193    head.className = "create-head";2194    const back = document.createElement("button");2195    back.className = "back-btn";2196    back.type = "button";2197    back.title = "Cancel";2198    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>`;2199    back.addEventListener("click", () => renderSilverPlatter(summary));2200    head.appendChild(back);2201    const headLbl = document.createElement("div");2202    headLbl.className = "create-label";2203    headLbl.textContent = "Edit entry";2204    head.appendChild(headLbl);2205    wrap.appendChild(head);22062207    const body = document.createElement("div");2208    body.className = "create-body";22092210    // Loading shimmer while we fetch the full entry2211    const loading = document.createElement("div");2212    loading.className = "empty-hint";2213    loading.textContent = "loading…";2214    body.appendChild(loading);2215    wrap.appendChild(body);2216    container.appendChild(wrap);22172218    const [res, idRes] = await Promise.all([2219      chrome.runtime.sendMessage({2220        type: "GET_ENTRY_FOR_FILL",2221        payload: { id: summary.id },2222      }).catch(() => null),2223      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2224    ]);2225    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2226    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];22272228    if (!entryRes || !entryRes.ok || !entryRes.data) {2229      loading.textContent = "couldn't load this entry. try again from the popup.";2230      return;2231    }2232    body.innerHTML = "";22332234    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2235      const group = document.createElement("div");2236      group.className = "f-group";2237      const lbl = document.createElement("div");2238      lbl.className = "f-label";2239      lbl.textContent = label;2240      const input = document.createElement("input");2241      input.className = "f-input";2242      input.type = type;2243      input.value = value;2244      input.autocomplete = "off";2245      group.append(lbl, input);2246      body.appendChild(group);2247      return { g: group, inp: input };2248    }22492250    const titleInput = field("title", entryRes.data.title ?? "").inp;2251    const urlInput = field("url", entryRes.data.url ?? "").inp;2252    urlInput.classList.add("url-f");2253    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2254    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2255    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2256    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2257    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");22582259    // Password row with reveal toggle2260    const pwGroup = document.createElement("div");2261    pwGroup.className = "f-group";2262    const pwLbl = document.createElement("div");2263    pwLbl.className = "f-label";2264    pwLbl.textContent = "password";2265    const pwRow = document.createElement("div");2266    pwRow.className = "f-row";2267    const pwInput = document.createElement("input");2268    pwInput.className = "f-input";2269    pwInput.type = "password";2270    pwInput.value = entryRes.data.password ?? "";2271    pwInput.autocomplete = "new-password";2272    const revealBtn = document.createElement("button");2273    revealBtn.className = "gen-btn";2274    revealBtn.type = "button";2275    revealBtn.textContent = "show";2276    revealBtn.addEventListener("click", () => {2277      const reveal = pwInput.type === "password";2278      pwInput.type = reveal ? "text" : "password";2279      revealBtn.textContent = reveal ? "hide" : "show";2280    });2281    pwRow.append(pwInput, revealBtn);2282    pwGroup.append(pwLbl, pwRow);2283    body.appendChild(pwGroup);22842285    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;22862287    // Notes2288    const notesGroup = document.createElement("div");2289    notesGroup.className = "f-group";2290    const notesLbl = document.createElement("div");2291    notesLbl.className = "f-label";2292    notesLbl.textContent = "notes";2293    const notesInput = document.createElement("textarea");2294    notesInput.className = "f-input";2295    notesInput.rows = 3;2296    notesInput.value = entryRes.data.notes ?? "";2297    notesInput.style.fontFamily = "Inter, sans-serif";2298    notesInput.style.resize = "vertical";2299    notesGroup.append(notesLbl, notesInput);2300    body.appendChild(notesGroup);23012302    // Save / Cancel row2303    const actionsRow = document.createElement("div");2304    actionsRow.className = "f-row";2305    const saveBtn = document.createElement("button");2306    saveBtn.className = "save-btn";2307    saveBtn.type = "button";2308    saveBtn.textContent = "Save changes";2309    saveBtn.style.flex = "1";2310    const cancelBtn = document.createElement("button");2311    cancelBtn.className = "gen-btn";2312    cancelBtn.type = "button";2313    cancelBtn.textContent = "cancel";2314    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2315    actionsRow.append(saveBtn, cancelBtn);2316    body.appendChild(actionsRow);23172318    saveBtn.addEventListener("click", async () => {2319      saveBtn.disabled = true;2320      const originalLabel = saveBtn.textContent;2321      saveBtn.textContent = "Saving…";2322      const patch: Record<string, unknown> = {2323        title: titleInput.value.trim(),2324        url: urlInput.value.trim(),2325        username: usernameInput.value.trim(),2326        email: emailInput.value.trim() || undefined,2327        password: pwInput.value,2328        totp: totpInput.value.trim(),2329        notes: notesInput.value,2330      };2331      const updateRes = (await chrome.runtime.sendMessage({2332        type: "UPDATE_ENTRY",2333        payload: { id: summary.id, patch },2334      }).catch(() => null)) as { ok: boolean; error?: string } | null;2335      if (!updateRes?.ok) {2336        saveBtn.disabled = false;2337        saveBtn.textContent = originalLabel;2338        const err = document.createElement("div");2339        err.className = "empty-hint";2340        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2341        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2342        body.appendChild(err);2343        setTimeout(() => err.remove(), 3000);2344        return;2345      }2346      // Refresh the platter with updated summary fields2347      const refreshed: SelectorEntry = {2348        id: summary.id,2349        title: patch.title as string,2350        username: patch.username as string,2351        email: patch.email as string | undefined,2352        url: patch.url as string,2353        hasTotp: Boolean(patch.totp),2354        hasPasskey: summary.hasPasskey,2355      };2356      renderSilverPlatter(refreshed);2357    });23582359    queueMicrotask(() => titleInput.focus());2360  }23612362  function renderLocked() {2363    container.innerHTML = "";23642365    // Domain header (same as list view)2366    const domHdr = document.createElement("div");2367    domHdr.className = "domain-header";2368    const eyebrow = document.createElement("div");2369    eyebrow.className = "domain-eyebrow";2370    eyebrow.textContent = "vault locked";2371    const domName = document.createElement("div");2372    domName.className = "domain-name";2373    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2374    domHdr.append(eyebrow, domName);2375    container.appendChild(domHdr);23762377    const wrap = document.createElement("div");2378    wrap.className = "locked-wrap";23792380    // Icon + label row2381    const head = document.createElement("div"); head.className = "locked-head";2382    const icon = document.createElement("div"); icon.className = "locked-icon";2383    icon.innerHTML = keySvgStr();2384    const title = document.createElement("div"); title.className = "locked-title";2385    title.textContent = "unlock to autofill";2386    head.append(icon, title);23872388    // Password input2389    const pwInp = document.createElement("input");2390    pwInp.className = "locked-input";2391    pwInp.type = "password";2392    pwInp.placeholder = "master password";2393    pwInp.setAttribute("autocomplete", "current-password");23942395    // Error line (hidden initially)2396    const errEl = document.createElement("div");2397    errEl.className = "locked-error";2398    errEl.style.display = "none";23992400    // Unlock button2401    const unlockBtn = document.createElement("button");2402    unlockBtn.className = "locked-btn";2403    unlockBtn.type = "button";2404    unlockBtn.textContent = "unlock";24052406    async function tryUnlock() {2407      const pw = pwInp.value.trim();2408      if (!pw) { pwInp.focus(); return; }2409      unlockBtn.disabled = true;2410      unlockBtn.textContent = "unlocking…";2411      errEl.style.display = "none";2412      try {2413        const res = await chrome.runtime.sendMessage({2414          type: "UNLOCK",2415          payload: { password: pw },2416        });2417        if ((res as { ok?: boolean }).ok) {2418          dismiss();2419          options.onUnlocked?.();2420        } else {2421          errEl.textContent = "incorrect password";2422          errEl.style.display = "block";2423          pwInp.value = "";2424          pwInp.focus();2425          unlockBtn.disabled = false;2426          unlockBtn.textContent = "unlock";2427        }2428      } catch {2429        errEl.textContent = "could not reach Peach";2430        errEl.style.display = "block";2431        unlockBtn.disabled = false;2432        unlockBtn.textContent = "unlock";2433      }2434    }24352436    pwInp.addEventListener("keydown", (e) => {2437      e.stopPropagation();2438      if (e.key === "Enter") void tryUnlock();2439    });2440    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2441    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2442    unlockBtn.addEventListener("click", () => void tryUnlock());24432444    wrap.append(head, pwInp, errEl, unlockBtn);2445    container.appendChild(wrap);24462447    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2448    // the page reclaims focus from our Shadow DOM input before the user can2449    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2450    // Instead: intercept keystrokes at the document capture phase — this runs2451    // before any page handler regardless of which element technically has2452    // OS focus — and route them into our input.2453    const captureKeydown = (e: KeyboardEvent) => {2454      if (!host.isConnected) {2455        document.removeEventListener("keydown", captureKeydown, true);2456        return;2457      }2458      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2459      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2460      // Intercept before page handlers and give our input focus.2461      e.stopImmediatePropagation();2462      if (e.key === "Escape") { dismiss(true); return; }2463      if (e.key === "Enter") { void tryUnlock(); return; }2464      // For all other printable/editing keys, ensure our input has focus so2465      // the browser delivers the keystroke there naturally.2466      if (document.activeElement !== host) {2467        pwInp.focus({ preventScroll: true });2468      }2469    };2470    captureKeydownRef = captureKeydown;2471    document.addEventListener("keydown", captureKeydown, true);24722473    // Best-effort focus on open — may be overridden by page focus trap,2474    // but the capture listener above handles typing regardless.2475    pwInp.focus({ preventScroll: true });2476    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2477  }24782479  function handleKeyDown(e: KeyboardEvent) {2480    if (options.locked) {2481      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2482      return;2483    }2484    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2485      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2486      return;2487    }2488    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2489    const count = allEntryEls.length;2490    if (document.activeElement === searchInput) {2491      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2492      if (count === 0) return;2493      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2494    }2495    if (count === 0) return;2496    switch (e.key) {2497      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2498      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2499      case "Enter": {2500        if (focusedIndex >= 0) {2501          const el = allEntryEls[focusedIndex] as HTMLElement;2502          const id = el.dataset.id;2503          if (id) { onSelect(id); dismiss(); }2504          else if (el.classList.contains("is-new") || !id) {2505            // "New entry" row (last item, no data-id)2506            showCreateForm();2507          }2508        }2509        break;2510      }2511      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2512    }2513  }25142515  document.addEventListener("keydown", handleKeyDown);25162517  document.body.appendChild(host);25182519  function updatePosition() {2520    const r = anchorEl.getBoundingClientRect();2521    host.style.top = `${r.bottom + window.scrollY + 5}px`;2522    host.style.left = `${r.left + window.scrollX}px`;2523  }2524  // These bindings are referenced from renderLocked()/dismiss() — they MUST2525  // be initialized before renderLocked() runs, or the synchronous assignment2526  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2527  // and throws ReferenceError. The throw lands after the popup is rendered2528  // but before showAutofillSelector returns its dismiss handle, leaving an2529  // orphan host in the DOM (which is what caused the locked-popup stacking2530  // and missing autofocus on every click).2531  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2532  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);25332534  if (options.locked) {2535    renderLocked();2536  } else if (options.isSignup && options.savedIdentities) {2537    // State 10: identity helper — signup form detected, show derived2538    // identity list (emails then usernames) instead of vault entry list.2539    renderIdentityHelper();2540  } else if (entries.length === 1 && !options.isSignup) {2541    // Silver platter (State 1): single domain match → focused fill view.2542    // Multi-match goes through renderList instead.2543    renderSilverPlatter(entries[0]!);2544  } else {2545    renderList();2546  }25472548  let exitScheduled = false;2549  function dismiss(userAction = false) {2550    // Idempotent: dismiss() can be called from multiple paths (Escape,2551    // outside click, entry select, fill success, host page nav). The exit2552    // animation must only play once and host.remove() must run exactly once.2553    if (exitScheduled) return;2554    exitScheduled = true;2555    // Detach listeners synchronously so nothing can re-trigger during the2556    // 130ms exit window (a focusin firing here would race against the2557    // dismiss-lock work in Pass 2).2558    stopObserving();2559    document.removeEventListener("click", outsideClick, { capture: true });2560    document.removeEventListener("keydown", handleKeyDown);2561    if (captureKeydownRef) {2562      document.removeEventListener("keydown", captureKeydownRef, true);2563      captureKeydownRef = null;2564    }2565    for (const cleanup of cleanupHooks) {2566      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2567    }2568    if (userAction) options.onDismiss?.();2569    container.classList.add("is-exiting");2570    setTimeout(() => host.remove(), 130);2571  }25722573  function outsideClick(ev: MouseEvent) {2574    const path = ev.composedPath();2575    // Never dismiss when clicking the anchor field itself — that click is2576    // what triggered the selector to open, and the user may click the field2577    // again to re-focus it without intending to close the selector.2578    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2579  }2580  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2581  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);25822583  return dismiss;2584}25852586export interface CardSelectorEntry {2587  id: string;2588  title: string;2589  cardholderName?: string;2590  last4?: string;2591  expMonth?: string;2592  expYear?: string;2593  network?: import("../shared/types").CardNetwork;2594}25952596interface CardSelectorOptions {2597  domain?: string;2598  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2599  onFill: (entry: import("../shared/types").VaultEntry) => void;2600  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2601  onDismiss?: () => void;2602}26032604/**2605 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2606 * passkey create or get. Renders as a fixed-position floating popup (no2607 * field anchor needed — passkeys don't require a focused input). Uses the2608 * same theme tokens and entrance animation as all other inline popup states.2609 */2610export function showPasskeyProGate(): void {2611  const domain = location.hostname.replace(/^www\./, "");26122613  const host = document.createElement("div");2614  host.setAttribute("data-peach-passkey-gate", "1");2615  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2616  const shadow = host.attachShadow({ mode: "closed" });26172618  const style = document.createElement("style");2619  style.textContent = `2620    :host { all: initial; }2621    .gate-wrap {2622      position: fixed;2623      top: 50%;2624      left: 50%;2625      transform: translate(-50%, -50%);2626      width: 280px;2627      pointer-events: auto;2628      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2629    }2630    @keyframes g-in {2631      from { opacity:0; transform: translate(-50%,-52%); }2632      to   { opacity:1; transform: translate(-50%,-50%); }2633    }2634    .gate-wrap.is-exiting {2635      animation: g-out 130ms ease-in forwards;2636    }2637    @keyframes g-out {2638      to { opacity:0; transform: translate(-50%,-52%); }2639    }2640    .gate {2641      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2642      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2643      border-radius: 12px;2644      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2645      padding: 16px;2646      font-family: Inter, sans-serif;2647    }2648    .gate-header {2649      display: flex;2650      align-items: center;2651      gap: 7px;2652      margin-bottom: 12px;2653      padding-bottom: 10px;2654      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2655    }2656    .gate-domain {2657      font-size: 12px;2658      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2659      font-family: "IBM Plex Mono", monospace;2660      overflow: hidden;2661      text-overflow: ellipsis;2662      white-space: nowrap;2663    }2664    .gate-title {2665      font-size: 14px;2666      font-weight: 500;2667      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2668      margin-bottom: 6px;2669    }2670    .gate-subtitle {2671      font-size: 12px;2672      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2673      line-height: 1.5;2674      margin-bottom: 14px;2675    }2676    .gate-btn {2677      display: block;2678      width: 100%;2679      padding: 9px 0;2680      border-radius: 8px;2681      border: none;2682      cursor: pointer;2683      font-size: 13px;2684      font-family: Inter, sans-serif;2685      font-weight: 500;2686      transition: opacity 100ms;2687      margin-bottom: 7px;2688      text-align: center;2689    }2690    .gate-btn:last-child { margin-bottom: 0; }2691    .gate-btn--accent {2692      background: ${accentHex};2693      color: #fff;2694    }2695    .gate-btn--accent:hover { opacity: 0.88; }2696    .gate-btn--ghost {2697      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2698      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2699    }2700    .gate-btn--ghost:hover { opacity: 0.75; }2701    .backdrop {2702      position: fixed;2703      inset: 0;2704      pointer-events: auto;2705    }2706  `;2707  shadow.appendChild(style);27082709  const backdrop = document.createElement("div");2710  backdrop.className = "backdrop";2711  shadow.appendChild(backdrop);27122713  const wrap = document.createElement("div");2714  wrap.className = "gate-wrap";2715  shadow.appendChild(wrap);27162717  const gate = document.createElement("div");2718  gate.className = "gate";2719  wrap.appendChild(gate);27202721  // Header: peach icon + domain2722  const header = document.createElement("div");2723  header.className = "gate-header";2724  const icon = document.createElement("span");2725  icon.innerHTML = peachIconSvg();2726  const domainEl = document.createElement("span");2727  domainEl.className = "gate-domain";2728  domainEl.textContent = domain;2729  header.append(icon, domainEl);2730  gate.appendChild(header);27312732  const title = document.createElement("div");2733  title.className = "gate-title";2734  title.textContent = "Passkeys are part of Peach Pro.";2735  gate.appendChild(title);27362737  const subtitle = document.createElement("div");2738  subtitle.className = "gate-subtitle";2739  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2740  gate.appendChild(subtitle);27412742  const upgradeBtn = document.createElement("button");2743  upgradeBtn.className = "gate-btn gate-btn--accent";2744  upgradeBtn.type = "button";2745  upgradeBtn.textContent = "Upgrade to Pro";2746  gate.appendChild(upgradeBtn);27472748  const laterBtn = document.createElement("button");2749  laterBtn.className = "gate-btn gate-btn--ghost";2750  laterBtn.type = "button";2751  laterBtn.textContent = "Not right now";2752  gate.appendChild(laterBtn);27532754  function dismiss() {2755    wrap.classList.add("is-exiting");2756    setTimeout(() => host.remove(), 130);2757  }27582759  upgradeBtn.addEventListener("click", () => {2760    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2761    dismiss();2762  });2763  laterBtn.addEventListener("click", dismiss);2764  backdrop.addEventListener("click", dismiss);27652766  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2767    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2768  });27692770  document.body.appendChild(host);2771}27722773/**2774 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2775 * detector sees the page invoke navigator.credentials.create(); content/index.ts2776 * checks vault + decline state then calls this. "Save passkey to Peach"2777 * initiates the popup-context credential flow; "Not now" records a 30-day2778 * decline for the domain so we don't re-show on every page reload.2779 */2780export function showPasskeyRegistrationOffer(args: {2781  rpId: string;2782  rpName?: string;2783  userName?: string;2784  userDisplayName?: string;2785}): void {2786  const domain = location.hostname.replace(/^www\./, "");2787  const displayName = args.rpName || domain;27882789  const host = document.createElement("div");2790  host.setAttribute("data-peach-passkey-offer", "1");2791  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2792  const shadow = host.attachShadow({ mode: "closed" });27932794  const style = document.createElement("style");2795  style.textContent = `2796    :host { all: initial; }2797    .offer-wrap {2798      position: fixed;2799      top: 16px;2800      right: 16px;2801      width: 320px;2802      pointer-events: auto;2803      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2804    }2805    @keyframes o-in {2806      from { opacity: 0; transform: translateY(-6px); }2807      to   { opacity: 1; transform: translateY(0); }2808    }2809    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2810    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2811    .offer {2812      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2813      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2814      border-radius: 12px;2815      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2816      padding: 14px 14px 12px;2817      font-family: Inter, sans-serif;2818      position: relative;2819    }2820    .offer-close {2821      position: absolute;2822      top: 8px;2823      right: 8px;2824      width: 18px;2825      height: 18px;2826      border: none;2827      background: transparent;2828      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2829      cursor: pointer;2830      font-size: 14px;2831      line-height: 1;2832      padding: 0;2833    }2834    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2835    .offer-header {2836      display: flex;2837      align-items: center;2838      gap: 7px;2839      margin-bottom: 8px;2840      padding-bottom: 8px;2841      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2842    }2843    .offer-domain {2844      font-size: 12px;2845      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2846      font-family: "IBM Plex Mono", monospace;2847      overflow: hidden;2848      text-overflow: ellipsis;2849      white-space: nowrap;2850    }2851    .offer-title {2852      font-size: 13px;2853      font-weight: 500;2854      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2855      margin-bottom: 4px;2856    }2857    .offer-subtitle {2858      font-size: 11px;2859      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2860      line-height: 1.45;2861      margin-bottom: 12px;2862    }2863    .offer-btn {2864      display: block;2865      width: 100%;2866      padding: 8px 0;2867      border-radius: 7px;2868      border: none;2869      cursor: pointer;2870      font-size: 12px;2871      font-family: Inter, sans-serif;2872      font-weight: 500;2873      transition: opacity 100ms;2874      margin-bottom: 6px;2875      text-align: center;2876    }2877    .offer-btn:last-child { margin-bottom: 0; }2878    .offer-btn--accent { background: ${accentHex}; color: #fff; }2879    .offer-btn--accent:hover { opacity: 0.88; }2880    .offer-btn--ghost {2881      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2882      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2883    }2884    .offer-btn--ghost:hover { opacity: 0.75; }2885  `;2886  shadow.appendChild(style);28872888  const wrap = document.createElement("div");2889  wrap.className = "offer-wrap";2890  shadow.appendChild(wrap);28912892  const offer = document.createElement("div");2893  offer.className = "offer";2894  wrap.appendChild(offer);28952896  const closeBtn = document.createElement("button");2897  closeBtn.className = "offer-close";2898  closeBtn.type = "button";2899  closeBtn.setAttribute("aria-label", "Dismiss");2900  closeBtn.textContent = "✕";2901  offer.appendChild(closeBtn);29022903  const header = document.createElement("div");2904  header.className = "offer-header";2905  const icon = document.createElement("span");2906  icon.innerHTML = peachIconSvg();2907  const domainEl = document.createElement("span");2908  domainEl.className = "offer-domain";2909  domainEl.textContent = domain;2910  header.append(icon, domainEl);2911  offer.appendChild(header);29122913  const title = document.createElement("div");2914  title.className = "offer-title";2915  title.textContent = "This site supports passkeys.";2916  offer.appendChild(title);29172918  const subtitle = document.createElement("div");2919  subtitle.className = "offer-subtitle";2920  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2921  offer.appendChild(subtitle);29222923  const saveBtn = document.createElement("button");2924  saveBtn.className = "offer-btn offer-btn--accent";2925  saveBtn.type = "button";2926  saveBtn.textContent = "Save passkey to Peach";2927  offer.appendChild(saveBtn);29282929  const laterBtn = document.createElement("button");2930  laterBtn.className = "offer-btn offer-btn--ghost";2931  laterBtn.type = "button";2932  laterBtn.textContent = "Not now";2933  offer.appendChild(laterBtn);29342935  function dismiss(decline: boolean) {2936    if (decline) {2937      chrome.runtime.sendMessage({2938        type: "PASSKEY_OFFER_DECLINE",2939        payload: { domain },2940      }).catch(() => {});2941    }2942    wrap.classList.add("is-exiting");2943    setTimeout(() => host.remove(), 130);2944  }29452946  saveBtn.addEventListener("click", () => {2947    chrome.runtime.sendMessage({2948      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2949      payload: {2950        rpId: args.rpId,2951        rpName: args.rpName ?? displayName,2952        userName: args.userName ?? "user",2953        userDisplayName: args.userDisplayName,2954      },2955    }).catch(() => {});2956    dismiss(false);2957  });2958  laterBtn.addEventListener("click", () => dismiss(true));2959  closeBtn.addEventListener("click", () => dismiss(true));29602961  document.body.appendChild(host);2962}29632964/**2965 * State 11 — passkey available indicator. Shown when the user lands on a2966 * domain for which they already have a stored passkey. Tells them where to2967 * find it (the entry already shows in the vault list); the "Sign in with2968 * passkey" button opens the popup so they can use the platform authenticator2969 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2970 * the actual sign-in transparently, so this banner is informational only.2971 */2972export function showPasskeyAvailable(args: {2973  rpId: string;2974  userName: string;2975  fromBrowser?: "chrome" | "firefox";2976  currentBrowser?: "chrome" | "firefox" | "unknown";2977}): void {2978  const domain = location.hostname.replace(/^www\./, "");2979  const crossBrowser =2980    args.fromBrowser &&2981    args.currentBrowser &&2982    args.currentBrowser !== "unknown" &&2983    args.fromBrowser !== args.currentBrowser;29842985  const host = document.createElement("div");2986  host.setAttribute("data-peach-passkey-available", "1");2987  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2988  const shadow = host.attachShadow({ mode: "closed" });29892990  const style = document.createElement("style");2991  style.textContent = `2992    :host { all: initial; }2993    .avail-wrap {2994      position: fixed;2995      top: 16px;2996      right: 16px;2997      width: 320px;2998      pointer-events: auto;2999      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3000    }3001    @keyframes a-in {3002      from { opacity: 0; transform: translateY(-6px); }3003      to   { opacity: 1; transform: translateY(0); }3004    }3005    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3006    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3007    .avail {3008      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3009      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3010      border-radius: 12px;3011      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3012      padding: 14px 14px 12px;3013      font-family: Inter, sans-serif;3014      position: relative;3015    }3016    .avail-close {3017      position: absolute;3018      top: 8px;3019      right: 8px;3020      width: 18px;3021      height: 18px;3022      border: none;3023      background: transparent;3024      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3025      cursor: pointer;3026      font-size: 14px;3027      line-height: 1;3028      padding: 0;3029    }3030    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3031    .avail-header {3032      display: flex;3033      align-items: center;3034      gap: 7px;3035      margin-bottom: 8px;3036      padding-bottom: 8px;3037      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3038    }3039    .avail-domain {3040      font-size: 12px;3041      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3042      font-family: "IBM Plex Mono", monospace;3043    }3044    .avail-label {3045      font-size: 9px;3046      letter-spacing: 0.16em;3047      text-transform: uppercase;3048      color: ${accentHex};3049      margin-bottom: 4px;3050    }3051    .avail-user {3052      font-size: 13px;3053      font-weight: 500;3054      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3055      margin-bottom: 12px;3056      overflow: hidden;3057      text-overflow: ellipsis;3058      white-space: nowrap;3059    }3060    .avail-cross {3061      font-size: 11px;3062      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3063      line-height: 1.45;3064      margin-bottom: 12px;3065      padding: 8px;3066      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3067      border-radius: 6px;3068    }3069    .avail-btn {3070      display: block;3071      width: 100%;3072      padding: 8px 0;3073      border-radius: 7px;3074      border: none;3075      cursor: pointer;3076      font-size: 12px;3077      font-family: Inter, sans-serif;3078      font-weight: 500;3079      transition: opacity 100ms;3080      margin-bottom: 6px;3081      text-align: center;3082    }3083    .avail-btn:last-child { margin-bottom: 0; }3084    .avail-btn--accent { background: ${accentHex}; color: #fff; }3085    .avail-btn--accent:hover { opacity: 0.88; }3086    .avail-btn--ghost {3087      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3088      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3089    }3090    .avail-btn--ghost:hover { opacity: 0.75; }3091  `;3092  shadow.appendChild(style);30933094  const wrap = document.createElement("div");3095  wrap.className = "avail-wrap";3096  shadow.appendChild(wrap);30973098  const avail = document.createElement("div");3099  avail.className = "avail";3100  wrap.appendChild(avail);31013102  const closeBtn = document.createElement("button");3103  closeBtn.className = "avail-close";3104  closeBtn.type = "button";3105  closeBtn.setAttribute("aria-label", "Dismiss");3106  closeBtn.textContent = "✕";3107  avail.appendChild(closeBtn);31083109  const header = document.createElement("div");3110  header.className = "avail-header";3111  const icon = document.createElement("span");3112  icon.innerHTML = peachIconSvg();3113  const domainEl = document.createElement("span");3114  domainEl.className = "avail-domain";3115  domainEl.textContent = domain;3116  header.append(icon, domainEl);3117  avail.appendChild(header);31183119  const label = document.createElement("div");3120  label.className = "avail-label";3121  label.textContent = "PASSKEY";3122  avail.appendChild(label);31233124  const user = document.createElement("div");3125  user.className = "avail-user";3126  user.textContent = args.userName;3127  avail.appendChild(user);31283129  if (crossBrowser) {3130    const cross = document.createElement("div");3131    cross.className = "avail-cross";3132    cross.textContent =3133      args.fromBrowser === "chrome"3134        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3135        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3136    avail.appendChild(cross);3137  }31383139  const signInBtn = document.createElement("button");3140  signInBtn.className = "avail-btn avail-btn--accent";3141  signInBtn.type = "button";3142  signInBtn.textContent = "Sign in with passkey";3143  avail.appendChild(signInBtn);31443145  const passwordBtn = document.createElement("button");3146  passwordBtn.className = "avail-btn avail-btn--ghost";3147  passwordBtn.type = "button";3148  passwordBtn.textContent = "Use password instead";3149  avail.appendChild(passwordBtn);31503151  function dismiss() {3152    wrap.classList.add("is-exiting");3153    setTimeout(() => host.remove(), 130);3154  }31553156  signInBtn.addEventListener("click", () => {3157    // On Chrome: the user clicking the page's own Sign-in button is what3158    //   triggers webAuthenticationProxy → existing background flow handles it.3159    //   Our button just dismisses since the page itself drives auth.3160    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3161    //   and surface the entry for manual reference (popup view).3162    dismiss();3163    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3164  });3165  passwordBtn.addEventListener("click", dismiss);3166  closeBtn.addEventListener("click", dismiss);31673168  document.body.appendChild(host);3169}31703171/**3172 * State 7 — card silver platter. Single-card focused fill view rendered3173 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3174 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3175 * so card and login flows render identically. Multi-card list view is a3176 * follow-up; today this picks the first card.3177 */3178export function showCardSelector(3179  anchorEl: HTMLInputElement,3180  cards: CardSelectorEntry[],3181  options: CardSelectorOptions3182): () => void {3183  if (cards.length === 0) return () => {};3184  const card = cards[0]!;31853186  const host = document.createElement("div");3187  host.style.cssText = "position: absolute; z-index: 2147483647;";3188  host.style.setProperty("--peach-accent", accentHex);3189  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3190  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3191  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3192  const shadow = host.attachShadow({ mode: "closed" });31933194  const style = shadow.appendChild(document.createElement("style"));3195  style.textContent = SELECTOR_STYLES;31963197  const rect = anchorEl.getBoundingClientRect();3198  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3199  host.style.left = `${rect.left + window.scrollX}px`;3200  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;32013202  const container = shadow.appendChild(document.createElement("div"));3203  container.className = "peach-inline-popup";3204  container.setAttribute("data-theme", popupTheme);32053206  // Domain header — eyebrow communicates the card context, not the site3207  const domHdr = document.createElement("div");3208  domHdr.className = "domain-header";3209  const eyebrow = document.createElement("div");3210  eyebrow.className = "domain-eyebrow";3211  eyebrow.textContent = "Pay with Peach";3212  const domName = document.createElement("div");3213  domName.className = "domain-name";3214  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3215  domHdr.append(eyebrow, domName);3216  container.appendChild(domHdr);32173218  const platter = document.createElement("div");3219  platter.className = "card-platter";32203221  if (card.network && card.network !== "unknown") {3222    const net = document.createElement("div");3223    net.className = "cp-network";3224    net.textContent = card.network;3225    platter.appendChild(net);3226  }32273228  const nick = document.createElement("div");3229  nick.className = "cp-nickname";3230  nick.textContent = card.title;3231  platter.appendChild(nick);32323233  if (card.last4) {3234    const l4 = document.createElement("div");3235    l4.className = "cp-last4";3236    l4.textContent = `•••• ${card.last4}`;3237    platter.appendChild(l4);3238  }32393240  const meta = document.createElement("div");3241  meta.className = "cp-meta";3242  if (card.cardholderName) {3243    const name = document.createElement("span");3244    name.textContent = card.cardholderName;3245    meta.appendChild(name);3246  }3247  if (card.expMonth && card.expYear) {3248    if (card.cardholderName) {3249      const sep = document.createElement("span");3250      sep.className = "cp-meta-sep";3251      sep.textContent = "·";3252      meta.appendChild(sep);3253    }3254    const exp = document.createElement("span");3255    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3256    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3257    meta.appendChild(exp);3258  }3259  if (meta.childElementCount > 0) platter.appendChild(meta);32603261  const fillWrap = document.createElement("div");3262  fillWrap.className = "cp-fill-wrap";3263  const fillBtn = document.createElement("button");3264  fillBtn.className = "sp-fill-btn";3265  fillBtn.type = "button";3266  fillBtn.textContent = "Fill card details";3267  fillBtn.addEventListener("click", async () => {3268    if (fillBtn.disabled) return;3269    fillBtn.disabled = true;3270    fillBtn.classList.add("filled");3271    fillBtn.innerHTML = checkSvgStr();3272    const resp = await chrome.runtime.sendMessage({3273      type: "GET_ENTRY_FOR_FILL",3274      payload: { id: card.id },3275    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3276    if (resp?.ok && resp.data) options.onFill(resp.data);3277    setTimeout(() => dismiss(), 400);3278  });3279  fillWrap.appendChild(fillBtn);3280  platter.appendChild(fillWrap);32813282  // Secondary actions — copy number, copy CVC, dismiss3283  const actions = document.createElement("div");3284  actions.className = "sp-actions";32853286  function flashBtn(b: HTMLButtonElement) {3287    b.classList.add("flashed");3288    setTimeout(() => b.classList.remove("flashed"), 700);3289  }32903291  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3292    const resp = await chrome.runtime.sendMessage({3293      type: "GET_ENTRY_FOR_FILL",3294      payload: { id: card.id },3295    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3296    return resp?.ok && resp.data ? resp.data : null;3297  }32983299  const copyNum = document.createElement("button");3300  copyNum.className = "sp-action-btn";3301  copyNum.type = "button";3302  copyNum.title = "Copy card number";3303  copyNum.textContent = "Copy number";3304  copyNum.addEventListener("click", async (e) => {3305    e.stopPropagation();3306    const full = await fetchFullCard();3307    if (!full?.cardNumber) return;3308    let alreadyWritten = false;3309    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}3310    await chrome.runtime.sendMessage({3311      type: "COPY",3312      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3313    }).catch(() => {});3314    flashBtn(copyNum);3315  });3316  actions.appendChild(copyNum);33173318  const copyCvc = document.createElement("button");3319  copyCvc.className = "sp-action-btn";3320  copyCvc.type = "button";3321  copyCvc.title = "Copy CVC";3322  copyCvc.textContent = "Copy CVC";3323  copyCvc.addEventListener("click", async (e) => {3324    e.stopPropagation();3325    const full = await fetchFullCard();3326    if (!full?.cvc) return;3327    let alreadyWritten = false;3328    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}3329    await chrome.runtime.sendMessage({3330      type: "COPY",3331      payload: { text: full.cvc, label: "CVC", alreadyWritten },3332    }).catch(() => {});3333    flashBtn(copyCvc);3334  });3335  actions.appendChild(copyCvc);33363337  const closeBtn = document.createElement("button");3338  closeBtn.className = "sp-action-btn";3339  closeBtn.type = "button";3340  closeBtn.title = "Dismiss";3341  closeBtn.textContent = "✕";3342  closeBtn.addEventListener("click", (e) => {3343    e.stopPropagation();3344    dismiss(true);3345  });3346  actions.appendChild(closeBtn);33473348  platter.appendChild(actions);3349  container.appendChild(platter);33503351  document.body.appendChild(host);3352  function updatePosition() {3353    const r = anchorEl.getBoundingClientRect();3354    host.style.top = `${r.bottom + window.scrollY + 5}px`;3355    host.style.left = `${r.left + window.scrollX}px`;3356  }3357  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);33583359  function onKeyDown(e: KeyboardEvent) {3360    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3361  }3362  document.addEventListener("keydown", onKeyDown);33633364  let exitScheduled = false;3365  function dismiss(userAction = false) {3366    if (exitScheduled) return;3367    exitScheduled = true;3368    stopObserving();3369    document.removeEventListener("click", outsideClick, { capture: true });3370    document.removeEventListener("keydown", onKeyDown);3371    if (userAction) options.onDismiss?.();3372    container.classList.add("is-exiting");3373    setTimeout(() => host.remove(), 130);3374  }33753376  function outsideClick(ev: MouseEvent) {3377    const path = ev.composedPath();3378    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3379  }3380  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33813382  return dismiss;3383}