inject.ts

132.3 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-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }986  .identity-alt-input-wrap.open { display: flex; }987  .identity-alt-input {988    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;989    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);990    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;991    outline: none; transition: border-color 120ms;992  }993  .identity-alt-input:focus {994    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);995    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);996  }997  .identity-alt-confirm {998    height: 32px; padding: 0 12px; border-radius: 7px; border: none;999    background: var(--peach-accent); color: #fff; font-size: 12px;1000    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1001  }1002  /* ── Generator view (after identity picked) ────────────────── */1003  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1004  .gen-confirmed {1005    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1006    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1007    border-radius: 8px;1008  }1009  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1010  .gen-confirmed-val {1011    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1012    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1013  }1014  .gen-label {1015    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1016    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1017  }1018  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1019  .gen-pw-val {1020    flex: 1; padding: 8px 10px; border-radius: 7px;1021    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1022    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1023    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1024  }1025  .gen-regen-btn {1026    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1027    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1028    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1029    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1030  }1031  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1032  .gen-fill-btn {1033    padding: 10px; border-radius: 8px; border: none;1034    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1035    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1036    transition: filter 120ms ease, transform 80ms ease;1037  }1038  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1039  .gen-fill-btn:active { transform: translateY(0); }10401041  /* ── Smart password generator (parity with main UI compact mode) ─── */1042  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1043  .pwgen-display-row {1044    display: flex; align-items: center; gap: 6px;1045    padding: 8px 10px; border-radius: 7px;1046    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1047  }1048  .pwgen-output {1049    flex: 1; min-width: 0; width: 0;1050    font-family: "IBM Plex Mono", monospace; font-size: 12px;1051    color: var(--peach-text);1052    background: transparent; border: none; outline: none; padding: 0;1053  }1054  .pwgen-icon-btn {1055    flex-shrink: 0;1056    width: 26px; height: 26px;1057    display: inline-flex; align-items: center; justify-content: center;1058    background: transparent; border: 1px solid var(--peach-input-border);1059    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1060    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1061  }1062  .pwgen-icon-btn:hover {1063    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1064    color: var(--peach-accent);1065    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1066  }1067  .pwgen-icon-btn.is-copied {1068    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1069    color: var(--peach-accent);1070    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1071  }1072  .pwgen-controls-row {1073    display: flex; align-items: center; gap: 8px;1074    flex-wrap: wrap;1075  }1076  .pwgen-slider {1077    flex: 1; min-width: 110px;1078    accent-color: var(--peach-accent);1079    cursor: pointer; height: 2px; background: transparent;1080  }1081  .pwgen-len-num {1082    font-family: "IBM Plex Mono", monospace; font-size: 11px;1083    color: var(--peach-accent); min-width: 22px; text-align: right;1084  }1085  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1086  .pwgen-len-input {1087    font-family: "IBM Plex Mono", monospace; font-size: 11px;1088    color: var(--peach-accent); width: 28px; text-align: right;1089    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1090    outline: none; padding: 0; min-width: 22px;1091  }1092  @keyframes identity-suggest-in {1093    from { opacity: 0; transform: translateY(-4px); }1094    to   { opacity: 1; transform: none; }1095  }1096  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1097    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1098  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1099  .identity-collapse-btn {1100    margin-left: auto; background: transparent; border: none; cursor: pointer;1101    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1102    line-height: 0; border-radius: 3px;1103    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1104  }1105  .identity-collapse-btn:hover { color: var(--peach-text); }1106  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1107  .identity-rows { display: grid; grid-template-rows: 1fr;1108    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1109  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1110  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1111    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent; }1112  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1113  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1114  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1115  .identity-filter-pill {1116    padding: 2px 7px; border-radius: 999px;1117    border: 1px solid var(--peach-input-border);1118    background: transparent; color: var(--peach-text-muted);1119    font-family: "IBM Plex Mono", monospace; font-size: 9px;1120    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1121  }1122  .identity-filter-pill.is-on {1123    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1124    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1125    color: var(--peach-accent);1126  }1127  .identity-suggest-row {1128    display: flex; align-items: center; gap: 5px;1129    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1130    background: transparent; cursor: pointer; text-align: left;1131    transition: background 80ms;1132  }1133  .identity-suggest-row:hover,1134  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1135  .identity-suggest-val {1136    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1137    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1138  }1139  .identity-suggest-type {1140    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1141    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1142  }1143  .identity-suggest-type--email {1144    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1145    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1146  }1147  .identity-suggest-type--username {1148    color: var(--peach-text-muted);1149    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1150  }1151  .identity-suggest-meta {1152    font-family: "IBM Plex Mono", monospace; font-size: 9px;1153    color: var(--peach-text-muted); flex-shrink: 0;1154  }1155  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1156  .pwgen-pill {1157    padding: 3px 8px; border-radius: 999px;1158    border: 1px solid var(--peach-input-border);1159    background: transparent; color: var(--peach-text-muted);1160    font-family: "IBM Plex Mono", monospace; font-size: 9px;1161    letter-spacing: 0.06em; cursor: pointer;1162    transition: all 130ms ease;1163  }1164  .pwgen-pill.is-on {1165    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1166    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1167    color: var(--peach-accent);1168  }1169  .pwgen-pill:not(.is-on):hover {1170    color: var(--peach-text-dim);1171    border-color: var(--peach-text-muted);1172  }1173  .pwgen-policy-hint {1174    font-size: 10px; color: var(--peach-text-muted);1175    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1176    line-height: 1.3;1177  }1178  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }11791180  /* ── Save offer (after password filled) ───────────────────── */1181  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1182  .save-offer-title {1183    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1184  }1185  .save-offer-row {1186    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1187    border-radius: 7px; background: var(--peach-input-bg);1188    border: 1px solid var(--peach-input-border);1189  }1190  .save-offer-lbl {1191    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1192    font-family: "IBM Plex Mono", monospace;1193  }1194  .save-offer-val {1195    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1196    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1197  }1198  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1199  .save-offer-save {1200    flex: 1; padding: 9px; border-radius: 8px; border: none;1201    background: var(--peach-accent); color: #fff; font-size: 13px;1202    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1203  }1204  .save-offer-save:hover { filter: brightness(1.08); }1205  .save-offer-skip {1206    flex: 1; padding: 9px; border-radius: 8px; border: none;1207    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1208    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1209    font-family: Inter, sans-serif; transition: background 100ms ease;1210  }1211  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1212`;12131214export function showAutofillSelector(1215  anchorEl: HTMLInputElement,1216  entries: SelectorEntry[],1217  onSelect: (id: string) => void,1218  options: SelectorOptions = {}1219): () => void {1220  const host = document.createElement("div");1221  host.style.cssText = "position: absolute; z-index: 2147483647;";1222  host.style.setProperty("--peach-accent", accentHex);1223  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1224  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1225  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1226  const shadow = host.attachShadow({ mode: "closed" });12271228  const style = shadow.appendChild(document.createElement("style"));1229  style.textContent = SELECTOR_STYLES;12301231  const rect = anchorEl.getBoundingClientRect();1232  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1233  host.style.left = `${rect.left + window.scrollX}px`;1234  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1235  // wide single-input fields (e.g. centered email input on signup pages).1236  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;12371238  const container = shadow.appendChild(document.createElement("div"));1239  container.className = "peach-inline-popup";1240  container.setAttribute("data-theme", popupTheme);12411242  const searchableEntries = options.searchableEntries ?? [];1243  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12441245  let query = "";1246  let focusedIndex = -1;1247  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1248  let searchInput: HTMLInputElement | null = null;1249  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1250  // setInterval. Add to this list — don't fan out the dismiss function.1251  const cleanupHooks: Array<() => void> = [];12521253  // Smooth height transitions whenever content changes height.1254  // ResizeObserver fires on natural height changes; we freeze the old height,1255  // then animate to the new one so the surface never jumps.1256  {1257    let prevH = 0;1258    let blocked = false;1259    const heightRo = new ResizeObserver(([entry]) => {1260      if (blocked) return;1261      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1262      if (prevH > 0 && Math.abs(h - prevH) > 1) {1263        blocked = true;1264        container.style.height = `${prevH}px`;1265        requestAnimationFrame(() => requestAnimationFrame(() => {1266          container.style.height = `${h}px`;1267          prevH = h;1268          const onEnd = (e: TransitionEvent) => {1269            if (e.propertyName !== "height") return;1270            container.style.height = "";1271            blocked = false;1272            container.removeEventListener("transitionend", onEnd);1273          };1274          container.addEventListener("transitionend", onEnd);1275        }));1276      } else {1277        prevH = h;1278      }1279    });1280    heightRo.observe(container);1281    cleanupHooks.push(() => heightRo.disconnect());1282  }12831284  // Pre-capture the anchor field value for username prefill1285  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1286  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1287  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";12881289  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1290    const seen = new Set<string>();1291    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1292  }12931294  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1295    const q = value.trim().toLowerCase();1296    const deduped = uniqueEntries(source);1297    if (!q) return deduped.slice(0, 8);1298    return deduped.filter(e =>1299      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1300    ).slice(0, 12);1301  }13021303  function activeEntries(): SelectorEntry[] {1304    // When user is typing a search, filter across all known entries (domain matches + vault)1305    if (query.trim()) {1306      const merged = uniqueEntries([...entries, ...searchableEntries]);1307      return filterEntries(merged, query);1308    }1309    // Default: show domain matches; fall back to vault search when no matches1310    if (entries.length > 0) return entries;1311    return filterEntries(searchableEntries, "").slice(0, 8);1312  }13131314  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1315    const icon = document.createElement("div");1316    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1317    if (isNew) {1318      icon.innerHTML = plusSvgStr();1319    } else {1320      // Use the generic key glyph for all entries in the page-injected selector.1321      // Avoids disclosing vault domains to any third party and avoids needing1322      // to expose the browser favicon API to page context via web_accessible_resources.1323      void url;1324      icon.innerHTML = keySvgStr();1325    }1326    return icon;1327  }13281329  function renderIdentityHelper() {1330    container.innerHTML = "";1331    const identities = options.savedIdentities ?? [];13321333    // Header: "NEW ACCOUNT" + domain name1334    const hdr = container.appendChild(document.createElement("div"));1335    hdr.className = "domain-header";1336    const eyebrow = hdr.appendChild(document.createElement("div"));1337    eyebrow.className = "domain-eyebrow";1338    eyebrow.textContent = "NEW ACCOUNT";1339    const domName = hdr.appendChild(document.createElement("div"));1340    domName.className = "domain-name";1341    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13421343    // Identity rows1344    const list = container.appendChild(document.createElement("div"));1345    list.className = "identity-list";1346    for (const id of identities) {1347      const row = list.appendChild(document.createElement("div"));1348      row.className = "peach-identity-row";1349      row.setAttribute("tabindex", "-1");1350      const val = row.appendChild(document.createElement("div"));1351      val.className = "peach-identity-value";1352      val.textContent = id.value;1353      const meta = row.appendChild(document.createElement("div"));1354      meta.className = "peach-identity-meta";1355      meta.textContent = `used ${id.useCount}×`;1356      row.addEventListener("click", () => {1357        options.onFillFields?.(id.value, "");1358        renderGenerator(id.value);1359      });1360    }13611362    // Divider before "Use a different email…"1363    if (identities.length > 0) {1364      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1365    }13661367    // "Use a different email…" expandable row1368    const altRow = container.appendChild(document.createElement("div"));1369    altRow.className = "identity-alt-row";1370    altRow.textContent = "+ Use a different email…";13711372    const altInputWrap = container.appendChild(document.createElement("div"));1373    altInputWrap.className = "identity-alt-input-wrap";1374    const altInput = altInputWrap.appendChild(document.createElement("input"));1375    altInput.className = "identity-alt-input";1376    altInput.type = "email";1377    altInput.placeholder = "[email protected]";1378    altInput.setAttribute("autocomplete", "off");1379    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1380    altConfirm.className = "identity-alt-confirm";1381    altConfirm.type = "button";1382    altConfirm.textContent = "✓";13831384    function fillCustomEmail() {1385      const v = altInput.value.trim();1386      if (!v) return;1387      options.onFillFields?.(v, "");1388      renderGenerator(v);1389    }13901391    altRow.addEventListener("click", () => {1392      altRow.style.display = "none";1393      altInputWrap.classList.add("open");1394      altInput.focus();1395    });1396    altConfirm.addEventListener("click", fillCustomEmail);1397    altInput.addEventListener("keydown", (e) => {1398      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1399    });1400  }14011402  function renderGenerator(filledEmail: string) {1403    container.innerHTML = "";1404    const sitePolicy = detectPasswordPolicy();14051406    const wrap = container.appendChild(document.createElement("div"));1407    wrap.className = "gen-view";14081409    // Header: domain + NEW ACCOUNT1410    const hdrRow = wrap.appendChild(document.createElement("div"));1411    hdrRow.className = "domain-header";1412    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1413    eyebrow2.className = "domain-eyebrow";1414    eyebrow2.textContent = "NEW ACCOUNT";1415    const domName2 = hdrRow.appendChild(document.createElement("div"));1416    domName2.className = "domain-name";1417    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14181419    // Confirmed email row1420    const conf = wrap.appendChild(document.createElement("div"));1421    conf.className = "gen-confirmed";1422    const confCheck = conf.appendChild(document.createElement("span"));1423    confCheck.className = "gen-confirmed-check";1424    confCheck.textContent = "✓";1425    const confVal = conf.appendChild(document.createElement("div"));1426    confVal.className = "gen-confirmed-val";1427    confVal.textContent = filledEmail;14281429    const lbl = wrap.appendChild(document.createElement("div"));1430    lbl.className = "gen-label";1431    lbl.textContent = "Generate a password";14321433    let currentPw = "";1434    const smartGen = createSmartGenerator({1435      policy: sitePolicy,1436      onChange: (pw) => { currentPw = pw; },1437    });1438    wrap.appendChild(smartGen.root);14391440    const fillBtn = wrap.appendChild(document.createElement("button"));1441    fillBtn.className = "gen-fill-btn";1442    fillBtn.type = "button";1443    fillBtn.textContent = "Copy & fill";1444    fillBtn.addEventListener("click", () => {1445      if (!currentPw) return;1446      options.onFillFields?.("", currentPw);1447      renderSaveOffer(filledEmail, currentPw);1448    });1449  }14501451  function renderSaveOffer(filledEmail: string, filledPassword: string) {1452    container.innerHTML = "";1453    const domain = options.domain ?? location.hostname.replace(/^www\./, "");14541455    const wrap = container.appendChild(document.createElement("div"));1456    wrap.className = "save-offer";14571458    const title = wrap.appendChild(document.createElement("div"));1459    title.className = "save-offer-title";1460    title.textContent = "Save this login to Peach?";14611462    function detailRow(label: string, value: string) {1463      const row = wrap.appendChild(document.createElement("div"));1464      row.className = "save-offer-row";1465      const lbl = row.appendChild(document.createElement("div"));1466      lbl.className = "save-offer-lbl";1467      lbl.textContent = label;1468      const val = row.appendChild(document.createElement("div"));1469      val.className = "save-offer-val";1470      val.textContent = value;1471    }14721473    detailRow("site", domain);1474    detailRow("email", filledEmail);1475    detailRow("password", "••••••••••••••••");14761477    const btns = wrap.appendChild(document.createElement("div"));1478    btns.className = "save-offer-btns";14791480    const saveBtn = btns.appendChild(document.createElement("button"));1481    saveBtn.className = "save-offer-save";1482    saveBtn.type = "button";1483    saveBtn.textContent = "Save";1484    saveBtn.addEventListener("click", async () => {1485      saveBtn.disabled = true;1486      saveBtn.textContent = "Saving…";1487      try {1488        const res = await chrome.runtime.sendMessage({1489          type: "ADD_ENTRY",1490          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1491        });1492        if ((res as { ok?: boolean }).ok) {1493          showSuccess(sTitle);1494        } else {1495          saveBtn.disabled = false;1496          saveBtn.textContent = "Save";1497        }1498      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1499    });15001501    const skipBtn = btns.appendChild(document.createElement("button"));1502    skipBtn.className = "save-offer-skip";1503    skipBtn.type = "button";1504    skipBtn.textContent = "Not now";1505    skipBtn.addEventListener("click", () => { dismiss(true); });1506  }15071508  function renderList() {1509    container.innerHTML = "";1510    focusedIndex = -1;1511    searchInput = null;15121513    const current = activeEntries();15141515    // Domain header (always show) — eyebrow + domain on the left,1516    // a "+" shortcut to the create form on the right so the user is never1517    // trapped in the search list when they want to make a new entry.1518    const domHdr = document.createElement("div");1519    domHdr.className = "domain-header";1520    const headText = document.createElement("div");1521    headText.className = "domain-header-text";1522    const eyebrow = document.createElement("div");1523    eyebrow.className = "domain-eyebrow";1524    eyebrow.textContent = options.isSignup1525      ? "Sign up as"1526      : entries.length > 0 ? "Saved for this site" : "No saved login";1527    const domName = document.createElement("div");1528    domName.className = "domain-name";1529    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1530    headText.append(eyebrow, domName);1531    domHdr.appendChild(headText);15321533    if (!options.isSignup) {1534      const addBtn = document.createElement("button");1535      addBtn.className = "domain-add-btn";1536      addBtn.type = "button";1537      addBtn.setAttribute("aria-label", "Create new entry");1538      addBtn.title = "Create new entry";1539      addBtn.textContent = "+";1540      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1541      domHdr.appendChild(addBtn);1542    }15431544    container.appendChild(domHdr);15451546    // Search — always show so user can find entries beyond the domain matches1547    const sw = document.createElement("div"); sw.className = "search-wrap";1548    searchInput = document.createElement("input");1549    searchInput.className = "search";1550    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1551    searchInput.value = query;1552    searchInput.addEventListener("input", () => {1553      query = searchInput?.value ?? "";1554      renderList();1555      searchInput?.focus();1556      searchInput?.setSelectionRange(query.length, query.length);1557    });1558    sw.appendChild(searchInput);1559    container.appendChild(sw);15601561    // Results1562    const results = document.createElement("div");1563    results.className = "results";1564    container.appendChild(results);15651566    if (current.length === 0 && entries.length > 0) {1567      // Show a hint but don't render empty entries1568    }15691570    for (let i = 0; i < current.length; i++) {1571      const e = current[i]!;1572      const entryEl = document.createElement("div");1573      entryEl.className = "entry";1574      entryEl.dataset.id = e.id;1575      entryEl.dataset.index = String(i);1576      entryEl.setAttribute("tabindex", "-1");15771578      entryEl.appendChild(makeEntryIcon(e.url));15791580      const info = document.createElement("div"); info.className = "entry-info";1581      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1582      const subEl = document.createElement("div"); subEl.className = "entry-sub";1583      const domain = e.url ? getDomainFromUrl(e.url) : "";1584      subEl.textContent = domain || e.username || "";1585      info.append(titleEl, subEl);1586      entryEl.appendChild(info);15871588      if (e.hasTotp) {1589        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1590        entryEl.appendChild(badge);1591      }1592      if (e.hasPasskey) {1593        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1594        entryEl.appendChild(badge);1595      }15961597      entryEl.addEventListener("click", () => {1598        if (options.isSignup && options.onFillFields) {1599          // Signup mode: clicking a saved identity fills the username field1600          options.onFillFields(e.username ?? "", "");1601          dismiss();1602        } else {1603          onSelect(e.id);1604          dismiss();1605        }1606      });1607      results.appendChild(entryEl);1608    }16091610    // Divider before "New entry"1611    if (current.length > 0) {1612      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1613    }16141615    // "New entry" row — always present1616    const newEl = document.createElement("div");1617    newEl.className = "entry";1618    newEl.setAttribute("tabindex", "-1");1619    newEl.appendChild(makeEntryIcon(undefined, true));16201621    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1622    const newTitle = document.createElement("div");1623    newTitle.className = "entry-title is-new";1624    newTitle.textContent = `New entry for ${sTitle}`;1625    const newSub = document.createElement("div");1626    newSub.className = "entry-sub";1627    newSub.textContent = sOrigin;1628    newInfo.append(newTitle, newSub);1629    newEl.appendChild(newInfo);1630    newEl.addEventListener("click", showCreateForm);1631    results.appendChild(newEl);16321633    // Focus search if present1634    if (searchInput) {1635      requestAnimationFrame(() => searchInput?.focus());1636    }1637  }16381639  function setFocused(idx: number) {1640    const all = container.querySelectorAll<HTMLElement>(".entry");1641    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1642    focusedIndex = idx;1643    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1644  }16451646  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1647    const typed = identities.filter(s => s.type === fieldType);1648    if (!typed.length) return;1649    let collapsed = false;1650    let suppressNextFocus = false;16511652    const list = g.appendChild(document.createElement("div"));1653    list.className = "identity-suggest-list";1654    list.style.display = "none";16551656    // Collapse toggle — sits alone now that filter pills are gone1657    const collapseRow = list.appendChild(document.createElement("div"));1658    collapseRow.className = "identity-filter-row";1659    collapseRow.style.justifyContent = "flex-end";1660    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1661    collapseBtn.type = "button";1662    collapseBtn.className = "identity-collapse-btn";1663    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>`;1664    collapseBtn.addEventListener("mousedown", (e) => {1665      e.preventDefault();1666      collapsed = !collapsed;1667      collapseBtn.classList.toggle("is-collapsed", collapsed);1668      rowsWrapper.classList.toggle("is-collapsed", collapsed);1669    });16701671    const rowsWrapper = list.appendChild(document.createElement("div"));1672    rowsWrapper.className = "identity-rows";1673    const rows = rowsWrapper.appendChild(document.createElement("div"));1674    rows.className = "identity-rows-inner";16751676    function pick(value: string) {1677      inp.value = value;1678      list.style.display = "none";1679      suppressNextFocus = true;1680      inp.focus();1681    }16821683    function render() {1684      const q = inp.value.toLowerCase();1685      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1686      rows.innerHTML = "";1687      if (!filtered.length) { list.style.display = "none"; return; }1688      for (const s of filtered) {1689        const row = rows.appendChild(document.createElement("button"));1690        row.type = "button"; row.className = "identity-suggest-row";1691        const val = row.appendChild(document.createElement("span"));1692        val.className = "identity-suggest-val"; val.textContent = s.value;1693        const meta = row.appendChild(document.createElement("span"));1694        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1695        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1696        row.addEventListener("keydown", (e) => {1697          if (e.key === "ArrowDown") {1698            e.preventDefault();1699            (row.nextElementSibling as HTMLElement | null)?.focus();1700          } else if (e.key === "ArrowUp") {1701            e.preventDefault();1702            const prev = row.previousElementSibling as HTMLElement | null;1703            if (prev) prev.focus();1704            else inp.focus();1705          } else if (e.key === "Enter" || e.key === " ") {1706            e.preventDefault();1707            pick(s.value);1708          } else if (e.key === "Escape") {1709            e.preventDefault();1710            list.style.display = "none";1711            suppressNextFocus = true;1712            inp.focus();1713          }1714        });1715        row.addEventListener("blur", (e) => {1716          const rt = (e as FocusEvent).relatedTarget as Node | null;1717          if (rt && (rt === inp || list.contains(rt))) return;1718          setTimeout(() => { list.style.display = "none"; }, 150);1719        });1720      }1721      list.style.display = "";1722    }17231724    inp.addEventListener("focus", () => {1725      if (suppressNextFocus) { suppressNextFocus = false; return; }1726      render();1727    });1728    inp.addEventListener("input", render);1729    inp.addEventListener("keydown", (e) => {1730      if (list.style.display === "none") return;1731      if (e.key === "ArrowDown" && !collapsed) {1732        e.preventDefault();1733        (rows.firstElementChild as HTMLElement | null)?.focus();1734      } else if (e.key === "Escape") {1735        e.preventDefault();1736        list.style.display = "none";1737      }1738    });1739    inp.addEventListener("blur", (e) => {1740      const rt = (e as FocusEvent).relatedTarget as Node | null;1741      if (rt && list.contains(rt)) return;1742      setTimeout(() => { list.style.display = "none"; }, 150);1743    });1744  }17451746  async function showCreateForm() {1747    currentMode = "create";1748    container.innerHTML = "";17491750    // Guard: the service worker may lock the vault between when the selector1751    // opens and when the user clicks "New entry". Show the inline unlock form1752    // instead of silently failing on save.1753    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1754    if (!statusRes?.unlocked) {1755      renderLocked();1756      return;1757    }17581759    // Detect page password policy once for this form — reused on every1760    // regenerate click so the user always gets a compliant password.1761    const sitePolicy = detectPasswordPolicy();17621763    // Fetch identities on-demand — they're passed in signup context but not1764    // in login/search context where the user still clicks "New entry".1765    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1766    if (!formIdentities.length) {1767      try {1768        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1769        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1770      } catch { /* silent fallback */ }1771    }17721773    const wrap = document.createElement("div");1774    wrap.className = "create-form-wrap";17751776    // Header1777    const head = document.createElement("div"); head.className = "create-head";1778    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1779    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>`;1780    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1781    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1782    head.append(backBtn, lbl);17831784    // Body1785    const body = document.createElement("div"); body.className = "create-body";17861787    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1788      const g = document.createElement("div"); g.className = "f-group";1789      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1790      const inp = document.createElement("input"); inp.className = "f-input";1791      g.append(l, inp); return { g, inp };1792    }17931794    // Title1795    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1796    body.appendChild(tg.g);17971798    // URL1799    const ug = fGroup("website");1800    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1801    if (loginSubdomain) {1802      const h = document.createElement("div"); h.className = "url-hint";1803      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1804    }1805    body.appendChild(ug.g);18061807    // Username — pre-fill from anchor if it doesn't look like an email1808    const xg = fGroup("username");1809    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1810    xg.inp.placeholder = "johndoe";1811    xg.inp.setAttribute("autocomplete", "off");1812    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1813    body.appendChild(xg.g);18141815    // Email — pre-fill from anchor if it looks like an email1816    const eg = fGroup("email");1817    (eg.inp as HTMLInputElement).type = "email";1818    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1819    eg.inp.placeholder = "[email protected]";1820    eg.inp.setAttribute("autocomplete", "off");1821    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1822    body.appendChild(eg.g);18231824    // Password — full smart generator with charset pills + length slider +1825    // policy hint. Mirrors the main UI's compact generator so users get the1826    // same controls inline as in the popup.1827    const pg = fGroup("password");1828    let currentPassword = prePassword || "";1829    const smartGen = createSmartGenerator({1830      policy: sitePolicy,1831      initialPassword: prePassword || undefined,1832      onChange: (pw) => { currentPassword = pw; },1833    });1834    pg.g.appendChild(smartGen.root);1835    body.appendChild(pg.g);18361837    // Save1838    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1839    saveBtn.textContent = "Save entry";1840    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1841    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1842    saveBtn.addEventListener("click", async () => {1843      const title = tg.inp.value.trim();1844      const pw = currentPassword.trim();1845      const username = xg.inp.value.trim();1846      const email = eg.inp.value.trim();1847      if (!title) {1848        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1849        showFormError("Entry needs a title");1850        return;1851      }1852      if (!pw) {1853        showFormError("Entry needs a password — tap regen to make one");1854        return;1855      }1856      errEl.style.display = "none";1857      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1858      try {1859        const res = await chrome.runtime.sendMessage({1860          type: "ADD_ENTRY",1861          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1862        });1863        if ((res as { ok?: boolean }).ok) {1864          // Fill the detected form. onFillFields uses whichever identity the1865          // page anchored on — the vault captures both username and email.1866          options.onFillFields?.(username || email, pw);1867          showSuccess(title);1868        } else {1869          const errMsg = (res as { error?: string }).error === "vault locked"1870            ? "Vault locked — open Peach to save"1871            : "Could not save entry";1872          showFormError(errMsg);1873          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1874        }1875      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1876    });1877    body.appendChild(saveBtn);1878    body.appendChild(errEl);18791880    wrap.append(head, body);1881    container.appendChild(wrap);1882    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1883  }18841885  function showSuccess(title: string) {1886    currentMode = "success";1887    container.innerHTML = "";1888    const wrap = document.createElement("div"); wrap.className = "success-wrap";1889    const ring = document.createElement("div"); ring.className = "success-ring";1890    ring.innerHTML = checkSvgStr();1891    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1892    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1893    wrap.append(ring, t, s);1894    container.appendChild(wrap);1895    setTimeout(() => dismiss(), 1600);1896  }18971898  function flashActionBtn(btn: HTMLButtonElement) {1899    btn.classList.add("flashed");1900    setTimeout(() => btn.classList.remove("flashed"), 700);1901  }19021903  function renderSilverPlatter(entry: SelectorEntry) {1904    container.innerHTML = "";1905    searchInput = null;1906    focusedIndex = -1;1907    currentMode = "silver-platter";19081909    const domHdr = document.createElement("div");1910    domHdr.className = "domain-header";1911    const headText = document.createElement("div");1912    headText.className = "domain-header-text";1913    const eyebrow = document.createElement("div");1914    eyebrow.className = "domain-eyebrow";1915    eyebrow.textContent = "Saved for this site";1916    const domName = document.createElement("div");1917    domName.className = "domain-name";1918    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1919    headText.append(eyebrow, domName);1920    domHdr.appendChild(headText);1921    if (!options.isSignup) {1922      const addBtn = document.createElement("button");1923      addBtn.className = "domain-add-btn";1924      addBtn.type = "button";1925      addBtn.setAttribute("aria-label", "Create new entry");1926      addBtn.title = "Create new entry";1927      addBtn.textContent = "+";1928      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1929      domHdr.appendChild(addBtn);1930    }1931    container.appendChild(domHdr);19321933    const platter = document.createElement("div");1934    platter.className = "silver-platter";19351936    const titleEl = document.createElement("div");1937    titleEl.className = "sp-title";1938    titleEl.textContent = entry.title;1939    platter.appendChild(titleEl);19401941    if (entry.email) {1942      const emailEl = document.createElement("div");1943      emailEl.className = "sp-identity-row";1944      const emailLbl = document.createElement("span");1945      emailLbl.className = "sp-identity-label";1946      emailLbl.textContent = "email";1947      const emailVal = document.createElement("span");1948      emailVal.className = "sp-username";1949      emailVal.textContent = entry.email;1950      emailEl.append(emailLbl, emailVal);1951      platter.appendChild(emailEl);1952    }19531954    if (entry.username) {1955      const userEl = document.createElement("div");1956      userEl.className = "sp-identity-row";1957      const userLbl = document.createElement("span");1958      userLbl.className = "sp-identity-label";1959      userLbl.textContent = entry.username.includes("@") ? "email" : "username";1960      const userVal = document.createElement("span");1961      userVal.className = "sp-username";1962      userVal.textContent = entry.username;1963      userEl.append(userLbl, userVal);1964      platter.appendChild(userEl);1965    }19661967    const fillBtn = document.createElement("button");1968    fillBtn.className = "sp-fill-btn";1969    fillBtn.type = "button";1970    fillBtn.textContent = "Fill credentials";1971    fillBtn.addEventListener("click", () => {1972      if (fillBtn.disabled) return;1973      fillBtn.disabled = true;1974      fillBtn.classList.add("filled");1975      fillBtn.innerHTML = checkSvgStr();1976      // Fire the fill, then exit via the standard exit animation. The fill1977      // itself is async (handled in index.ts) — by 400ms the form is filled1978      // and the popup begins its exit. Total dwell from click to host1979      // removal: 400ms + 130ms (exit animation) = 530ms.1980      onSelect(entry.id);1981      setTimeout(() => dismiss(), 400);1982    });1983    platter.appendChild(fillBtn);19841985    const actions = document.createElement("div");1986    actions.className = "sp-actions";19871988    if (entry.email) {1989      const copyEmail = document.createElement("button");1990      copyEmail.className = "sp-action-btn";1991      copyEmail.type = "button";1992      copyEmail.title = "Copy email";1993      copyEmail.textContent = "Copy email";1994      copyEmail.addEventListener("click", async (e) => {1995        e.stopPropagation();1996        let alreadyWritten = false;1997        try { await navigator.clipboard.writeText(entry.email!); alreadyWritten = true; } catch {}1998        await chrome.runtime.sendMessage({1999          type: "COPY",2000          payload: { text: entry.email, label: "Email", alreadyWritten },2001        }).catch(() => {});2002        flashActionBtn(copyEmail);2003      });2004      actions.appendChild(copyEmail);2005    }20062007    const copyU = document.createElement("button");2008    copyU.className = "sp-action-btn";2009    copyU.type = "button";2010    const copyULabel = entry.username?.includes("@") ? "Copy email" : "Copy username";2011    copyU.title = copyULabel;2012    copyU.textContent = copyULabel;2013    copyU.disabled = !entry.username;2014    copyU.addEventListener("click", async (e) => {2015      e.stopPropagation();2016      if (!entry.username) return;2017      let alreadyWritten = false;2018      try { await navigator.clipboard.writeText(entry.username); alreadyWritten = true; } catch {}2019      await chrome.runtime.sendMessage({2020        type: "COPY",2021        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2022      }).catch(() => {});2023      flashActionBtn(copyU);2024    });2025    actions.appendChild(copyU);20262027    const copyP = document.createElement("button");2028    copyP.className = "sp-action-btn";2029    copyP.type = "button";2030    copyP.title = "Copy password";2031    copyP.textContent = "Copy password";2032    copyP.addEventListener("click", async (e) => {2033      e.stopPropagation();2034      const resp = await chrome.runtime.sendMessage({2035        type: "GET_ENTRY_FOR_FILL",2036        payload: { id: entry.id },2037      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2038      if (!resp?.ok || !resp.data?.password) return;2039      let alreadyWritten = false;2040      try { await navigator.clipboard.writeText(resp.data.password); alreadyWritten = true; } catch {}2041      await chrome.runtime.sendMessage({2042        type: "COPY",2043        payload: { text: resp.data.password, label: "Password", alreadyWritten },2044      }).catch(() => {});2045      flashActionBtn(copyP);2046    });2047    actions.appendChild(copyP);20482049    let trayEl: HTMLDivElement | null = null;2050    let trayInterval: ReturnType<typeof setInterval> | null = null;20512052    function closeTray() {2053      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2054      trayEl?.remove();2055      trayEl = null;2056    }2057    // Register so dismiss() will close the tray and clear the interval2058    // even if the user dismisses without explicitly closing the tray.2059    cleanupHooks.push(closeTray);20602061    async function openTOTPTray() {2062      // Fetch the entry to get the TOTP secret. The selector summary doesn't2063      // carry it (and shouldn't — passing secrets only at fill/copy time keeps2064      // the message-passing surface minimal per Projects.md §5.2).2065      const resp = await chrome.runtime.sendMessage({2066        type: "GET_ENTRY_FOR_FILL",2067        payload: { id: entry.id },2068      }).catch(() => null) as { ok: boolean; data?: { totp?: string } } | null;2069      const secret = resp?.ok ? resp.data?.totp : undefined;2070      if (!secret) return;20712072      trayEl = document.createElement("div");2073      trayEl.className = "sp-tray";20742075      const label = document.createElement("span");2076      label.className = "sp-tray-label";2077      label.textContent = "2FA";2078      trayEl.appendChild(label);20792080      const codeEl = document.createElement("div");2081      codeEl.className = "sp-totp-code";2082      trayEl.appendChild(codeEl);20832084      const ringNs = "http://www.w3.org/2000/svg";2085      const ring = document.createElementNS(ringNs, "svg");2086      ring.setAttribute("class", "sp-totp-ring");2087      ring.setAttribute("viewBox", "0 0 24 24");2088      const trackC = document.createElementNS(ringNs, "circle");2089      trackC.setAttribute("class", "ring-track");2090      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2091      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2092      const fillC = document.createElementNS(ringNs, "circle");2093      fillC.setAttribute("class", "ring-fill");2094      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2095      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2096      fillC.setAttribute("stroke-linecap", "round");2097      fillC.setAttribute("stroke-dasharray", "62.83");2098      ring.append(trackC, fillC);2099      trayEl.appendChild(ring);21002101      const copyBtn = document.createElement("button");2102      copyBtn.className = "sp-totp-copy";2103      copyBtn.type = "button";2104      copyBtn.textContent = "Copy";2105      trayEl.appendChild(copyBtn);21062107      function refresh() {2108        const { code, remaining } = generateTOTP(secret!);2109        // Group as "847 291" — easier to read than "847291"2110        codeEl.textContent = code.length === 62111          ? `${code.slice(0, 3)} ${code.slice(3)}`2112          : code;2113        // Ring fills counter-clockwise as time elapses: dashoffset goes from2114        // 0 (full ring) to 62.83 (empty) over the 30s window.2115        const fraction = (30 - remaining) / 30;2116        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2117      }2118      refresh();2119      trayInterval = setInterval(refresh, 1000);21202121      copyBtn.addEventListener("click", async (e) => {2122        e.stopPropagation();2123        const { code } = generateTOTP(secret!);2124        let alreadyWritten = false;2125        try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}2126        await chrome.runtime.sendMessage({2127          type: "COPY",2128          payload: { text: code, label: "TOTP", alreadyWritten },2129        }).catch(() => {});2130        copyBtn.textContent = "Copied";2131        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2132      });21332134      platter.appendChild(trayEl);2135    }21362137    const editBtn = document.createElement("button");2138    editBtn.className = "sp-action-btn sp-action-edit";2139    editBtn.type = "button";2140    editBtn.title = "Edit entry";2141    editBtn.textContent = "Edit";2142    editBtn.addEventListener("click", (e) => {2143      e.stopPropagation();2144      closeTray();2145      void renderInlineEdit(entry);2146    });2147    actions.appendChild(editBtn);21482149    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2150    // "···" toggle was zero-savings (the toggle button took the same space2151    // the "2FA" label needed) and made the code one extra click away.2152    if (entry.hasTotp) void openTOTPTray();21532154    platter.appendChild(actions);2155    container.appendChild(platter);2156  }21572158  /**2159   * Inline-popup edit mode. Swaps the silver platter for an editable form2160   * over the same shadow-DOM surface so the user never leaves the page.2161   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2162   * with the new fields. Cancel returns without writing.2163   */2164  async function renderInlineEdit(summary: SelectorEntry) {2165    container.innerHTML = "";2166    const wrap = document.createElement("div");2167    wrap.className = "create-form-wrap";21682169    const head = document.createElement("div");2170    head.className = "create-head";2171    const back = document.createElement("button");2172    back.className = "back-btn";2173    back.type = "button";2174    back.title = "Cancel";2175    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>`;2176    back.addEventListener("click", () => renderSilverPlatter(summary));2177    head.appendChild(back);2178    const headLbl = document.createElement("div");2179    headLbl.className = "create-label";2180    headLbl.textContent = "Edit entry";2181    head.appendChild(headLbl);2182    wrap.appendChild(head);21832184    const body = document.createElement("div");2185    body.className = "create-body";21862187    // Loading shimmer while we fetch the full entry2188    const loading = document.createElement("div");2189    loading.className = "empty-hint";2190    loading.textContent = "loading…";2191    body.appendChild(loading);2192    wrap.appendChild(body);2193    container.appendChild(wrap);21942195    const [res, idRes] = await Promise.all([2196      chrome.runtime.sendMessage({2197        type: "GET_ENTRY_FOR_FILL",2198        payload: { id: summary.id },2199      }).catch(() => null),2200      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2201    ]);2202    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2203    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];22042205    if (!entryRes || !entryRes.ok || !entryRes.data) {2206      loading.textContent = "couldn't load this entry. try again from the popup.";2207      return;2208    }2209    body.innerHTML = "";22102211    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2212      const group = document.createElement("div");2213      group.className = "f-group";2214      const lbl = document.createElement("div");2215      lbl.className = "f-label";2216      lbl.textContent = label;2217      const input = document.createElement("input");2218      input.className = "f-input";2219      input.type = type;2220      input.value = value;2221      input.autocomplete = "off";2222      group.append(lbl, input);2223      body.appendChild(group);2224      return { g: group, inp: input };2225    }22262227    const titleInput = field("title", entryRes.data.title ?? "").inp;2228    const urlInput = field("url", entryRes.data.url ?? "").inp;2229    urlInput.classList.add("url-f");2230    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2231    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2232    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2233    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2234    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");22352236    // Password row with reveal toggle2237    const pwGroup = document.createElement("div");2238    pwGroup.className = "f-group";2239    const pwLbl = document.createElement("div");2240    pwLbl.className = "f-label";2241    pwLbl.textContent = "password";2242    const pwRow = document.createElement("div");2243    pwRow.className = "f-row";2244    const pwInput = document.createElement("input");2245    pwInput.className = "f-input";2246    pwInput.type = "password";2247    pwInput.value = entryRes.data.password ?? "";2248    pwInput.autocomplete = "new-password";2249    const revealBtn = document.createElement("button");2250    revealBtn.className = "gen-btn";2251    revealBtn.type = "button";2252    revealBtn.textContent = "show";2253    revealBtn.addEventListener("click", () => {2254      const reveal = pwInput.type === "password";2255      pwInput.type = reveal ? "text" : "password";2256      revealBtn.textContent = reveal ? "hide" : "show";2257    });2258    pwRow.append(pwInput, revealBtn);2259    pwGroup.append(pwLbl, pwRow);2260    body.appendChild(pwGroup);22612262    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;22632264    // Notes2265    const notesGroup = document.createElement("div");2266    notesGroup.className = "f-group";2267    const notesLbl = document.createElement("div");2268    notesLbl.className = "f-label";2269    notesLbl.textContent = "notes";2270    const notesInput = document.createElement("textarea");2271    notesInput.className = "f-input";2272    notesInput.rows = 3;2273    notesInput.value = entryRes.data.notes ?? "";2274    notesInput.style.fontFamily = "Inter, sans-serif";2275    notesInput.style.resize = "vertical";2276    notesGroup.append(notesLbl, notesInput);2277    body.appendChild(notesGroup);22782279    // Save / Cancel row2280    const actionsRow = document.createElement("div");2281    actionsRow.className = "f-row";2282    const saveBtn = document.createElement("button");2283    saveBtn.className = "save-btn";2284    saveBtn.type = "button";2285    saveBtn.textContent = "Save changes";2286    saveBtn.style.flex = "1";2287    const cancelBtn = document.createElement("button");2288    cancelBtn.className = "gen-btn";2289    cancelBtn.type = "button";2290    cancelBtn.textContent = "cancel";2291    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2292    actionsRow.append(saveBtn, cancelBtn);2293    body.appendChild(actionsRow);22942295    saveBtn.addEventListener("click", async () => {2296      saveBtn.disabled = true;2297      const originalLabel = saveBtn.textContent;2298      saveBtn.textContent = "Saving…";2299      const patch: Record<string, unknown> = {2300        title: titleInput.value.trim(),2301        url: urlInput.value.trim(),2302        username: usernameInput.value.trim(),2303        email: emailInput.value.trim() || undefined,2304        password: pwInput.value,2305        totp: totpInput.value.trim(),2306        notes: notesInput.value,2307      };2308      const updateRes = (await chrome.runtime.sendMessage({2309        type: "UPDATE_ENTRY",2310        payload: { id: summary.id, patch },2311      }).catch(() => null)) as { ok: boolean; error?: string } | null;2312      if (!updateRes?.ok) {2313        saveBtn.disabled = false;2314        saveBtn.textContent = originalLabel;2315        const err = document.createElement("div");2316        err.className = "empty-hint";2317        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2318        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2319        body.appendChild(err);2320        setTimeout(() => err.remove(), 3000);2321        return;2322      }2323      // Refresh the platter with updated summary fields2324      const refreshed: SelectorEntry = {2325        id: summary.id,2326        title: patch.title as string,2327        username: patch.username as string,2328        email: patch.email as string | undefined,2329        url: patch.url as string,2330        hasTotp: Boolean(patch.totp),2331        hasPasskey: summary.hasPasskey,2332      };2333      renderSilverPlatter(refreshed);2334    });23352336    queueMicrotask(() => titleInput.focus());2337  }23382339  function renderLocked() {2340    container.innerHTML = "";23412342    // Domain header (same as list view)2343    const domHdr = document.createElement("div");2344    domHdr.className = "domain-header";2345    const eyebrow = document.createElement("div");2346    eyebrow.className = "domain-eyebrow";2347    eyebrow.textContent = "vault locked";2348    const domName = document.createElement("div");2349    domName.className = "domain-name";2350    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2351    domHdr.append(eyebrow, domName);2352    container.appendChild(domHdr);23532354    const wrap = document.createElement("div");2355    wrap.className = "locked-wrap";23562357    // Icon + label row2358    const head = document.createElement("div"); head.className = "locked-head";2359    const icon = document.createElement("div"); icon.className = "locked-icon";2360    icon.innerHTML = keySvgStr();2361    const title = document.createElement("div"); title.className = "locked-title";2362    title.textContent = "unlock to autofill";2363    head.append(icon, title);23642365    // Password input2366    const pwInp = document.createElement("input");2367    pwInp.className = "locked-input";2368    pwInp.type = "password";2369    pwInp.placeholder = "master password";2370    pwInp.setAttribute("autocomplete", "current-password");23712372    // Error line (hidden initially)2373    const errEl = document.createElement("div");2374    errEl.className = "locked-error";2375    errEl.style.display = "none";23762377    // Unlock button2378    const unlockBtn = document.createElement("button");2379    unlockBtn.className = "locked-btn";2380    unlockBtn.type = "button";2381    unlockBtn.textContent = "unlock";23822383    async function tryUnlock() {2384      const pw = pwInp.value.trim();2385      if (!pw) { pwInp.focus(); return; }2386      unlockBtn.disabled = true;2387      unlockBtn.textContent = "unlocking…";2388      errEl.style.display = "none";2389      try {2390        const res = await chrome.runtime.sendMessage({2391          type: "UNLOCK",2392          payload: { password: pw },2393        });2394        if ((res as { ok?: boolean }).ok) {2395          dismiss();2396          options.onUnlocked?.();2397        } else {2398          errEl.textContent = "incorrect password";2399          errEl.style.display = "block";2400          pwInp.value = "";2401          pwInp.focus();2402          unlockBtn.disabled = false;2403          unlockBtn.textContent = "unlock";2404        }2405      } catch {2406        errEl.textContent = "could not reach Peach";2407        errEl.style.display = "block";2408        unlockBtn.disabled = false;2409        unlockBtn.textContent = "unlock";2410      }2411    }24122413    pwInp.addEventListener("keydown", (e) => {2414      e.stopPropagation();2415      if (e.key === "Enter") void tryUnlock();2416    });2417    pwInp.addEventListener("keyup", (e) => e.stopPropagation());2418    pwInp.addEventListener("keypress", (e) => e.stopPropagation());2419    unlockBtn.addEventListener("click", () => void tryUnlock());24202421    wrap.append(head, pwInp, errEl, unlockBtn);2422    container.appendChild(wrap);24232424    // On pages with aggressive focus traps (Etsy modal, Google sign-in, etc.)2425    // the page reclaims focus from our Shadow DOM input before the user can2426    // type. Fighting over focus with a focusout→refocus loop hangs the tab.2427    // Instead: intercept keystrokes at the document capture phase — this runs2428    // before any page handler regardless of which element technically has2429    // OS focus — and route them into our input.2430    const captureKeydown = (e: KeyboardEvent) => {2431      if (!host.isConnected) {2432        document.removeEventListener("keydown", captureKeydown, true);2433        return;2434      }2435      // Let browser shortcuts (Ctrl/Cmd/Alt combos) and Tab pass through.2436      if (e.ctrlKey || e.metaKey || e.altKey || e.key === "Tab") return;2437      // Intercept before page handlers and give our input focus.2438      e.stopImmediatePropagation();2439      if (e.key === "Escape") { dismiss(true); return; }2440      if (e.key === "Enter") { void tryUnlock(); return; }2441      // For all other printable/editing keys, ensure our input has focus so2442      // the browser delivers the keystroke there naturally.2443      if (document.activeElement !== host) {2444        pwInp.focus({ preventScroll: true });2445      }2446    };2447    captureKeydownRef = captureKeydown;2448    document.addEventListener("keydown", captureKeydown, true);24492450    // Best-effort focus on open — may be overridden by page focus trap,2451    // but the capture listener above handles typing regardless.2452    pwInp.focus({ preventScroll: true });2453    requestAnimationFrame(() => { if (host.isConnected) pwInp.focus({ preventScroll: true }); });2454  }24552456  function handleKeyDown(e: KeyboardEvent) {2457    if (options.locked) {2458      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2459      return;2460    }2461    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2462      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2463      return;2464    }2465    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2466    const count = allEntryEls.length;2467    if (document.activeElement === searchInput) {2468      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2469      if (count === 0) return;2470      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2471    }2472    if (count === 0) return;2473    switch (e.key) {2474      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2475      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2476      case "Enter": {2477        if (focusedIndex >= 0) {2478          const el = allEntryEls[focusedIndex] as HTMLElement;2479          const id = el.dataset.id;2480          if (id) { onSelect(id); dismiss(); }2481          else if (el.classList.contains("is-new") || !id) {2482            // "New entry" row (last item, no data-id)2483            showCreateForm();2484          }2485        }2486        break;2487      }2488      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2489    }2490  }24912492  document.addEventListener("keydown", handleKeyDown);24932494  document.body.appendChild(host);24952496  function updatePosition() {2497    const r = anchorEl.getBoundingClientRect();2498    host.style.top = `${r.bottom + window.scrollY + 5}px`;2499    host.style.left = `${r.left + window.scrollX}px`;2500  }2501  // These bindings are referenced from renderLocked()/dismiss() — they MUST2502  // be initialized before renderLocked() runs, or the synchronous assignment2503  // `captureKeydownRef = captureKeydown` inside renderLocked hits the TDZ2504  // and throws ReferenceError. The throw lands after the popup is rendered2505  // but before showAutofillSelector returns its dismiss handle, leaving an2506  // orphan host in the DOM (which is what caused the locked-popup stacking2507  // and missing autofocus on every click).2508  let captureKeydownRef: ((e: KeyboardEvent) => void) | null = null;2509  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);25102511  if (options.locked) {2512    renderLocked();2513  } else if (options.isSignup && options.savedIdentities) {2514    // State 10: identity helper — signup form detected, show derived2515    // identity list (emails then usernames) instead of vault entry list.2516    renderIdentityHelper();2517  } else if (entries.length === 1 && !options.isSignup) {2518    // Silver platter (State 1): single domain match → focused fill view.2519    // Multi-match goes through renderList instead.2520    renderSilverPlatter(entries[0]!);2521  } else {2522    renderList();2523  }25242525  let exitScheduled = false;2526  function dismiss(userAction = false) {2527    // Idempotent: dismiss() can be called from multiple paths (Escape,2528    // outside click, entry select, fill success, host page nav). The exit2529    // animation must only play once and host.remove() must run exactly once.2530    if (exitScheduled) return;2531    exitScheduled = true;2532    // Detach listeners synchronously so nothing can re-trigger during the2533    // 130ms exit window (a focusin firing here would race against the2534    // dismiss-lock work in Pass 2).2535    stopObserving();2536    document.removeEventListener("click", outsideClick, { capture: true });2537    document.removeEventListener("keydown", handleKeyDown);2538    if (captureKeydownRef) {2539      document.removeEventListener("keydown", captureKeydownRef, true);2540      captureKeydownRef = null;2541    }2542    for (const cleanup of cleanupHooks) {2543      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2544    }2545    if (userAction) options.onDismiss?.();2546    container.classList.add("is-exiting");2547    setTimeout(() => host.remove(), 130);2548  }25492550  function outsideClick(ev: MouseEvent) {2551    const path = ev.composedPath();2552    // Never dismiss when clicking the anchor field itself — that click is2553    // what triggered the selector to open, and the user may click the field2554    // again to re-focus it without intending to close the selector.2555    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2556  }2557  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2558  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);25592560  return dismiss;2561}25622563export interface CardSelectorEntry {2564  id: string;2565  title: string;2566  cardholderName?: string;2567  last4?: string;2568  expMonth?: string;2569  expYear?: string;2570  network?: import("../shared/types").CardNetwork;2571}25722573interface CardSelectorOptions {2574  domain?: string;2575  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2576  onFill: (entry: import("../shared/types").VaultEntry) => void;2577  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2578  onDismiss?: () => void;2579}25802581/**2582 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2583 * passkey create or get. Renders as a fixed-position floating popup (no2584 * field anchor needed — passkeys don't require a focused input). Uses the2585 * same theme tokens and entrance animation as all other inline popup states.2586 */2587export function showPasskeyProGate(): void {2588  const domain = location.hostname.replace(/^www\./, "");25892590  const host = document.createElement("div");2591  host.setAttribute("data-peach-passkey-gate", "1");2592  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2593  const shadow = host.attachShadow({ mode: "closed" });25942595  const style = document.createElement("style");2596  style.textContent = `2597    :host { all: initial; }2598    .gate-wrap {2599      position: fixed;2600      top: 50%;2601      left: 50%;2602      transform: translate(-50%, -50%);2603      width: 280px;2604      pointer-events: auto;2605      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2606    }2607    @keyframes g-in {2608      from { opacity:0; transform: translate(-50%,-52%); }2609      to   { opacity:1; transform: translate(-50%,-50%); }2610    }2611    .gate-wrap.is-exiting {2612      animation: g-out 130ms ease-in forwards;2613    }2614    @keyframes g-out {2615      to { opacity:0; transform: translate(-50%,-52%); }2616    }2617    .gate {2618      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2619      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2620      border-radius: 12px;2621      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2622      padding: 16px;2623      font-family: Inter, sans-serif;2624    }2625    .gate-header {2626      display: flex;2627      align-items: center;2628      gap: 7px;2629      margin-bottom: 12px;2630      padding-bottom: 10px;2631      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2632    }2633    .gate-domain {2634      font-size: 12px;2635      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2636      font-family: "IBM Plex Mono", monospace;2637      overflow: hidden;2638      text-overflow: ellipsis;2639      white-space: nowrap;2640    }2641    .gate-title {2642      font-size: 14px;2643      font-weight: 500;2644      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2645      margin-bottom: 6px;2646    }2647    .gate-subtitle {2648      font-size: 12px;2649      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2650      line-height: 1.5;2651      margin-bottom: 14px;2652    }2653    .gate-btn {2654      display: block;2655      width: 100%;2656      padding: 9px 0;2657      border-radius: 8px;2658      border: none;2659      cursor: pointer;2660      font-size: 13px;2661      font-family: Inter, sans-serif;2662      font-weight: 500;2663      transition: opacity 100ms;2664      margin-bottom: 7px;2665      text-align: center;2666    }2667    .gate-btn:last-child { margin-bottom: 0; }2668    .gate-btn--accent {2669      background: ${accentHex};2670      color: #fff;2671    }2672    .gate-btn--accent:hover { opacity: 0.88; }2673    .gate-btn--ghost {2674      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2675      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2676    }2677    .gate-btn--ghost:hover { opacity: 0.75; }2678    .backdrop {2679      position: fixed;2680      inset: 0;2681      pointer-events: auto;2682    }2683  `;2684  shadow.appendChild(style);26852686  const backdrop = document.createElement("div");2687  backdrop.className = "backdrop";2688  shadow.appendChild(backdrop);26892690  const wrap = document.createElement("div");2691  wrap.className = "gate-wrap";2692  shadow.appendChild(wrap);26932694  const gate = document.createElement("div");2695  gate.className = "gate";2696  wrap.appendChild(gate);26972698  // Header: peach icon + domain2699  const header = document.createElement("div");2700  header.className = "gate-header";2701  const icon = document.createElement("span");2702  icon.innerHTML = peachIconSvg();2703  const domainEl = document.createElement("span");2704  domainEl.className = "gate-domain";2705  domainEl.textContent = domain;2706  header.append(icon, domainEl);2707  gate.appendChild(header);27082709  const title = document.createElement("div");2710  title.className = "gate-title";2711  title.textContent = "Passkeys are part of Peach Pro.";2712  gate.appendChild(title);27132714  const subtitle = document.createElement("div");2715  subtitle.className = "gate-subtitle";2716  subtitle.textContent = "Store and use passkeys across all your devices, securely.";2717  gate.appendChild(subtitle);27182719  const upgradeBtn = document.createElement("button");2720  upgradeBtn.className = "gate-btn gate-btn--accent";2721  upgradeBtn.type = "button";2722  upgradeBtn.textContent = "Upgrade to Pro";2723  gate.appendChild(upgradeBtn);27242725  const laterBtn = document.createElement("button");2726  laterBtn.className = "gate-btn gate-btn--ghost";2727  laterBtn.type = "button";2728  laterBtn.textContent = "Not right now";2729  gate.appendChild(laterBtn);27302731  function dismiss() {2732    wrap.classList.add("is-exiting");2733    setTimeout(() => host.remove(), 130);2734  }27352736  upgradeBtn.addEventListener("click", () => {2737    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});2738    dismiss();2739  });2740  laterBtn.addEventListener("click", dismiss);2741  backdrop.addEventListener("click", dismiss);27422743  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {2744    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }2745  });27462747  document.body.appendChild(host);2748}27492750/**2751 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world2752 * detector sees the page invoke navigator.credentials.create(); content/index.ts2753 * checks vault + decline state then calls this. "Save passkey to Peach"2754 * initiates the popup-context credential flow; "Not now" records a 30-day2755 * decline for the domain so we don't re-show on every page reload.2756 */2757export function showPasskeyRegistrationOffer(args: {2758  rpId: string;2759  rpName?: string;2760  userName?: string;2761  userDisplayName?: string;2762}): void {2763  const domain = location.hostname.replace(/^www\./, "");2764  const displayName = args.rpName || domain;27652766  const host = document.createElement("div");2767  host.setAttribute("data-peach-passkey-offer", "1");2768  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";2769  const shadow = host.attachShadow({ mode: "closed" });27702771  const style = document.createElement("style");2772  style.textContent = `2773    :host { all: initial; }2774    .offer-wrap {2775      position: fixed;2776      top: 16px;2777      right: 16px;2778      width: 320px;2779      pointer-events: auto;2780      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;2781    }2782    @keyframes o-in {2783      from { opacity: 0; transform: translateY(-6px); }2784      to   { opacity: 1; transform: translateY(0); }2785    }2786    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }2787    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }2788    .offer {2789      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2790      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2791      border-radius: 12px;2792      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2793      padding: 14px 14px 12px;2794      font-family: Inter, sans-serif;2795      position: relative;2796    }2797    .offer-close {2798      position: absolute;2799      top: 8px;2800      right: 8px;2801      width: 18px;2802      height: 18px;2803      border: none;2804      background: transparent;2805      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};2806      cursor: pointer;2807      font-size: 14px;2808      line-height: 1;2809      padding: 0;2810    }2811    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }2812    .offer-header {2813      display: flex;2814      align-items: center;2815      gap: 7px;2816      margin-bottom: 8px;2817      padding-bottom: 8px;2818      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2819    }2820    .offer-domain {2821      font-size: 12px;2822      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2823      font-family: "IBM Plex Mono", monospace;2824      overflow: hidden;2825      text-overflow: ellipsis;2826      white-space: nowrap;2827    }2828    .offer-title {2829      font-size: 13px;2830      font-weight: 500;2831      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2832      margin-bottom: 4px;2833    }2834    .offer-subtitle {2835      font-size: 11px;2836      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};2837      line-height: 1.45;2838      margin-bottom: 12px;2839    }2840    .offer-btn {2841      display: block;2842      width: 100%;2843      padding: 8px 0;2844      border-radius: 7px;2845      border: none;2846      cursor: pointer;2847      font-size: 12px;2848      font-family: Inter, sans-serif;2849      font-weight: 500;2850      transition: opacity 100ms;2851      margin-bottom: 6px;2852      text-align: center;2853    }2854    .offer-btn:last-child { margin-bottom: 0; }2855    .offer-btn--accent { background: ${accentHex}; color: #fff; }2856    .offer-btn--accent:hover { opacity: 0.88; }2857    .offer-btn--ghost {2858      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2859      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};2860    }2861    .offer-btn--ghost:hover { opacity: 0.75; }2862  `;2863  shadow.appendChild(style);28642865  const wrap = document.createElement("div");2866  wrap.className = "offer-wrap";2867  shadow.appendChild(wrap);28682869  const offer = document.createElement("div");2870  offer.className = "offer";2871  wrap.appendChild(offer);28722873  const closeBtn = document.createElement("button");2874  closeBtn.className = "offer-close";2875  closeBtn.type = "button";2876  closeBtn.setAttribute("aria-label", "Dismiss");2877  closeBtn.textContent = "✕";2878  offer.appendChild(closeBtn);28792880  const header = document.createElement("div");2881  header.className = "offer-header";2882  const icon = document.createElement("span");2883  icon.innerHTML = peachIconSvg();2884  const domainEl = document.createElement("span");2885  domainEl.className = "offer-domain";2886  domainEl.textContent = domain;2887  header.append(icon, domainEl);2888  offer.appendChild(header);28892890  const title = document.createElement("div");2891  title.className = "offer-title";2892  title.textContent = "This site supports passkeys.";2893  offer.appendChild(title);28942895  const subtitle = document.createElement("div");2896  subtitle.className = "offer-subtitle";2897  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";2898  offer.appendChild(subtitle);28992900  const saveBtn = document.createElement("button");2901  saveBtn.className = "offer-btn offer-btn--accent";2902  saveBtn.type = "button";2903  saveBtn.textContent = "Save passkey to Peach";2904  offer.appendChild(saveBtn);29052906  const laterBtn = document.createElement("button");2907  laterBtn.className = "offer-btn offer-btn--ghost";2908  laterBtn.type = "button";2909  laterBtn.textContent = "Not now";2910  offer.appendChild(laterBtn);29112912  function dismiss(decline: boolean) {2913    if (decline) {2914      chrome.runtime.sendMessage({2915        type: "PASSKEY_OFFER_DECLINE",2916        payload: { domain },2917      }).catch(() => {});2918    }2919    wrap.classList.add("is-exiting");2920    setTimeout(() => host.remove(), 130);2921  }29222923  saveBtn.addEventListener("click", () => {2924    chrome.runtime.sendMessage({2925      type: "INITIATE_FIREFOX_PASSKEY_CREATE",2926      payload: {2927        rpId: args.rpId,2928        rpName: args.rpName ?? displayName,2929        userName: args.userName ?? "user",2930        userDisplayName: args.userDisplayName,2931      },2932    }).catch(() => {});2933    dismiss(false);2934  });2935  laterBtn.addEventListener("click", () => dismiss(true));2936  closeBtn.addEventListener("click", () => dismiss(true));29372938  document.body.appendChild(host);2939}29402941/**2942 * State 11 — passkey available indicator. Shown when the user lands on a2943 * domain for which they already have a stored passkey. Tells them where to2944 * find it (the entry already shows in the vault list); the "Sign in with2945 * passkey" button opens the popup so they can use the platform authenticator2946 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles2947 * the actual sign-in transparently, so this banner is informational only.2948 */2949export function showPasskeyAvailable(args: {2950  rpId: string;2951  userName: string;2952  fromBrowser?: "chrome" | "firefox";2953  currentBrowser?: "chrome" | "firefox" | "unknown";2954}): void {2955  const domain = location.hostname.replace(/^www\./, "");2956  const crossBrowser =2957    args.fromBrowser &&2958    args.currentBrowser &&2959    args.currentBrowser !== "unknown" &&2960    args.fromBrowser !== args.currentBrowser;29612962  const host = document.createElement("div");2963  host.setAttribute("data-peach-passkey-available", "1");2964  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";2965  const shadow = host.attachShadow({ mode: "closed" });29662967  const style = document.createElement("style");2968  style.textContent = `2969    :host { all: initial; }2970    .avail-wrap {2971      position: fixed;2972      top: 16px;2973      right: 16px;2974      width: 320px;2975      pointer-events: auto;2976      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;2977    }2978    @keyframes a-in {2979      from { opacity: 0; transform: translateY(-6px); }2980      to   { opacity: 1; transform: translateY(0); }2981    }2982    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }2983    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }2984    .avail {2985      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2986      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2987      border-radius: 12px;2988      box-shadow: 0 12px 48px rgba(0,0,0,0.55);2989      padding: 14px 14px 12px;2990      font-family: Inter, sans-serif;2991      position: relative;2992    }2993    .avail-close {2994      position: absolute;2995      top: 8px;2996      right: 8px;2997      width: 18px;2998      height: 18px;2999      border: none;3000      background: transparent;3001      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3002      cursor: pointer;3003      font-size: 14px;3004      line-height: 1;3005      padding: 0;3006    }3007    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3008    .avail-header {3009      display: flex;3010      align-items: center;3011      gap: 7px;3012      margin-bottom: 8px;3013      padding-bottom: 8px;3014      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3015    }3016    .avail-domain {3017      font-size: 12px;3018      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3019      font-family: "IBM Plex Mono", monospace;3020    }3021    .avail-label {3022      font-size: 9px;3023      letter-spacing: 0.16em;3024      text-transform: uppercase;3025      color: ${accentHex};3026      margin-bottom: 4px;3027    }3028    .avail-user {3029      font-size: 13px;3030      font-weight: 500;3031      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3032      margin-bottom: 12px;3033      overflow: hidden;3034      text-overflow: ellipsis;3035      white-space: nowrap;3036    }3037    .avail-cross {3038      font-size: 11px;3039      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3040      line-height: 1.45;3041      margin-bottom: 12px;3042      padding: 8px;3043      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3044      border-radius: 6px;3045    }3046    .avail-btn {3047      display: block;3048      width: 100%;3049      padding: 8px 0;3050      border-radius: 7px;3051      border: none;3052      cursor: pointer;3053      font-size: 12px;3054      font-family: Inter, sans-serif;3055      font-weight: 500;3056      transition: opacity 100ms;3057      margin-bottom: 6px;3058      text-align: center;3059    }3060    .avail-btn:last-child { margin-bottom: 0; }3061    .avail-btn--accent { background: ${accentHex}; color: #fff; }3062    .avail-btn--accent:hover { opacity: 0.88; }3063    .avail-btn--ghost {3064      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3065      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3066    }3067    .avail-btn--ghost:hover { opacity: 0.75; }3068  `;3069  shadow.appendChild(style);30703071  const wrap = document.createElement("div");3072  wrap.className = "avail-wrap";3073  shadow.appendChild(wrap);30743075  const avail = document.createElement("div");3076  avail.className = "avail";3077  wrap.appendChild(avail);30783079  const closeBtn = document.createElement("button");3080  closeBtn.className = "avail-close";3081  closeBtn.type = "button";3082  closeBtn.setAttribute("aria-label", "Dismiss");3083  closeBtn.textContent = "✕";3084  avail.appendChild(closeBtn);30853086  const header = document.createElement("div");3087  header.className = "avail-header";3088  const icon = document.createElement("span");3089  icon.innerHTML = peachIconSvg();3090  const domainEl = document.createElement("span");3091  domainEl.className = "avail-domain";3092  domainEl.textContent = domain;3093  header.append(icon, domainEl);3094  avail.appendChild(header);30953096  const label = document.createElement("div");3097  label.className = "avail-label";3098  label.textContent = "PASSKEY";3099  avail.appendChild(label);31003101  const user = document.createElement("div");3102  user.className = "avail-user";3103  user.textContent = args.userName;3104  avail.appendChild(user);31053106  if (crossBrowser) {3107    const cross = document.createElement("div");3108    cross.className = "avail-cross";3109    cross.textContent =3110      args.fromBrowser === "chrome"3111        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3112        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3113    avail.appendChild(cross);3114  }31153116  const signInBtn = document.createElement("button");3117  signInBtn.className = "avail-btn avail-btn--accent";3118  signInBtn.type = "button";3119  signInBtn.textContent = "Sign in with passkey";3120  avail.appendChild(signInBtn);31213122  const passwordBtn = document.createElement("button");3123  passwordBtn.className = "avail-btn avail-btn--ghost";3124  passwordBtn.type = "button";3125  passwordBtn.textContent = "Use password instead";3126  avail.appendChild(passwordBtn);31273128  function dismiss() {3129    wrap.classList.add("is-exiting");3130    setTimeout(() => host.remove(), 130);3131  }31323133  signInBtn.addEventListener("click", () => {3134    // On Chrome: the user clicking the page's own Sign-in button is what3135    //   triggers webAuthenticationProxy → existing background flow handles it.3136    //   Our button just dismisses since the page itself drives auth.3137    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3138    //   and surface the entry for manual reference (popup view).3139    dismiss();3140    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3141  });3142  passwordBtn.addEventListener("click", dismiss);3143  closeBtn.addEventListener("click", dismiss);31443145  document.body.appendChild(host);3146}31473148/**3149 * State 7 — card silver platter. Single-card focused fill view rendered3150 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3151 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3152 * so card and login flows render identically. Multi-card list view is a3153 * follow-up; today this picks the first card.3154 */3155export function showCardSelector(3156  anchorEl: HTMLInputElement,3157  cards: CardSelectorEntry[],3158  options: CardSelectorOptions3159): () => void {3160  if (cards.length === 0) return () => {};3161  const card = cards[0]!;31623163  const host = document.createElement("div");3164  host.style.cssText = "position: absolute; z-index: 2147483647;";3165  host.style.setProperty("--peach-accent", accentHex);3166  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3167  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3168  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3169  const shadow = host.attachShadow({ mode: "closed" });31703171  const style = shadow.appendChild(document.createElement("style"));3172  style.textContent = SELECTOR_STYLES;31733174  const rect = anchorEl.getBoundingClientRect();3175  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3176  host.style.left = `${rect.left + window.scrollX}px`;3177  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;31783179  const container = shadow.appendChild(document.createElement("div"));3180  container.className = "peach-inline-popup";3181  container.setAttribute("data-theme", popupTheme);31823183  // Domain header — eyebrow communicates the card context, not the site3184  const domHdr = document.createElement("div");3185  domHdr.className = "domain-header";3186  const eyebrow = document.createElement("div");3187  eyebrow.className = "domain-eyebrow";3188  eyebrow.textContent = "Pay with Peach";3189  const domName = document.createElement("div");3190  domName.className = "domain-name";3191  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3192  domHdr.append(eyebrow, domName);3193  container.appendChild(domHdr);31943195  const platter = document.createElement("div");3196  platter.className = "card-platter";31973198  if (card.network && card.network !== "unknown") {3199    const net = document.createElement("div");3200    net.className = "cp-network";3201    net.textContent = card.network;3202    platter.appendChild(net);3203  }32043205  const nick = document.createElement("div");3206  nick.className = "cp-nickname";3207  nick.textContent = card.title;3208  platter.appendChild(nick);32093210  if (card.last4) {3211    const l4 = document.createElement("div");3212    l4.className = "cp-last4";3213    l4.textContent = `•••• ${card.last4}`;3214    platter.appendChild(l4);3215  }32163217  const meta = document.createElement("div");3218  meta.className = "cp-meta";3219  if (card.cardholderName) {3220    const name = document.createElement("span");3221    name.textContent = card.cardholderName;3222    meta.appendChild(name);3223  }3224  if (card.expMonth && card.expYear) {3225    if (card.cardholderName) {3226      const sep = document.createElement("span");3227      sep.className = "cp-meta-sep";3228      sep.textContent = "·";3229      meta.appendChild(sep);3230    }3231    const exp = document.createElement("span");3232    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3233    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3234    meta.appendChild(exp);3235  }3236  if (meta.childElementCount > 0) platter.appendChild(meta);32373238  const fillWrap = document.createElement("div");3239  fillWrap.className = "cp-fill-wrap";3240  const fillBtn = document.createElement("button");3241  fillBtn.className = "sp-fill-btn";3242  fillBtn.type = "button";3243  fillBtn.textContent = "Fill card details";3244  fillBtn.addEventListener("click", async () => {3245    if (fillBtn.disabled) return;3246    fillBtn.disabled = true;3247    fillBtn.classList.add("filled");3248    fillBtn.innerHTML = checkSvgStr();3249    const resp = await chrome.runtime.sendMessage({3250      type: "GET_ENTRY_FOR_FILL",3251      payload: { id: card.id },3252    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3253    if (resp?.ok && resp.data) options.onFill(resp.data);3254    setTimeout(() => dismiss(), 400);3255  });3256  fillWrap.appendChild(fillBtn);3257  platter.appendChild(fillWrap);32583259  // Secondary actions — copy number, copy CVC, dismiss3260  const actions = document.createElement("div");3261  actions.className = "sp-actions";32623263  function flashBtn(b: HTMLButtonElement) {3264    b.classList.add("flashed");3265    setTimeout(() => b.classList.remove("flashed"), 700);3266  }32673268  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3269    const resp = await chrome.runtime.sendMessage({3270      type: "GET_ENTRY_FOR_FILL",3271      payload: { id: card.id },3272    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3273    return resp?.ok && resp.data ? resp.data : null;3274  }32753276  const copyNum = document.createElement("button");3277  copyNum.className = "sp-action-btn";3278  copyNum.type = "button";3279  copyNum.title = "Copy card number";3280  copyNum.textContent = "Copy number";3281  copyNum.addEventListener("click", async (e) => {3282    e.stopPropagation();3283    const full = await fetchFullCard();3284    if (!full?.cardNumber) return;3285    let alreadyWritten = false;3286    try { await navigator.clipboard.writeText(full.cardNumber); alreadyWritten = true; } catch {}3287    await chrome.runtime.sendMessage({3288      type: "COPY",3289      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3290    }).catch(() => {});3291    flashBtn(copyNum);3292  });3293  actions.appendChild(copyNum);32943295  const copyCvc = document.createElement("button");3296  copyCvc.className = "sp-action-btn";3297  copyCvc.type = "button";3298  copyCvc.title = "Copy CVC";3299  copyCvc.textContent = "Copy CVC";3300  copyCvc.addEventListener("click", async (e) => {3301    e.stopPropagation();3302    const full = await fetchFullCard();3303    if (!full?.cvc) return;3304    let alreadyWritten = false;3305    try { await navigator.clipboard.writeText(full.cvc); alreadyWritten = true; } catch {}3306    await chrome.runtime.sendMessage({3307      type: "COPY",3308      payload: { text: full.cvc, label: "CVC", alreadyWritten },3309    }).catch(() => {});3310    flashBtn(copyCvc);3311  });3312  actions.appendChild(copyCvc);33133314  const closeBtn = document.createElement("button");3315  closeBtn.className = "sp-action-btn";3316  closeBtn.type = "button";3317  closeBtn.title = "Dismiss";3318  closeBtn.textContent = "✕";3319  closeBtn.addEventListener("click", (e) => {3320    e.stopPropagation();3321    dismiss(true);3322  });3323  actions.appendChild(closeBtn);33243325  platter.appendChild(actions);3326  container.appendChild(platter);33273328  document.body.appendChild(host);3329  function updatePosition() {3330    const r = anchorEl.getBoundingClientRect();3331    host.style.top = `${r.bottom + window.scrollY + 5}px`;3332    host.style.left = `${r.left + window.scrollX}px`;3333  }3334  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);33353336  function onKeyDown(e: KeyboardEvent) {3337    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3338  }3339  document.addEventListener("keydown", onKeyDown);33403341  let exitScheduled = false;3342  function dismiss(userAction = false) {3343    if (exitScheduled) return;3344    exitScheduled = true;3345    stopObserving();3346    document.removeEventListener("click", outsideClick, { capture: true });3347    document.removeEventListener("keydown", onKeyDown);3348    if (userAction) options.onDismiss?.();3349    container.classList.add("is-exiting");3350    setTimeout(() => host.remove(), 130);3351  }33523353  function outsideClick(ev: MouseEvent) {3354    const path = ev.composedPath();3355    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3356  }3357  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);33583359  return dismiss;3360}