inject.ts

146.0 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 } from "../shared/generate";14import { detectPasswordPolicy } from "./policy";1516let accentHex = "#E8956D";17let popupTheme: "dark" | "light" = "dark";18chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string; theme?: string } } | undefined) => {19  const data = resp?.data;20  const name = data?.accentColor ?? "peach";21  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";22  popupTheme = data?.theme === "light" ? "light" : "dark";23});2425// 8-digit hex alpha helpers for the accent-derived shadow tokens.26// `#E8956D` + alpha `28` → `#E8956D28`. The browser parses the trailing27// two hex digits as the alpha channel.28function withAlpha(hex: string, alpha: string): string {29  // Defensive: only 6-digit hex inputs are supported here. ACCENT_COLORS30  // always exposes 6-digit hex, so this is a guard against future changes31  // shipping shorthand colors that would silently break the var injection.32  return /^#[0-9a-f]{6}$/i.test(hex) ? hex + alpha : hex;33}3435export interface SelectorEntry {36  id: string;37  title: string;38  username?: string;39  email?: string;40  url?: string;41  hasTotp?: boolean;42  /** True when the entry also has a passkey credential attached. */43  hasPasskey?: boolean;44}4546interface SelectorOptions {47  domain?: string;48  searchableEntries?: SelectorEntry[];49  /** True when shown on a signup form — changes header label and entry-click behaviour */50  isSignup?: boolean;51  /**52   * Derived identity list (emails then usernames) for signup mode (State 10).53   * When present, renderIdentityHelper() is used instead of renderList().54   */55  savedIdentities?: SavedIdentity[];56  /**57   * Called after the user picks a saved identity (signup mode only) or58   * after successfully saving a new entry on a signup form.59   * Lets the caller fill the visible username + password fields.60   */61  onFillFields?: (username: string, password: string) => void;62  /**63   * When true, show an inline unlock form instead of the entries list.64   * Used when the vault is locked so the user can unlock without opening65   * the popup.66   */67  locked?: boolean;68  /**69   * Called after a successful inline unlock — the caller should re-query70   * entries and re-open the selector with real data.71   */72  onUnlocked?: () => void;73  /**74   * Called when the user explicitly dismisses the selector (Escape, Tab, or75   * click outside) — NOT when an entry is selected or on auto-close.76   * Used by the caller to suppress spurious reopens on the same field.77   */78  onDismiss?: () => void;79}8081function getDomainFromUrl(url: string): string {82  try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }83}8485function keySvgStr(): string {86  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>`;87}8889function plusSvgStr(): string {90  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>`;91}9293function searchSvgStr(): string {94  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"><circle cx="5.25" cy="5.25" r="3.5"/><path d="M7.9 7.9l2.35 2.35"/></svg>`;95}9697function backSvgStr(): string {98  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.4" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 2.5L3.5 6l4 3.5"/></svg>`;99}100101function peachIconSvg(): string {102  // Peach body stays brand-peach regardless of `accentHex` — a sage or103  // sky accent must not turn the autofill icon green or blue. Accent104  // color still tints surrounding glow/hover halos below.105  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 240 240" fill="none" aria-hidden="true"><path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/><path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z" fill="#FFB082"/><path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z" fill="#E5805C"/><ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/></svg>`;106}107108function checkSvgStr(): string {109  return `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="#5E7A42" stroke-width="1.5" stroke-linecap="round"><path d="M4 10.5L8 14.5L16 6.5"/></svg>`;110}111112function smartUrl(): { origin: string; title: string; loginSubdomain: boolean } {113  const { hostname, origin } = location;114  const parts = hostname.split(".");115  const AUTH_PREFIXES = ["accounts", "auth", "login", "signin", "sign-in", "sso",116    "id", "identity", "secure", "portal", "my", "am", "idp", "connect", "oauth",117    "oidc", "federation", "saml", "cas", "ldap"];118  const loginSubdomain = parts.length > 2 && AUTH_PREFIXES.includes(parts[0]!.toLowerCase());119  const rootName = parts.length >= 2 ? parts[parts.length - 2]! : parts[0]!;120  const title = rootName.charAt(0).toUpperCase() + rootName.slice(1);121  return { origin, title, loginSubdomain };122}123124/**125 * Shows a bottom-of-page toast after filling credentials when the entry has126 * never matched the current site — offering to add the current origin to the127 * entry's `additionalUrls` so future visits auto-suggest it. Closes after 9s.128 */129export function showRememberSiteToast(130  pageDomain: string,131  entryId: string,132): void {133  const host = document.createElement("div");134  host.style.cssText = "position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:2147483647;pointer-events:auto;";135  host.style.setProperty("--peach-accent", accentHex);136  const shadow = host.attachShadow({ mode: "closed" });137138  const style = document.createElement("style");139  style.textContent = `140    .bar {141      display:flex;align-items:center;gap:10px;padding:10px 14px;142      background:#131109;border:1px solid rgba(240,232,216,0.09);143      border-radius:10px;box-shadow:0 8px 32px rgba(0,0,0,0.75);144      font-family:Inter,sans-serif;white-space:nowrap;145      animation:tf-in 180ms cubic-bezier(0.16,1,0.3,1) both;146    }147    @keyframes tf-in { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none} }148    .txt { font-size:11px;color:rgba(240,232,216,0.55);font-family:"IBM Plex Mono",monospace; }149    .yes {150      padding:5px 12px;border-radius:6px;border:none;cursor:pointer;font-size:11px;151      background:var(--peach-accent);color:#fff;transition:background 100ms;font-family:Inter,sans-serif;152    }153    .yes:hover { background:color-mix(in srgb, var(--peach-accent) 82%, #000); }154    .no {155      padding:5px 10px;border-radius:6px;border:none;cursor:pointer;font-size:11px;156      background:rgba(240,232,216,0.07);color:rgba(240,232,216,0.45);font-family:Inter,sans-serif;157    }158  `;159  shadow.appendChild(style);160161  const bar = document.createElement("div"); bar.className = "bar";162  const txt = document.createElement("span"); txt.className = "txt";163  txt.textContent = `Remember ${pageDomain} for this entry?`;164  const yesBtn = document.createElement("button"); yesBtn.className = "yes";165  yesBtn.textContent = "Remember";166  yesBtn.addEventListener("click", async () => {167    await chrome.runtime.sendMessage({168      type: "ADD_ADDITIONAL_URL",169      payload: { id: entryId, url: location.origin },170    });171    host.remove();172  });173  const noBtn = document.createElement("button"); noBtn.className = "no";174  noBtn.textContent = "Not now";175  noBtn.addEventListener("click", () => host.remove());176  bar.append(txt, yesBtn, noBtn);177  shadow.appendChild(bar);178  document.body.appendChild(host);179  setTimeout(() => host.remove(), 9000);180}181182interface SmartGenerator {183  root: HTMLElement;184  getPassword: () => string;185  /** Copy the current password to the clipboard with the standard pulse UX. */186  copy: () => Promise<void>;187}188189interface SmartGeneratorOptions {190  /** Site-detected policy — clamps length, sets symbol toggle, exposes hint. */191  policy: PasswordPolicy;192  /**193   * Seed value: used as the displayed password without regenerating, e.g. the194   * password the user already typed into the page. The generator still195   * regenerates the moment any control changes.196   */197  initialPassword?: string;198  /** Fires every time the password regenerates (initial + on changes). */199  onChange?: (pw: string) => void;200}201202/**203 * Build the inline-popup smart-password generator. Mirrors the main popup's204 * GeneratorDrawer (compact mode): readout row + length slider + 4 charset205 * pills + a policy hint that names the constraints Peach detected on the206 * page. Writing this in pure DOM rather than reusing the Solid component207 * keeps the content-script bundle small.208 */209function createSmartGenerator(opts: SmartGeneratorOptions): SmartGenerator {210  const policy = opts.policy ?? {};211212  // Start at site max (strongest password the site accepts), fall back to 64213  let length = policy.maxLength ?? 64;214  if (policy.minLength) length = Math.max(length, policy.minLength);215  if (length < 8) length = 8;216  if (length > 128) length = 128;217218  let upper = true;219  let lower = true;220  let numbers = true;221  let symbols = !policy.forbidsSymbols;222  if (policy.requiresSymbols) symbols = true;223  const forbiddenChars = policy.forbiddenChars ?? "";224225  let password = "";226227  const root = document.createElement("div");228  root.className = "pwgen-block";229230  const displayRow = root.appendChild(document.createElement("div"));231  displayRow.className = "pwgen-display-row";232  const output = displayRow.appendChild(document.createElement("input")) as HTMLInputElement;233  output.type = "text";234  output.className = "pwgen-output";235  output.setAttribute("autocomplete", "off");236  output.setAttribute("spellcheck", "false");237  output.setAttribute("autocorrect", "off");238  output.setAttribute("autocapitalize", "off");239240  const regenBtn = displayRow.appendChild(document.createElement("button"));241  regenBtn.className = "pwgen-icon-btn";242  regenBtn.type = "button";243  regenBtn.setAttribute("aria-label", "Regenerate password");244  regenBtn.title = "Regenerate";245  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>`;246247  const copyBtn = displayRow.appendChild(document.createElement("button"));248  copyBtn.className = "pwgen-icon-btn";249  copyBtn.type = "button";250  copyBtn.setAttribute("aria-label", "Copy password");251  copyBtn.title = "Copy";252  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>`;253254  const controls = root.appendChild(document.createElement("div"));255  controls.className = "pwgen-controls-row";256  const slider = controls.appendChild(document.createElement("input"));257  slider.type = "range";258  slider.className = "pwgen-slider";259  slider.min = "8";260  slider.max = "128";261  slider.value = String(length);262  if (policy.minLength) slider.min = String(Math.max(8, policy.minLength));263  if (policy.maxLength) slider.max = String(Math.min(128, policy.maxLength));264  const lenNum = controls.appendChild(document.createElement("span"));265  lenNum.className = "pwgen-len-num pwgen-len-num--edit";266  lenNum.textContent = String(length);267  lenNum.addEventListener("click", () => {268    const li = document.createElement("input");269    li.type = "text"; li.inputMode = "numeric";270    li.className = "pwgen-len-input"; li.value = String(length);271    lenNum.replaceWith(li);272    requestAnimationFrame(() => li.select());273    function commitLenEdit() {274      const n = parseInt(li.value, 10);275      if (!isNaN(n)) {276        length = Math.max(parseInt(slider.min, 10), Math.min(parseInt(slider.max, 10), n));277        slider.value = String(length);278        regenerate();279      }280      lenNum.textContent = String(length);281      li.replaceWith(lenNum);282    }283    li.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); commitLenEdit(); } else if (e.key === "Escape") { li.replaceWith(lenNum); } });284    li.addEventListener("blur", commitLenEdit);285  });286287  const pills = root.appendChild(document.createElement("div"));288  pills.className = "pwgen-pills";289290  function makePill(label: string, on: boolean, onToggle: (next: boolean) => void): HTMLButtonElement {291    const b = document.createElement("button");292    b.type = "button";293    b.className = `pwgen-pill ${on ? "is-on" : ""}`;294    b.textContent = label;295    b.addEventListener("click", () => {296      const next = !b.classList.contains("is-on");297      b.classList.toggle("is-on", next);298      onToggle(next);299    });300    return b;301  }302  pills.appendChild(makePill("A-Z", upper, (next) => { upper = next; regenerate(); }));303  pills.appendChild(makePill("a-z", lower, (next) => { lower = next; regenerate(); }));304  pills.appendChild(makePill("0-9", numbers, (next) => { numbers = next; regenerate(); }));305  pills.appendChild(makePill("!@#", symbols, (next) => {306    // The site forbids symbols — UI lets the user override but still warn.307    symbols = next;308    regenerate();309  }));310311  // Policy hint — surfaces what Peach read off the site so the user knows the312  // generator is already tuned to it. Only shows when something interesting313  // was detected.314  const hintParts: string[] = [];315  if (policy.minLength) hintParts.push(`min ${policy.minLength}`);316  if (policy.maxLength) hintParts.push(`max ${policy.maxLength}`);317  if (policy.requiresSymbols) hintParts.push("requires symbols");318  if (policy.forbidsSymbols) hintParts.push("no symbols");319  if (policy.forbiddenChars) hintParts.push(`excludes ${policy.forbiddenChars.slice(0, 6)}${policy.forbiddenChars.length > 6 ? "…" : ""}`);320  if (hintParts.length > 0) {321    const hint = root.appendChild(document.createElement("div"));322    hint.className = "pwgen-policy-hint";323    const accent = document.createElement("span");324    accent.className = "pwgen-hint-accent";325    accent.textContent = "site rules · ";326    const text = document.createTextNode(hintParts.join(" · "));327    hint.appendChild(accent);328    hint.appendChild(text);329  }330331  function regenerate() {332    // Falls back gracefully when the user toggles every charset off — the333    // shared generator forces lowercase in that case rather than throwing.334    password = generatePassword({335      length,336      includeUppercase: upper,337      includeLowercase: lower,338      includeNumbers: numbers,339      includeSymbols: symbols,340      forbiddenChars,341    });342    output.value = password;343    opts.onChange?.(password);344  }345346  output.addEventListener("input", () => {347    password = output.value;348    length = password.length;349    slider.value = String(Math.max(8, Math.min(128, length)));350    lenNum.textContent = String(length);351    opts.onChange?.(password);352  });353354  slider.addEventListener("input", () => {355    length = parseInt(slider.value, 10);356    lenNum.textContent = String(length);357    regenerate();358  });359  regenBtn.addEventListener("click", regenerate);360361  let copyResetTimer: ReturnType<typeof setTimeout> | null = null;362  async function copy(): Promise<void> {363    try {364      await navigator.clipboard.writeText(password);365      copyBtn.classList.add("is-copied");366      if (copyResetTimer) clearTimeout(copyResetTimer);367      copyResetTimer = setTimeout(() => copyBtn.classList.remove("is-copied"), 1400);368    } catch {369      // Clipboard API may be denied — silently no-op; user still has regen UI.370    }371  }372  copyBtn.addEventListener("click", () => { void copy(); });373374  if (opts.initialPassword) {375    password = opts.initialPassword;376    output.value = password;377    opts.onChange?.(password);378  } else {379    regenerate();380  }381382  return {383    root,384    getPassword: () => password,385    copy,386  };387}388389export function observeAnchorPosition(390  anchorEl: HTMLElement,391  onUpdate: () => void392): () => void {393  let rafId = 0;394  let burstUntil = 0;395396  const runUpdate = () => {397    rafId = 0;398    onUpdate();399    if (performance.now() < burstUntil) rafId = requestAnimationFrame(runUpdate);400  };401  const scheduleUpdate = () => { if (!rafId) rafId = requestAnimationFrame(runUpdate); };402  const scheduleBurst = (ms = 220) => {403    burstUntil = Math.max(burstUntil, performance.now() + ms);404    scheduleUpdate();405  };406407  const resizeObserver = new ResizeObserver(() => scheduleBurst());408  resizeObserver.observe(anchorEl);409  if (anchorEl.parentElement) resizeObserver.observe(anchorEl.parentElement);410411  const mutationObserver = new MutationObserver(() => scheduleBurst());412  mutationObserver.observe(anchorEl, { attributes: true, attributeFilter: ["class", "style", "type", "hidden"] });413  if (anchorEl.parentElement) {414    mutationObserver.observe(anchorEl.parentElement, { attributes: true, attributeFilter: ["class", "style", "hidden"] });415  }416417  const onScroll = () => scheduleUpdate();418  window.addEventListener("scroll", onScroll, true);419  window.addEventListener("resize", onScroll);420  window.visualViewport?.addEventListener("resize", onScroll);421  window.visualViewport?.addEventListener("scroll", onScroll);422  anchorEl.addEventListener("focus", () => scheduleBurst());423  anchorEl.addEventListener("input", () => scheduleBurst());424425  scheduleBurst(260);426427  return () => {428    if (rafId) cancelAnimationFrame(rafId);429    resizeObserver.disconnect();430    mutationObserver.disconnect();431    window.removeEventListener("scroll", onScroll, true);432    window.removeEventListener("resize", onScroll);433    window.visualViewport?.removeEventListener("resize", onScroll);434    window.visualViewport?.removeEventListener("scroll", onScroll);435  };436}437438export function injectFieldIcon(field: HTMLInputElement, onClick: () => void): () => void {439  const button = document.createElement("button");440  button.type = "button";441  button.setAttribute("aria-label", "Peach autofill");442  button.title = "Fill with Peach";443  button.innerHTML = peachIconSvg();444  // position: fixed is load-bearing — not absolute. Absolute positioning445  // inherits the nearest positioned ancestor's box, which on sites with446  // overflow:hidden or sticky parents clips or offsets the icon. Fixed447  // anchors to the viewport and escapes all parent layout.448  button.style.cssText = `449    position: fixed; z-index: 2147483646;450    width: 26px; height: 26px; cursor: pointer;451    pointer-events: auto; border: none; padding: 3px;452    display: inline-flex; align-items: center; justify-content: center;453    background: transparent; border-radius: 999px;454    transition: opacity 140ms ease, background 120ms ease, box-shadow 120ms ease, transform 80ms ease;455    opacity: 0;456  `;457  button.addEventListener("mouseenter", () => {458    button.style.background = `color-mix(in srgb, ${accentHex} 12%, transparent)`;459    button.style.boxShadow = `0 0 0 1px color-mix(in srgb, ${accentHex} 18%, transparent), 0 0 14px color-mix(in srgb, ${accentHex} 12%, transparent)`;460    button.style.transform = "scale(1.08)";461  });462  button.addEventListener("mouseleave", () => {463    button.style.background = "transparent";464    button.style.boxShadow = "none";465    button.style.transform = "none";466  });467  button.addEventListener("pointerdown", e => { e.stopPropagation(); e.preventDefault(); });468  button.addEventListener("click", e => { e.stopPropagation(); e.preventDefault(); onClick(); });469470  document.body.appendChild(button);471472  function updatePosition() {473    const rect = field.getBoundingClientRect();474    if (rect.width === 0 || rect.height === 0) {475      button.style.opacity = "0"; button.style.pointerEvents = "none";476      return;477    }478    const sz = 26;479    const inset = Math.max(5, Math.min(10, rect.height * 0.22));480    const top = rect.top + rect.height / 2 - sz / 2;481    // Clamp left so the icon stays fully inside the field's right edge, never482    // spilling onto an adjacent sibling button.483    const minLeft = rect.left + 4;484    const left = Math.max(minLeft, rect.right - sz - inset);485    // Hide if the field is too narrow to fit the icon cleanly (< 40px)486    if (rect.width < 40) {487      button.style.opacity = "0"; button.style.pointerEvents = "none";488      return;489    }490    button.style.top = `${top}px`;491    button.style.left = `${left}px`;492    button.style.opacity = "1"; button.style.pointerEvents = "auto";493  }494  updatePosition();495  requestAnimationFrame(() => { button.style.opacity = "1"; });496  const stopObserving = observeAnchorPosition(field, updatePosition);497  return () => { stopObserving(); button.remove(); };498}499500// All theme-dependent values resolve through tokens scoped to501// .peach-inline-popup[data-theme="dark|light"]. Accent variables502// (--peach-accent, --peach-accent-dim, --peach-glow, --peach-border-accent)503// are identical in both themes — only surface tokens differ. See504// Projects.md §4.14: hardcoded hex inside this stylesheet breaks the505// theme switch — only literal brand-peach in peachIconSvg may stay raw.506const SELECTOR_STYLES = `507  :host { all: initial; }508  *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }509510  .peach-inline-popup[data-theme="dark"] {511    --peach-bg:           #1a1410;512    --peach-bg-card:      #221c16;513    --peach-text:         #f5f0ea;514    --peach-text-dim:     #8a7a6a;515    --peach-text-muted:   #4a3a2a;516    --peach-border:       rgba(255,255,255,0.07);517    --peach-input-bg:     rgba(255,255,255,0.05);518    --peach-input-border: rgba(255,255,255,0.08);519  }520  .peach-inline-popup[data-theme="light"] {521    --peach-bg:           #fdf8f4;522    --peach-bg-card:      #f5ede4;523    --peach-text:         #1c1310;524    --peach-text-dim:     #6b5a4a;525    --peach-text-muted:   #a89080;526    --peach-border:       rgba(0,0,0,0.08);527    --peach-input-bg:     rgba(0,0,0,0.04);528    --peach-input-border: rgba(0,0,0,0.10);529  }530531  .peach-inline-popup {532    background: var(--peach-bg);533    border: 1px solid var(--peach-border-accent, var(--peach-border));534    border-radius: 14px;535    overflow: hidden;536    box-shadow:537      0 8px 40px var(--peach-glow, transparent),538      0 2px 12px rgba(0,0,0,0.5);539    font-family: Inter, -apple-system, BlinkMacSystemFont, sans-serif;540    animation: peach-enter 200ms cubic-bezier(0.16,1,0.3,1) forwards;541    transition: height 220ms cubic-bezier(0.16,1,0.3,1);542  }543  /* Light theme: shadow against a light page is too strong otherwise — drop both544     the accent glow and the dark drop-shadow opacity to keep the popup elegant. */545  .peach-inline-popup[data-theme="light"] {546    box-shadow:547      0 8px 40px color-mix(in srgb, var(--peach-accent) 10%, transparent),548      0 2px 12px rgba(0,0,0,0.12);549  }550  .peach-inline-popup.is-exiting {551    animation: peach-exit 130ms cubic-bezier(0.4,0,1,1) forwards;552    pointer-events: none;553  }554555  @keyframes peach-enter {556    0%   { opacity: 0; transform: translateY(-8px) scale(0.96); filter: blur(3px); }557    65%  { opacity: 1; filter: blur(0); }558    100% { opacity: 1; transform: translateY(0) scale(1); }559  }560  @keyframes peach-exit {561    0%   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }562    100% { opacity: 0; transform: translateY(-4px) scale(0.98); filter: blur(2px); }563  }564  @keyframes peach-slide-in {565    from { opacity: 0; transform: translateX(12px); }566    to   { opacity: 1; transform: translateX(0); }567  }568  @keyframes peach-slide-back {569    from { opacity: 0; transform: translateX(-12px); }570    to   { opacity: 1; transform: translateX(0); }571  }572  .peach-content[data-dir="forward"] { animation: peach-slide-in 150ms cubic-bezier(0.16,1,0.3,1) both; }573  .peach-content[data-dir="back"]    { animation: peach-slide-back 150ms cubic-bezier(0.16,1,0.3,1) both; }574575  /* Domain header */576  .domain-header {577    padding: 9px 13px 7px;578    border-bottom: 1px solid var(--peach-border);579    display: flex; align-items: center; justify-content: space-between;580    gap: 8px;581  }582  .domain-header-text {583    display: flex; flex-direction: column; gap: 2px;584    min-width: 0; flex: 1;585  }586  .domain-eyebrow {587    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;588    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;589  }590  .domain-name {591    font-size: 10px; color: color-mix(in srgb, var(--peach-accent) 60%, transparent);592    font-family: "IBM Plex Mono", monospace;593    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;594  }595  .domain-header-actions {596    display: inline-flex; align-items: center; gap: 5px;597    flex-shrink: 0;598  }599  .domain-add-btn,600  .domain-search-btn {601    flex-shrink: 0;602    width: 22px; height: 22px;603    display: inline-flex; align-items: center; justify-content: center;604    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);605    border: 1px solid color-mix(in srgb, var(--peach-accent) 28%, transparent);606    border-radius: 6px;607    color: var(--peach-accent);608    cursor: pointer; padding: 0;609    transition: background 120ms, border-color 120ms, transform 80ms;610    font-family: "IBM Plex Mono", monospace;611    font-size: 14px; line-height: 1;612  }613  .domain-add-btn:hover,614  .domain-search-btn:hover {615    background: color-mix(in srgb, var(--peach-accent) 22%, transparent);616    border-color: color-mix(in srgb, var(--peach-accent) 48%, transparent);617    transform: scale(1.06);618  }619  .domain-add-btn:active,620  .domain-search-btn:active { transform: scale(0.96); }621622  /* Search */623  .search-wrap {624    padding: 9px 12px 7px;625    border-bottom: 1px solid var(--peach-border);626  }627  .search {628    width: 100%; background: var(--peach-input-bg);629    border: 1px solid var(--peach-input-border);630    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;631    font-size: 12px; outline: none; font-family: "IBM Plex Mono", monospace;632    transition: border-color 120ms, box-shadow 120ms;633  }634  .search:focus {635    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);636    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);637  }638  .search::placeholder { color: var(--peach-text-muted); }639640  /* Results */641  .results { max-height: 256px; overflow-y: auto; scrollbar-width: none; }642  .results::-webkit-scrollbar { display: none; }643644  /* Entry rows */645  .entry {646    display: flex; align-items: center; padding: 8px 12px;647    cursor: pointer; border-bottom: 1px solid var(--peach-border);648    transition: background 70ms; position: relative; outline: none;649  }650  .entry:last-child { border-bottom: none; }651  .entry:hover { background: color-mix(in srgb, var(--peach-text) 4%, transparent); }652  .entry.focused { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }653  .entry.focused::before {654    content: ""; position: absolute; left: 0; top: 3px; bottom: 3px;655    width: 2px; border-radius: 2px;656    background: color-mix(in srgb, var(--peach-accent) 55%, transparent);657  }658659  .entry-icon {660    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;661    background: var(--peach-input-bg); border: 1px solid var(--peach-border);662    display: flex; align-items: center; justify-content: center;663    overflow: hidden; margin-right: 10px;664  }665  .entry-icon img { width: 15px; height: 15px; border-radius: 2px; display: block; }666  .entry-icon.is-new {667    background: color-mix(in srgb, var(--peach-accent) 8%, transparent);668    border-color: color-mix(in srgb, var(--peach-accent) 15%, transparent);669    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);670  }671672  .entry-info { flex: 1; min-width: 0; }673  .entry-title {674    font-size: 12.5px; color: var(--peach-text);675    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;676    line-height: 1.3;677  }678  .entry-title.is-new { color: color-mix(in srgb, var(--peach-accent) 90%, transparent); font-size: 12px; }679  .entry-sub {680    font-size: 10px; color: var(--peach-text-dim);681    font-family: "IBM Plex Mono", monospace;682    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;683    margin-top: 1px;684  }685686  .totp-badge {687    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;688    border-radius: 4px; background: color-mix(in srgb, var(--peach-accent) 10%, transparent);689    color: color-mix(in srgb, var(--peach-accent) 75%, transparent);690    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 8px;691  }692  .passkey-badge {693    font-size: 8px; letter-spacing: 0.04em; padding: 2px 6px;694    border-radius: 4px;695    background: color-mix(in srgb, var(--peach-accent) 14%, transparent);696    color: color-mix(in srgb, var(--peach-accent) 85%, transparent);697    border: 1px solid color-mix(in srgb, var(--peach-accent) 24%, transparent);698    font-family: "IBM Plex Mono", monospace; flex-shrink: 0; margin-left: 6px;699  }700701  .divider { height: 1px; background: var(--peach-border); margin: 2px 0; }702703  .empty-hint {704    padding: 14px 13px; font-size: 11px; color: var(--peach-text-dim);705    font-family: "IBM Plex Mono", monospace;706  }707708  /* Create form */709  .create-form-wrap {710    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;711  }712  .create-head {713    display: flex; align-items: center; gap: 8px;714    padding: 10px 12px; border-bottom: 1px solid var(--peach-border);715  }716  .back-btn {717    background: transparent; border: none; cursor: pointer;718    color: var(--peach-text-dim); padding: 3px; border-radius: 5px;719    display: flex; align-items: center; line-height: 0;720    transition: color 100ms, background 100ms;721  }722  .back-btn:hover { color: var(--peach-text); background: var(--peach-input-bg); }723  .create-label { font-size: 12px; color: var(--peach-text); font-weight: 500; flex: 1; }724  /* minmax(0, 1fr) caps the grid track at the popup width — without it,725     long monospace content (e.g. a 60-char generated password) would726     auto-size the track wider than the popup and overflow the right edge. */727  .create-body { padding: 12px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }728  .f-group { display: grid; grid-template-columns: minmax(0, 1fr); gap: 3px; }729  .f-label {730    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;731    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;732  }733  .f-input {734    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);735    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;736    font-size: 11px; font-family: "IBM Plex Mono", monospace;737    outline: none; width: 100%; transition: border-color 120ms, box-shadow 120ms;738  }739  .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); }740  .f-input::placeholder { color: var(--peach-text-muted); }741  .f-input.url-f { font-size: 10px; color: var(--peach-text-dim); letter-spacing: 0.01em; }742  .f-row { display: flex; gap: 6px; }743  .f-row .f-input { flex: 1; min-width: 0; }744  .gen-btn {745    padding: 0 10px; border-radius: 7px; border: none;746    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);747    color: color-mix(in srgb, var(--peach-accent) 80%, transparent);748    font-size: 10px; font-family: "IBM Plex Mono", monospace;749    cursor: pointer; white-space: nowrap; flex-shrink: 0;750    display: flex; align-items: center; gap: 4px;751    transition: background 100ms;752  }753  .gen-btn:hover { background: color-mix(in srgb, var(--peach-accent) 18%, transparent); }754  .gen-toggle-link {755    background: none; border: none; padding: 2px 0;756    color: color-mix(in srgb, var(--peach-accent) 60%, transparent);757    font-size: 10px; font-family: "IBM Plex Mono", monospace;758    cursor: pointer; text-align: left; transition: color 100ms;759  }760  .gen-toggle-link:hover { color: var(--peach-accent); }761  .save-btn {762    width: 100%; padding: 8px; border-radius: 8px; border: none;763    background: var(--peach-accent); color: #fff; font-size: 12px;764    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;765    transition: background 120ms, box-shadow 120ms, transform 80ms;766    letter-spacing: 0.01em;767  }768  .save-btn:hover {769    background: color-mix(in srgb, var(--peach-accent) 82%, #000);770    box-shadow: 0 4px 20px var(--peach-glow, transparent);771  }772  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }773  .url-hint {774    font-size: 9px; color: color-mix(in srgb, var(--peach-accent) 45%, transparent);775    font-family: "IBM Plex Mono", monospace; font-style: italic;776  }777778  /* Success */779  .success-wrap {780    display: flex; flex-direction: column; align-items: center;781    padding: 24px 16px 20px; gap: 8px;782    animation: su-in 280ms cubic-bezier(0.16,1,0.3,1) both;783  }784  @keyframes su-in { from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:none} }785  .success-ring {786    width: 40px; height: 40px; border-radius: 50%;787    background: rgba(123,144,96,0.10); border: 1.5px solid rgba(123,144,96,0.25);788    display: flex; align-items: center; justify-content: center;789  }790  .success-text { font-size: 12.5px; color: var(--peach-text); font-weight: 500; }791  .success-sub { font-size: 10px; color: var(--peach-text-dim); font-family:"IBM Plex Mono",monospace; }792793  /* Silver platter (State 1 — single match) */794  .silver-platter {795    padding: 14px 14px 12px;796    display: flex; flex-direction: column; gap: 6px;797  }798  .sp-title {799    font-size: 14px; font-weight: 500; color: var(--peach-text);800    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;801    line-height: 1.25;802  }803  .sp-identity-row {804    display: flex; align-items: baseline; gap: 5px; margin-bottom: 3px;805  }806  .sp-identity-label {807    font-size: 9px; font-weight: 600; letter-spacing: 0.05em;808    text-transform: uppercase; color: var(--peach-text-muted); flex-shrink: 0;809  }810  .sp-username {811    font-size: 12px; color: var(--peach-text-dim);812    font-family: "IBM Plex Mono", monospace;813    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;814    margin-bottom: 0;815  }816  .sp-identity-row + .sp-fill-btn, .sp-username + .sp-fill-btn { margin-top: 6px; }817  .sp-fill-btn {818    width: 100%; padding: 11px; border-radius: 9px; border: none;819    background: var(--peach-accent); color: #fff;820    font-size: 13px; font-weight: 500; cursor: pointer;821    font-family: Inter, sans-serif; letter-spacing: 0.01em;822    display: flex; align-items: center; justify-content: center; min-height: 38px;823    transition: filter 120ms ease, transform 80ms ease, box-shadow 120ms ease, background 120ms ease;824  }825  .sp-fill-btn:hover {826    filter: brightness(1.1);827    box-shadow: 0 4px 20px var(--peach-glow, transparent);828    transform: translateY(-1px);829  }830  .sp-fill-btn:active { transform: translateY(0); filter: brightness(0.95); }831  .sp-fill-btn.filled {832    background: #16a34a; transform: none; filter: none;833    box-shadow: 0 4px 16px rgba(22,163,74,0.35);834    cursor: default;835  }836  .sp-fill-btn:disabled { cursor: default; }837  .sp-actions-group {838    margin-top: 6px;839    display: flex; flex-direction: column; gap: 4px;840  }841  .sp-actions-label {842    font-size: 8px; letter-spacing: 0.18em; text-transform: uppercase;843    color: var(--peach-text-muted);844    font-family: "IBM Plex Mono", monospace;845    text-align: center;846  }847  .sp-actions {848    display: flex; gap: 4px; justify-content: space-between; align-items: center;849  }850  .sp-action-btn {851    flex: 1; height: 28px; border: none; border-radius: 6px;852    background: transparent; color: var(--peach-text-dim);853    font-size: 12px; cursor: pointer;854    transition: background 120ms ease, color 120ms ease;855    font-family: Inter, sans-serif; letter-spacing: 0.04em;856    display: inline-flex; align-items: center; justify-content: center; gap: 4px;857    white-space: nowrap; overflow: hidden;858  }859  .sp-action-btn:hover:not(:disabled) {860    background: color-mix(in srgb, var(--peach-text) 5%, transparent);861    color: var(--peach-text);862  }863  .sp-action-btn:disabled { opacity: 0.3; cursor: default; }864  .sp-action-btn.flashed {865    color: var(--peach-accent);866    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);867  }868869  /* TOTP tray — shown below the silver-platter secondary actions */870  .sp-tray {871    margin-top: 8px;872    padding: 10px 12px;873    border-radius: 9px;874    background: var(--peach-input-bg);875    border: 1px solid var(--peach-input-border);876    display: flex; align-items: center; gap: 12px;877    animation: peach-slide-in 180ms cubic-bezier(0.16,1,0.3,1) both;878  }879  .sp-tray-label {880    font-size: 8px; letter-spacing: 0.12em; text-transform: uppercase;881    color: var(--peach-text-dim); font-family: "IBM Plex Mono", monospace;882    flex-shrink: 0;883  }884  .sp-totp-code {885    font-size: 18px; font-weight: 500;886    color: var(--peach-text);887    font-family: "IBM Plex Mono", monospace;888    letter-spacing: 0.12em;889    flex: 1;890    text-align: center;891  }892  .sp-totp-ring {893    width: 22px; height: 22px; flex-shrink: 0;894  }895  .sp-totp-ring .ring-track { stroke: var(--peach-input-border); }896  .sp-totp-ring .ring-fill {897    stroke: var(--peach-accent);898    transition: stroke-dashoffset 1s linear;899    transform: rotate(-90deg);900    transform-origin: center;901  }902  .sp-totp-copy {903    background: transparent; border: none; cursor: pointer;904    padding: 4px 8px; border-radius: 5px;905    color: var(--peach-text-dim); font-size: 11px;906    font-family: Inter, sans-serif;907    transition: background 120ms, color 120ms;908  }909  .sp-totp-copy:hover {910    background: color-mix(in srgb, var(--peach-text) 5%, transparent);911    color: var(--peach-text);912  }913914  /* Card silver platter (State 7) — reuses .sp-* primary action classes */915  .card-platter {916    padding: 12px 14px 10px;917    display: flex; flex-direction: column; gap: 4px;918  }919  .cp-network {920    font-size: 10px; font-weight: 600;921    color: var(--peach-accent);922    letter-spacing: 0.08em; text-transform: uppercase;923    font-family: Inter, sans-serif;924  }925  .cp-nickname {926    font-size: 14px; font-weight: 500; color: var(--peach-text);927    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;928    line-height: 1.2;929  }930  .cp-last4 {931    font-size: 12px; color: var(--peach-text-dim);932    font-family: "IBM Plex Mono", monospace;933    letter-spacing: 0.04em;934    margin-top: 2px;935  }936  .cp-meta {937    font-size: 11px; color: var(--peach-text-dim);938    font-family: "IBM Plex Mono", monospace;939    margin-top: 2px;940    display: flex; gap: 10px; align-items: center;941  }942  .cp-meta-sep { opacity: 0.5; }943  .cp-fill-wrap { margin-top: 10px; }944945  /* Locked state */946  .locked-wrap {947    display: flex; flex-direction: column; align-items: stretch;948    padding: 14px 13px 13px; gap: 9px;949  }950  .locked-head { display: flex; align-items: center; gap: 8px; padding-bottom: 2px; }951  .locked-icon {952    width: 24px; height: 24px; border-radius: 6px; flex-shrink: 0;953    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);954    display: flex; align-items: center; justify-content: center;955  }956  .locked-title { font-size: 11.5px; color: var(--peach-text); font-weight: 500; }957  .locked-sub { font-size: 10.5px; line-height: 1.4; color: var(--peach-text-muted); text-align: center; margin: 2px 0 2px; }958  .locked-input {959    width: 100%; background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);960    border-radius: 7px; color: var(--peach-text); padding: 7px 10px;961    font-size: 11px; font-family: "IBM Plex Mono", monospace;962    outline: none; transition: border-color 120ms, box-shadow 120ms;963  }964  .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); }965  .locked-input::placeholder { color: var(--peach-text-muted); }966  .locked-btn {967    width: 100%; padding: 8px; border-radius: 8px; border: none;968    background: var(--peach-accent); color: #fff; font-size: 12px;969    font-family: Inter, sans-serif; cursor: pointer; font-weight: 500;970    transition: background 120ms;971    letter-spacing: 0.01em;972    box-shadow: 0 2px 16px var(--peach-glow, transparent);973    animation: peach-pulse-glow 2.4s ease-in-out infinite;974  }975  .locked-btn:hover { background: color-mix(in srgb, var(--peach-accent) 82%, #000); }976  .locked-btn:disabled { opacity: 0.4; cursor: not-allowed; animation: none; }977  .locked-error {978    font-size: 10px; color: rgba(220,80,60,0.85);979    font-family: "IBM Plex Mono", monospace;980  }981982  @keyframes peach-pulse-glow {983    0%, 100% { box-shadow: 0 2px 16px var(--peach-glow, transparent); }984    50%      { box-shadow: 0 2px 28px var(--peach-glow, transparent),985                            0 0 48px var(--peach-glow, transparent); }986  }987988  /* ── State 10: identity helper ─────────────────────────────── */989  .identity-list {990    max-height: 192px; overflow-y: auto; padding: 4px 0;991    scrollbar-width: none;992  }993  .identity-list::-webkit-scrollbar { display: none; }994  .peach-identity-row {995    display: flex; align-items: center; gap: 10px;996    padding: 9px 12px; cursor: pointer; border-radius: 8px;997    transition: background 100ms ease;998  }999  .peach-identity-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1000  .peach-identity-value {1001    font-family: "IBM Plex Mono", monospace; font-size: 13px;1002    color: var(--peach-text); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;1003  }1004  .peach-identity-meta { font-size: 10px; color: var(--peach-text-muted); flex-shrink: 0; }1005  .identity-alt-row {1006    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1007    border-radius: 8px; transition: background 100ms ease;1008    color: var(--peach-text-dim); font-size: 12px; font-family: Inter, sans-serif;1009  }1010  .identity-alt-row:hover { background: color-mix(in srgb, var(--peach-text) 6%, transparent); }1011  .identity-escape-row {1012    display: flex; align-items: center; padding: 8px 12px; cursor: pointer;1013    border-radius: 8px; transition: background 100ms ease; outline: none;1014    color: var(--peach-accent); font-size: 11px; font-family: Inter, sans-serif;1015    margin-top: 2px;1016  }1017  .identity-escape-row:hover, .identity-escape-row:focus { background: color-mix(in srgb, var(--peach-accent) 8%, transparent); }1018  .identity-alt-input-wrap { display: none; padding: 0 12px 8px; gap: 6px; align-items: center; }1019  .identity-alt-input-wrap.open { display: flex; }1020  .identity-alt-input {1021    flex: 1; height: 32px; padding: 0 10px; border-radius: 7px;1022    border: 1px solid var(--peach-input-border); background: var(--peach-input-bg);1023    color: var(--peach-text); font-family: "IBM Plex Mono", monospace; font-size: 12px;1024    outline: none; transition: border-color 120ms;1025  }1026  .identity-alt-input:focus {1027    border-color: color-mix(in srgb, var(--peach-accent) 40%, transparent);1028    box-shadow: 0 0 0 2px color-mix(in srgb, var(--peach-accent) 10%, transparent);1029  }1030  .identity-alt-confirm {1031    height: 32px; padding: 0 12px; border-radius: 7px; border: none;1032    background: var(--peach-accent); color: #fff; font-size: 12px;1033    cursor: pointer; font-family: Inter, sans-serif; flex-shrink: 0;1034  }1035  /* ── Generator view (after identity picked) ────────────────── */1036  .gen-view { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1037  .gen-confirmed {1038    display: flex; align-items: center; gap: 8px; padding: 7px 10px;1039    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1040    border-radius: 8px;1041  }1042  .gen-confirmed-check { color: var(--peach-accent); font-size: 13px; font-weight: 600; }1043  .gen-confirmed-val {1044    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1045    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1046  }1047  .gen-label {1048    font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase;1049    color: var(--peach-text-muted); font-family: "IBM Plex Mono", monospace;1050  }1051  .gen-pw-row { display: flex; gap: 6px; align-items: center; }1052  .gen-pw-val {1053    flex: 1; padding: 8px 10px; border-radius: 7px;1054    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1055    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1056    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;1057  }1058  .gen-regen-btn {1059    height: 34px; padding: 0 10px; border-radius: 7px; border: none;1060    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1061    color: var(--peach-text-dim); font-size: 11px; cursor: pointer;1062    font-family: "IBM Plex Mono", monospace; transition: background 100ms ease;1063  }1064  .gen-regen-btn:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1065  .gen-fill-btn {1066    padding: 10px; border-radius: 8px; border: none;1067    background: var(--peach-accent); color: #fff; font-size: 13px; font-weight: 500;1068    cursor: pointer; font-family: Inter, sans-serif; letter-spacing: 0.01em;1069    transition: filter 120ms ease, transform 80ms ease;1070  }1071  .gen-fill-btn:hover { filter: brightness(1.08); transform: translateY(-1px); }1072  .gen-fill-btn:active { transform: translateY(0); }10731074  /* ── Smart password generator (parity with main UI compact mode) ─── */1075  .pwgen-block { display: flex; flex-direction: column; gap: 8px; }1076  .pwgen-display-row {1077    display: flex; align-items: center; gap: 6px;1078    padding: 8px 10px; border-radius: 7px;1079    background: var(--peach-input-bg); border: 1px solid var(--peach-input-border);1080  }1081  .pwgen-output {1082    flex: 1; min-width: 0; width: 0;1083    font-family: "IBM Plex Mono", monospace; font-size: 12px;1084    color: var(--peach-text);1085    background: transparent; border: none; outline: none; padding: 0;1086  }1087  .pwgen-icon-btn {1088    flex-shrink: 0;1089    width: 26px; height: 26px;1090    display: inline-flex; align-items: center; justify-content: center;1091    background: transparent; border: 1px solid var(--peach-input-border);1092    border-radius: 6px; color: var(--peach-text-dim); cursor: pointer;1093    padding: 0; transition: background 100ms, color 100ms, border-color 100ms;1094  }1095  .pwgen-icon-btn:hover {1096    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1097    color: var(--peach-accent);1098    border-color: color-mix(in srgb, var(--peach-accent) 30%, transparent);1099  }1100  .pwgen-icon-btn.is-copied {1101    background: color-mix(in srgb, var(--peach-accent) 18%, transparent);1102    color: var(--peach-accent);1103    border-color: color-mix(in srgb, var(--peach-accent) 45%, transparent);1104  }1105  .pwgen-controls-row {1106    display: flex; align-items: center; gap: 8px;1107    flex-wrap: wrap;1108  }1109  .pwgen-slider {1110    flex: 1; min-width: 110px;1111    accent-color: var(--peach-accent);1112    cursor: pointer; height: 2px; background: transparent;1113  }1114  .pwgen-len-num {1115    font-family: "IBM Plex Mono", monospace; font-size: 11px;1116    color: var(--peach-accent); min-width: 22px; text-align: right;1117  }1118  .pwgen-len-num--edit { cursor: text; border-bottom: 1px dotted color-mix(in srgb, var(--peach-accent) 50%, transparent); }1119  .pwgen-len-input {1120    font-family: "IBM Plex Mono", monospace; font-size: 11px;1121    color: var(--peach-accent); width: 28px; text-align: right;1122    background: transparent; border: none; border-bottom: 1px solid var(--peach-accent);1123    outline: none; padding: 0; min-width: 22px;1124  }1125  @keyframes identity-suggest-in {1126    from { opacity: 0; transform: translateY(-4px); }1127    to   { opacity: 1; transform: none; }1128  }1129  .identity-suggest-list { display: flex; flex-direction: column; gap: 1px; margin-top: 3px;1130    animation: identity-suggest-in 180ms cubic-bezier(0.16,1,0.3,1) both; }1131  .identity-filter-row { display: flex; align-items: center; gap: 4px; padding: 2px 0 4px; }1132  .identity-collapse-btn {1133    margin-left: auto; background: transparent; border: none; cursor: pointer;1134    color: var(--peach-text-muted); padding: 2px 4px; display: flex; align-items: center;1135    line-height: 0; border-radius: 3px;1136    transition: color 100ms ease, transform 220ms cubic-bezier(0.16,1,0.3,1);1137  }1138  .identity-collapse-btn:hover { color: var(--peach-text); }1139  .identity-collapse-btn.is-collapsed { transform: rotate(-90deg); }1140  .identity-rows { display: grid; grid-template-rows: 1fr;1141    transition: grid-template-rows 220ms cubic-bezier(0.16,1,0.3,1); }1142  .identity-rows.is-collapsed { grid-template-rows: 0fr; }1143  .identity-rows-inner { overflow-y: auto; min-height: 0; max-height: 148px;1144    scrollbar-width: thin; scrollbar-color: var(--peach-text-muted) transparent;1145    mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%);1146    -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 18px), transparent 100%); }1147  .identity-rows-inner::-webkit-scrollbar { width: 4px; }1148  .identity-rows-inner::-webkit-scrollbar-track { background: transparent; }1149  .identity-rows-inner::-webkit-scrollbar-thumb { background: var(--peach-text-muted); border-radius: 2px; }1150  .identity-filter-pill {1151    padding: 2px 7px; border-radius: 999px;1152    border: 1px solid var(--peach-input-border);1153    background: transparent; color: var(--peach-text-muted);1154    font-family: "IBM Plex Mono", monospace; font-size: 9px;1155    cursor: pointer; transition: border-color 80ms, background 80ms, color 80ms;1156  }1157  .identity-filter-pill.is-on {1158    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1159    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1160    color: var(--peach-accent);1161  }1162  .identity-suggest-row {1163    display: flex; align-items: center; gap: 5px;1164    width: 100%; padding: 4px 6px; border-radius: 5px; border: none;1165    background: transparent; cursor: pointer; text-align: left;1166    transition: background 80ms;1167  }1168  .identity-suggest-row:hover,1169  .identity-suggest-row:focus { background: color-mix(in srgb, var(--peach-accent) 10%, transparent); outline: none; }1170  .identity-suggest-val {1171    font-family: "IBM Plex Mono", monospace; font-size: 10px; color: var(--peach-text);1172    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;1173  }1174  .identity-suggest-type {1175    font-family: "IBM Plex Mono", monospace; font-size: 8px; font-weight: 600;1176    flex-shrink: 0; padding: 1px 3px; border-radius: 3px;1177  }1178  .identity-suggest-type--email {1179    color: color-mix(in srgb, var(--peach-accent) 70%, transparent);1180    background: color-mix(in srgb, var(--peach-accent) 12%, transparent);1181  }1182  .identity-suggest-type--username {1183    color: var(--peach-text-muted);1184    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1185  }1186  .identity-suggest-meta {1187    font-family: "IBM Plex Mono", monospace; font-size: 9px;1188    color: var(--peach-text-muted); flex-shrink: 0;1189  }1190  .pwgen-pills { display: flex; gap: 5px; flex-wrap: wrap; }1191  .pwgen-pill {1192    padding: 3px 8px; border-radius: 999px;1193    border: 1px solid var(--peach-input-border);1194    background: transparent; color: var(--peach-text-muted);1195    font-family: "IBM Plex Mono", monospace; font-size: 9px;1196    letter-spacing: 0.06em; cursor: pointer;1197    transition: all 130ms ease;1198  }1199  .pwgen-pill.is-on {1200    border-color: color-mix(in srgb, var(--peach-accent) 50%, transparent);1201    background: color-mix(in srgb, var(--peach-accent) 10%, transparent);1202    color: var(--peach-accent);1203  }1204  .pwgen-pill:not(.is-on):hover {1205    color: var(--peach-text-dim);1206    border-color: var(--peach-text-muted);1207  }1208  .pwgen-policy-hint {1209    font-size: 10px; color: var(--peach-text-muted);1210    font-family: "IBM Plex Mono", monospace; letter-spacing: 0.04em;1211    line-height: 1.3;1212  }1213  .pwgen-policy-hint .pwgen-hint-accent { color: var(--peach-accent); }12141215  /* ── Save offer (after password filled) ───────────────────── */1216  .save-offer { padding: 12px; display: flex; flex-direction: column; gap: 8px; }1217  .save-offer-title {1218    font-size: 12px; font-weight: 600; color: var(--peach-text); font-family: Inter, sans-serif;1219  }1220  .save-offer-row {1221    display: flex; align-items: center; gap: 8px; padding: 6px 8px;1222    border-radius: 7px; background: var(--peach-input-bg);1223    border: 1px solid var(--peach-input-border);1224  }1225  .save-offer-lbl {1226    font-size: 10px; color: var(--peach-text-muted); width: 54px; flex-shrink: 0;1227    font-family: "IBM Plex Mono", monospace;1228  }1229  .save-offer-val {1230    font-family: "IBM Plex Mono", monospace; font-size: 12px; color: var(--peach-text);1231    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;1232  }1233  .save-offer-btns { display: flex; gap: 8px; margin-top: 4px; }1234  .save-offer-save {1235    flex: 1; padding: 9px; border-radius: 8px; border: none;1236    background: var(--peach-accent); color: #fff; font-size: 13px;1237    cursor: pointer; font-family: Inter, sans-serif; transition: filter 120ms ease;1238  }1239  .save-offer-save:hover { filter: brightness(1.08); }1240  .save-offer-skip {1241    flex: 1; padding: 9px; border-radius: 8px; border: none;1242    background: color-mix(in srgb, var(--peach-text) 8%, transparent);1243    color: var(--peach-text-dim); font-size: 13px; cursor: pointer;1244    font-family: Inter, sans-serif; transition: background 100ms ease;1245  }1246  .save-offer-skip:hover { background: color-mix(in srgb, var(--peach-text) 14%, transparent); }1247`;12481249export function showAutofillSelector(1250  anchorEl: HTMLInputElement,1251  entries: SelectorEntry[],1252  onSelect: (id: string) => void,1253  options: SelectorOptions = {}1254): () => void {1255  const host = document.createElement("div");1256  host.style.cssText = "position: absolute; z-index: 2147483647;";1257  host.style.setProperty("--peach-accent", accentHex);1258  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));1259  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));1260  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));1261  const shadow = host.attachShadow({ mode: "closed" });12621263  const style = shadow.appendChild(document.createElement("style"));1264  style.textContent = SELECTOR_STYLES;12651266  const rect = anchorEl.getBoundingClientRect();1267  host.style.top = `${rect.bottom + window.scrollY + 5}px`;1268  host.style.left = `${rect.left + window.scrollX}px`;1269  // Spec §1.1: 320px width. The Math.max() floor preserves usability on1270  // wide single-input fields (e.g. centered email input on signup pages).1271  // Frozen at open time — updatePosition re-asserts this so page CSS cannot1272  // expand the host after the initial measurement.1273  const popupWidth = Math.min(Math.max(rect.width, 320), 400);1274  host.style.width = `${popupWidth}px`;12751276  const container = shadow.appendChild(document.createElement("div"));1277  container.className = "peach-inline-popup";1278  container.setAttribute("data-theme", popupTheme);12791280  const searchableEntries = options.searchableEntries ?? [];1281  const { origin: sOrigin, title: sTitle, loginSubdomain } = smartUrl();12821283  let query = "";1284  let focusedIndex = -1;1285  let currentMode: "list" | "create" | "success" | "silver-platter" = "list";1286  let searchInput: HTMLInputElement | null = null;1287  // Tracks the silver-platter entry the user pivoted away from, so the1288  // search/list header can offer a one-click way back to it. null when the1289  // popup never showed a single-match platter (e.g. multi-match list view).1290  let silverPlatterOrigin: SelectorEntry | null = null;1291  // Hooks any sub-state owns for cleanup at dismiss time. Today: TOTP tray1292  // setInterval. Add to this list — don't fan out the dismiss function.1293  const cleanupHooks: Array<() => void> = [];12941295  // Smooth height transitions whenever content changes height.1296  // ResizeObserver fires on natural height changes; we freeze the old height,1297  // then animate to the new one so the surface never jumps.1298  {1299    let prevH = 0;1300    let blocked = false;1301    const heightRo = new ResizeObserver(([entry]) => {1302      if (blocked) return;1303      const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;1304      if (prevH > 0 && Math.abs(h - prevH) > 1) {1305        blocked = true;1306        container.style.height = `${prevH}px`;1307        requestAnimationFrame(() => requestAnimationFrame(() => {1308          container.style.height = `${h}px`;1309          prevH = h;1310          const onEnd = (e: TransitionEvent) => {1311            if (e.propertyName !== "height") return;1312            container.style.height = "";1313            blocked = false;1314            container.removeEventListener("transitionend", onEnd);1315          };1316          container.addEventListener("transitionend", onEnd);1317        }));1318      } else {1319        prevH = h;1320      }1321    });1322    heightRo.observe(container);1323    cleanupHooks.push(() => heightRo.disconnect());1324  }13251326  // Pre-capture the anchor field value for username prefill1327  const preUsername = (anchorEl.type !== "password") ? (anchorEl.value?.trim() ?? "") : "";1328  const pwInForm = anchorEl.closest("form")?.querySelector<HTMLInputElement>("input[type='password']");1329  const prePassword = pwInForm?.value?.trim() ?? (anchorEl.type === "password" ? anchorEl.value?.trim() : "") ?? "";13301331  function uniqueEntries(list: SelectorEntry[]): SelectorEntry[] {1332    const seen = new Set<string>();1333    return list.filter(e => { if (seen.has(e.id)) return false; seen.add(e.id); return true; });1334  }13351336  function filterEntries(source: SelectorEntry[], value: string): SelectorEntry[] {1337    const q = value.trim().toLowerCase();1338    const deduped = uniqueEntries(source);1339    if (!q) return deduped.slice(0, 8);1340    return deduped.filter(e =>1341      [e.title, e.username ?? "", e.url ?? ""].join(" ").toLowerCase().includes(q)1342    ).slice(0, 12);1343  }13441345  function activeEntries(): SelectorEntry[] {1346    // When user is typing a search, filter across all known entries (domain matches + vault)1347    if (query.trim()) {1348      const merged = uniqueEntries([...entries, ...searchableEntries]);1349      return filterEntries(merged, query);1350    }1351    // Default: show domain matches; fall back to vault search when no matches1352    if (entries.length > 0) return entries;1353    return filterEntries(searchableEntries, "").slice(0, 8);1354  }13551356  function makeEntryIcon(url?: string, isNew = false): HTMLDivElement {1357    const icon = document.createElement("div");1358    icon.className = `entry-icon${isNew ? " is-new" : ""}`;1359    if (isNew) {1360      icon.innerHTML = plusSvgStr();1361    } else {1362      // Use the generic key glyph for all entries in the page-injected selector.1363      // Avoids disclosing vault domains to any third party and avoids needing1364      // to expose the browser favicon API to page context via web_accessible_resources.1365      void url;1366      icon.innerHTML = keySvgStr();1367    }1368    return icon;1369  }13701371  function renderIdentityHelper() {1372    container.innerHTML = "";1373    const identities = options.savedIdentities ?? [];13741375    // Header: "NEW ACCOUNT" + domain name1376    const hdr = container.appendChild(document.createElement("div"));1377    hdr.className = "domain-header";1378    const eyebrow = hdr.appendChild(document.createElement("div"));1379    eyebrow.className = "domain-eyebrow";1380    eyebrow.textContent = "NEW ACCOUNT";1381    const domName = hdr.appendChild(document.createElement("div"));1382    domName.className = "domain-name";1383    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");13841385    // Identity rows1386    const list = container.appendChild(document.createElement("div"));1387    list.className = "identity-list";1388    for (const id of identities) {1389      const row = list.appendChild(document.createElement("div"));1390      row.className = "peach-identity-row";1391      row.setAttribute("tabindex", "-1");1392      const val = row.appendChild(document.createElement("div"));1393      val.className = "peach-identity-value";1394      val.textContent = id.value;1395      const meta = row.appendChild(document.createElement("div"));1396      meta.className = "peach-identity-meta";1397      meta.textContent = `used ${id.useCount}×`;1398      row.addEventListener("click", () => {1399        options.onFillFields?.(id.value, "");1400        renderGenerator(id.value);1401      });1402    }14031404    // Divider before "Use a different email…"1405    if (identities.length > 0) {1406      container.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1407    }14081409    // "Use a different email…" expandable row1410    const altRow = container.appendChild(document.createElement("div"));1411    altRow.className = "identity-alt-row";1412    altRow.textContent = "+ Use a different email…";14131414    const altInputWrap = container.appendChild(document.createElement("div"));1415    altInputWrap.className = "identity-alt-input-wrap";1416    const altInput = altInputWrap.appendChild(document.createElement("input"));1417    altInput.className = "identity-alt-input";1418    altInput.type = "email";1419    altInput.placeholder = "[email protected]";1420    altInput.setAttribute("autocomplete", "off");1421    const altConfirm = altInputWrap.appendChild(document.createElement("button"));1422    altConfirm.className = "identity-alt-confirm";1423    altConfirm.type = "button";1424    altConfirm.textContent = "✓";14251426    function fillCustomEmail() {1427      const v = altInput.value.trim();1428      if (!v) return;1429      options.onFillFields?.(v, "");1430      renderGenerator(v);1431    }14321433    altRow.addEventListener("click", () => {1434      altRow.style.display = "none";1435      altInputWrap.classList.add("open");1436      altInput.focus();1437    });1438    altConfirm.addEventListener("click", fillCustomEmail);1439    altInput.addEventListener("keydown", (e) => {1440      if (e.key === "Enter") { e.preventDefault(); fillCustomEmail(); }1441    });14421443    // Escape hatch: user already has a vault entry for this site but it1444    // wasn't detected (different domain, old entry, etc.). Tapping this1445    // switches to the full searchable list so they can find and fill it;1446    // selecting an entry there will trigger the remember-site toast if1447    // the domain isn't already associated.1448    if ((options.searchableEntries?.length ?? 0) > 0) {1449      const escapeRow = container.appendChild(document.createElement("div"));1450      escapeRow.className = "identity-escape-row";1451      escapeRow.textContent = "I already have an account →";1452      escapeRow.setAttribute("tabindex", "0");1453      escapeRow.addEventListener("click", () => renderList());1454      escapeRow.addEventListener("keydown", (e) => {1455        if (e.key === "Enter" || e.key === " ") { e.preventDefault(); renderList(); }1456      });1457    }1458  }14591460  function renderGenerator(filledEmail: string) {1461    container.innerHTML = "";1462    const sitePolicy = detectPasswordPolicy();14631464    const wrap = container.appendChild(document.createElement("div"));1465    wrap.className = "gen-view";14661467    // Header: domain + NEW ACCOUNT1468    const hdrRow = wrap.appendChild(document.createElement("div"));1469    hdrRow.className = "domain-header";1470    const eyebrow2 = hdrRow.appendChild(document.createElement("div"));1471    eyebrow2.className = "domain-eyebrow";1472    eyebrow2.textContent = "NEW ACCOUNT";1473    const domName2 = hdrRow.appendChild(document.createElement("div"));1474    domName2.className = "domain-name";1475    domName2.textContent = options.domain ?? location.hostname.replace(/^www\./, "");14761477    // Confirmed email row1478    const conf = wrap.appendChild(document.createElement("div"));1479    conf.className = "gen-confirmed";1480    const confCheck = conf.appendChild(document.createElement("span"));1481    confCheck.className = "gen-confirmed-check";1482    confCheck.textContent = "✓";1483    const confVal = conf.appendChild(document.createElement("div"));1484    confVal.className = "gen-confirmed-val";1485    confVal.textContent = filledEmail;14861487    const lbl = wrap.appendChild(document.createElement("div"));1488    lbl.className = "gen-label";1489    lbl.textContent = "Generate a password";14901491    let currentPw = "";1492    const smartGen = createSmartGenerator({1493      policy: sitePolicy,1494      onChange: (pw) => { currentPw = pw; },1495    });1496    wrap.appendChild(smartGen.root);14971498    const fillBtn = wrap.appendChild(document.createElement("button"));1499    fillBtn.className = "gen-fill-btn";1500    fillBtn.type = "button";1501    fillBtn.textContent = "Copy & fill";1502    fillBtn.addEventListener("click", () => {1503      if (!currentPw) return;1504      options.onFillFields?.("", currentPw);1505      renderSaveOffer(filledEmail, currentPw);1506    });1507  }15081509  function renderSaveOffer(filledEmail: string, filledPassword: string) {1510    container.innerHTML = "";1511    const domain = options.domain ?? location.hostname.replace(/^www\./, "");15121513    const wrap = container.appendChild(document.createElement("div"));1514    wrap.className = "save-offer";15151516    const title = wrap.appendChild(document.createElement("div"));1517    title.className = "save-offer-title";1518    title.textContent = "Save this login to Peach?";15191520    function detailRow(label: string, value: string) {1521      const row = wrap.appendChild(document.createElement("div"));1522      row.className = "save-offer-row";1523      const lbl = row.appendChild(document.createElement("div"));1524      lbl.className = "save-offer-lbl";1525      lbl.textContent = label;1526      const val = row.appendChild(document.createElement("div"));1527      val.className = "save-offer-val";1528      val.textContent = value;1529    }15301531    detailRow("site", domain);1532    detailRow("email", filledEmail);1533    detailRow("password", "••••••••••••••••");15341535    const btns = wrap.appendChild(document.createElement("div"));1536    btns.className = "save-offer-btns";15371538    const saveBtn = btns.appendChild(document.createElement("button"));1539    saveBtn.className = "save-offer-save";1540    saveBtn.type = "button";1541    saveBtn.textContent = "Save";1542    saveBtn.addEventListener("click", async () => {1543      saveBtn.disabled = true;1544      saveBtn.textContent = "Saving…";1545      try {1546        const res = await chrome.runtime.sendMessage({1547          type: "ADD_ENTRY",1548          payload: { title: sTitle, url: sOrigin, username: filledEmail, password: filledPassword, type: "login" },1549        });1550        if ((res as { ok?: boolean }).ok) {1551          showSuccess(sTitle);1552        } else {1553          saveBtn.disabled = false;1554          saveBtn.textContent = "Save";1555        }1556      } catch { saveBtn.disabled = false; saveBtn.textContent = "Save"; }1557    });15581559    const skipBtn = btns.appendChild(document.createElement("button"));1560    skipBtn.className = "save-offer-skip";1561    skipBtn.type = "button";1562    skipBtn.textContent = "Not now";1563    skipBtn.addEventListener("click", () => { dismiss(true); });1564  }15651566  function renderList() {1567    container.innerHTML = "";1568    focusedIndex = -1;1569    searchInput = null;1570    currentMode = "list";15711572    const current = activeEntries();15731574    // Domain header (always show) — eyebrow + domain on the left,1575    // a "+" shortcut to the create form on the right so the user is never1576    // trapped in the search list when they want to make a new entry.1577    const domHdr = document.createElement("div");1578    domHdr.className = "domain-header";1579    const headText = document.createElement("div");1580    headText.className = "domain-header-text";1581    const eyebrow = document.createElement("div");1582    eyebrow.className = "domain-eyebrow";1583    eyebrow.textContent = options.isSignup1584      ? "Sign up as"1585      : entries.length > 0 ? "Saved for this site" : "No saved login";1586    const domName = document.createElement("div");1587    domName.className = "domain-name";1588    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");1589    headText.append(eyebrow, domName);1590    domHdr.appendChild(headText);15911592    if (!options.isSignup) {1593      const actions = document.createElement("div");1594      actions.className = "domain-header-actions";15951596      // Back arrow takes the place of the silver-platter's search icon when1597      // the user has pivoted away from a single-match platter — gives them1598      // a one-click way back to the original recommendation.1599      if (silverPlatterOrigin) {1600        const backBtn = document.createElement("button");1601        backBtn.className = "domain-search-btn";1602        backBtn.type = "button";1603        backBtn.setAttribute("aria-label", "Back to suggested entry");1604        backBtn.title = "Back to suggested entry";1605        backBtn.innerHTML = backSvgStr();1606        backBtn.addEventListener("click", (e) => {1607          e.stopPropagation();1608          if (silverPlatterOrigin) renderSilverPlatter(silverPlatterOrigin);1609        });1610        actions.appendChild(backBtn);1611      }16121613      const addBtn = document.createElement("button");1614      addBtn.className = "domain-add-btn";1615      addBtn.type = "button";1616      addBtn.setAttribute("aria-label", "Create new entry");1617      addBtn.title = "Create new entry";1618      addBtn.textContent = "+";1619      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });1620      actions.appendChild(addBtn);16211622      domHdr.appendChild(actions);1623    }16241625    container.appendChild(domHdr);16261627    // Search — always show so user can find entries beyond the domain matches1628    const sw = document.createElement("div"); sw.className = "search-wrap";1629    searchInput = document.createElement("input");1630    searchInput.className = "search";1631    searchInput.placeholder = entries.length > 0 ? "search for another entry…" : "search vault…";1632    searchInput.value = query;1633    searchInput.addEventListener("input", () => {1634      query = searchInput?.value ?? "";1635      renderList();1636      searchInput?.focus();1637      searchInput?.setSelectionRange(query.length, query.length);1638    });1639    sw.appendChild(searchInput);1640    container.appendChild(sw);16411642    // Results1643    const results = document.createElement("div");1644    results.className = "results";1645    container.appendChild(results);16461647    if (current.length === 0 && entries.length > 0) {1648      // Show a hint but don't render empty entries1649    }16501651    for (let i = 0; i < current.length; i++) {1652      const e = current[i]!;1653      const entryEl = document.createElement("div");1654      entryEl.className = "entry";1655      entryEl.dataset.id = e.id;1656      entryEl.dataset.index = String(i);1657      entryEl.setAttribute("tabindex", "-1");16581659      entryEl.appendChild(makeEntryIcon(e.url));16601661      const info = document.createElement("div"); info.className = "entry-info";1662      const titleEl = document.createElement("div"); titleEl.className = "entry-title"; titleEl.textContent = e.title;1663      const subEl = document.createElement("div"); subEl.className = "entry-sub";1664      const domain = e.url ? getDomainFromUrl(e.url) : "";1665      subEl.textContent = domain || e.username || "";1666      info.append(titleEl, subEl);1667      entryEl.appendChild(info);16681669      if (e.hasTotp) {1670        const badge = document.createElement("span"); badge.className = "totp-badge"; badge.textContent = "TOTP";1671        entryEl.appendChild(badge);1672      }1673      if (e.hasPasskey) {1674        const badge = document.createElement("span"); badge.className = "passkey-badge"; badge.textContent = "passkey";1675        entryEl.appendChild(badge);1676      }16771678      entryEl.addEventListener("click", () => {1679        if (options.isSignup && options.onFillFields) {1680          // Signup mode: clicking a saved identity fills the username field1681          options.onFillFields(e.username ?? "", "");1682          dismiss();1683        } else {1684          onSelect(e.id);1685          dismiss();1686        }1687      });1688      results.appendChild(entryEl);1689    }16901691    // Divider before "New entry"1692    if (current.length > 0) {1693      results.appendChild(Object.assign(document.createElement("div"), { className: "divider" }));1694    }16951696    // "New entry" row — always present1697    const newEl = document.createElement("div");1698    newEl.className = "entry";1699    newEl.setAttribute("tabindex", "-1");1700    newEl.appendChild(makeEntryIcon(undefined, true));17011702    const newInfo = document.createElement("div"); newInfo.className = "entry-info";1703    const newTitle = document.createElement("div");1704    newTitle.className = "entry-title is-new";1705    newTitle.textContent = `New entry for ${sTitle}`;1706    const newSub = document.createElement("div");1707    newSub.className = "entry-sub";1708    newSub.textContent = sOrigin;1709    newInfo.append(newTitle, newSub);1710    newEl.appendChild(newInfo);1711    newEl.addEventListener("click", showCreateForm);1712    results.appendChild(newEl);17131714    // Focus search if present1715    if (searchInput) {1716      requestAnimationFrame(() => {1717        searchInput?.focus();1718        // Seed query (from type-to-search or domain-search-btn) lands at the1719        // end so the next keystroke extends it, not overwrites.1720        searchInput?.setSelectionRange(query.length, query.length);1721      });1722    }1723  }17241725  function setFocused(idx: number) {1726    const all = container.querySelectorAll<HTMLElement>(".entry");1727    all.forEach((el, i) => el.classList.toggle("focused", i === idx));1728    focusedIndex = idx;1729    if (idx >= 0) (all[idx] as HTMLElement).scrollIntoView({ block: "nearest" });1730  }17311732  function attachIdentitySuggestions(g: HTMLDivElement, inp: HTMLInputElement, identities: SavedIdentity[], fieldType: "username" | "email"): void {1733    const typed = identities.filter(s => s.type === fieldType);1734    if (!typed.length) return;1735    let collapsed = false;1736    let suppressNextFocus = false;17371738    const list = g.appendChild(document.createElement("div"));1739    list.className = "identity-suggest-list";1740    list.style.display = "none";17411742    // Collapse toggle — sits alone now that filter pills are gone1743    const collapseRow = list.appendChild(document.createElement("div"));1744    collapseRow.className = "identity-filter-row";1745    collapseRow.style.justifyContent = "flex-end";1746    const collapseBtn = collapseRow.appendChild(document.createElement("button"));1747    collapseBtn.type = "button";1748    collapseBtn.className = "identity-collapse-btn";1749    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>`;1750    collapseBtn.addEventListener("mousedown", (e) => {1751      e.preventDefault();1752      collapsed = !collapsed;1753      collapseBtn.classList.toggle("is-collapsed", collapsed);1754      rowsWrapper.classList.toggle("is-collapsed", collapsed);1755    });17561757    const rowsWrapper = list.appendChild(document.createElement("div"));1758    rowsWrapper.className = "identity-rows";1759    const rows = rowsWrapper.appendChild(document.createElement("div"));1760    rows.className = "identity-rows-inner";17611762    function pick(value: string) {1763      inp.value = value;1764      list.style.display = "none";1765      suppressNextFocus = true;1766      inp.focus();1767    }17681769    function render() {1770      const q = inp.value.toLowerCase();1771      const filtered = typed.filter(s => !q || s.value.toLowerCase().includes(q)).slice(0, 8);1772      rows.innerHTML = "";1773      if (!filtered.length) { list.style.display = "none"; return; }1774      for (const s of filtered) {1775        const row = rows.appendChild(document.createElement("button"));1776        row.type = "button"; row.className = "identity-suggest-row";1777        const val = row.appendChild(document.createElement("span"));1778        val.className = "identity-suggest-val"; val.textContent = s.value;1779        const meta = row.appendChild(document.createElement("span"));1780        meta.className = "identity-suggest-meta"; meta.textContent = `${s.useCount}×`;1781        row.addEventListener("mousedown", (e) => { e.preventDefault(); pick(s.value); });1782        row.addEventListener("keydown", (e) => {1783          if (e.key === "ArrowDown") {1784            e.preventDefault();1785            (row.nextElementSibling as HTMLElement | null)?.focus();1786          } else if (e.key === "ArrowUp") {1787            e.preventDefault();1788            const prev = row.previousElementSibling as HTMLElement | null;1789            if (prev) prev.focus();1790            else inp.focus();1791          } else if (e.key === "Enter" || e.key === " ") {1792            e.preventDefault();1793            pick(s.value);1794          } else if (e.key === "Escape") {1795            e.preventDefault();1796            list.style.display = "none";1797            suppressNextFocus = true;1798            inp.focus();1799          }1800        });1801        row.addEventListener("blur", (e) => {1802          const rt = (e as FocusEvent).relatedTarget as Node | null;1803          if (rt && (rt === inp || list.contains(rt))) return;1804          setTimeout(() => { list.style.display = "none"; }, 150);1805        });1806      }1807      list.style.display = "";1808    }18091810    inp.addEventListener("focus", () => {1811      if (suppressNextFocus) { suppressNextFocus = false; return; }1812      render();1813    });1814    inp.addEventListener("input", render);1815    inp.addEventListener("keydown", (e) => {1816      if (list.style.display === "none") return;1817      if (e.key === "ArrowDown" && !collapsed) {1818        e.preventDefault();1819        (rows.firstElementChild as HTMLElement | null)?.focus();1820      } else if (e.key === "Escape") {1821        e.preventDefault();1822        list.style.display = "none";1823      }1824    });1825    inp.addEventListener("blur", (e) => {1826      const rt = (e as FocusEvent).relatedTarget as Node | null;1827      if (rt && list.contains(rt)) return;1828      setTimeout(() => { list.style.display = "none"; }, 150);1829    });1830  }18311832  async function showCreateForm() {1833    currentMode = "create";1834    container.innerHTML = "";18351836    // Guard: the service worker may lock the vault between when the selector1837    // opens and when the user clicks "New entry". Show the inline unlock form1838    // instead of silently failing on save.1839    const statusRes = await chrome.runtime.sendMessage({ type: "GET_VAULT_STATUS" }).catch(() => null) as { unlocked?: boolean } | null;1840    if (!statusRes?.unlocked) {1841      renderLocked();1842      return;1843    }18441845    // Detect page password policy once for this form — reused on every1846    // regenerate click so the user always gets a compliant password.1847    const sitePolicy = detectPasswordPolicy();18481849    // Fetch identities on-demand — they're passed in signup context but not1850    // in login/search context where the user still clicks "New entry".1851    let formIdentities: SavedIdentity[] = options.savedIdentities ?? [];1852    if (!formIdentities.length) {1853      try {1854        const idRes = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as { ok: boolean; data?: SavedIdentity[] } | null;1855        if (idRes?.ok && Array.isArray(idRes.data)) formIdentities = idRes.data;1856      } catch { /* silent fallback */ }1857    }18581859    const wrap = document.createElement("div");1860    wrap.className = "create-form-wrap";18611862    // Header1863    const head = document.createElement("div"); head.className = "create-head";1864    const backBtn = document.createElement("button"); backBtn.className = "back-btn";1865    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>`;1866    backBtn.addEventListener("click", () => { currentMode = "list"; renderList(); });1867    const lbl = document.createElement("div"); lbl.className = "create-label"; lbl.textContent = "New entry";1868    head.append(backBtn, lbl);18691870    // Body1871    const body = document.createElement("div"); body.className = "create-body";18721873    function fGroup(label: string): { g: HTMLDivElement; inp: HTMLInputElement } {1874      const g = document.createElement("div"); g.className = "f-group";1875      const l = document.createElement("div"); l.className = "f-label"; l.textContent = label;1876      const inp = document.createElement("input"); inp.className = "f-input";1877      g.append(l, inp); return { g, inp };1878    }18791880    // Title1881    const tg = fGroup("title"); tg.inp.value = sTitle; tg.inp.placeholder = "e.g. Google";1882    body.appendChild(tg.g);18831884    // URL1885    const ug = fGroup("website");1886    ug.inp.className = "f-input url-f"; ug.inp.value = sOrigin; ug.inp.placeholder = "https://";1887    if (loginSubdomain) {1888      const h = document.createElement("div"); h.className = "url-hint";1889      h.textContent = "⊘ Recognized sign-in subdomain"; ug.g.appendChild(h);1890    }1891    body.appendChild(ug.g);18921893    // Username — pre-fill from anchor if it doesn't look like an email1894    const xg = fGroup("username");1895    xg.inp.value = preUsername && !preUsername.includes("@") ? preUsername : "";1896    xg.inp.placeholder = "johndoe";1897    xg.inp.setAttribute("autocomplete", "off");1898    if (formIdentities.length) attachIdentitySuggestions(xg.g, xg.inp, formIdentities, "username");1899    body.appendChild(xg.g);19001901    // Email — pre-fill from anchor if it looks like an email1902    const eg = fGroup("email");1903    (eg.inp as HTMLInputElement).type = "email";1904    eg.inp.value = preUsername && preUsername.includes("@") ? preUsername : "";1905    eg.inp.placeholder = "[email protected]";1906    eg.inp.setAttribute("autocomplete", "off");1907    if (formIdentities.length) attachIdentitySuggestions(eg.g, eg.inp, formIdentities, "email");1908    body.appendChild(eg.g);19091910    // Password — full smart generator with charset pills + length slider +1911    // policy hint. Mirrors the main UI's compact generator so users get the1912    // same controls inline as in the popup.1913    const pg = fGroup("password");1914    pg.inp.remove(); // smartGen provides its own display — no separate input needed1915    let currentPassword = prePassword || "";1916    const smartGen = createSmartGenerator({1917      policy: sitePolicy,1918      initialPassword: prePassword || undefined,1919      onChange: (pw) => { currentPassword = pw; },1920    });1921    pg.g.appendChild(smartGen.root);1922    body.appendChild(pg.g);19231924    // Save1925    const saveBtn = document.createElement("button"); saveBtn.className = "save-btn"; saveBtn.type = "button";1926    saveBtn.textContent = "Save entry";1927    const errEl = document.createElement("div"); errEl.className = "locked-error"; errEl.style.display = "none";1928    function showFormError(msg: string) { errEl.textContent = msg; errEl.style.display = ""; }1929    saveBtn.addEventListener("click", async () => {1930      const title = tg.inp.value.trim();1931      const pw = currentPassword.trim();1932      const username = xg.inp.value.trim();1933      const email = eg.inp.value.trim();1934      if (!title) {1935        tg.inp.style.borderColor = "rgba(220,70,60,0.5)"; tg.inp.focus();1936        showFormError("Entry needs a title");1937        return;1938      }1939      if (!pw) {1940        showFormError("Entry needs a password — tap regen to make one");1941        return;1942      }1943      errEl.style.display = "none";1944      saveBtn.disabled = true; saveBtn.textContent = "Saving…";1945      try {1946        const res = await chrome.runtime.sendMessage({1947          type: "ADD_ENTRY",1948          payload: { title, url: ug.inp.value.trim(), username, email: email || undefined, password: pw, type: "login" },1949        });1950        if ((res as { ok?: boolean }).ok) {1951          // Fill the detected form. onFillFields uses whichever identity the1952          // page anchored on — the vault captures both username and email.1953          options.onFillFields?.(username || email, pw);1954          showSuccess(title);1955        } else {1956          const errMsg = (res as { error?: string }).error === "vault locked"1957            ? "Vault locked — open Peach to save"1958            : "Could not save entry";1959          showFormError(errMsg);1960          saveBtn.disabled = false; saveBtn.textContent = "Save entry";1961        }1962      } catch { showFormError("Could not reach Peach"); saveBtn.disabled = false; saveBtn.textContent = "Save entry"; }1963    });1964    body.appendChild(saveBtn);1965    body.appendChild(errEl);19661967    wrap.append(head, body);1968    container.appendChild(wrap);1969    requestAnimationFrame(() => { tg.inp.focus(); tg.inp.select(); });1970  }19711972  function showSuccess(title: string) {1973    currentMode = "success";1974    container.innerHTML = "";1975    const wrap = document.createElement("div"); wrap.className = "success-wrap";1976    const ring = document.createElement("div"); ring.className = "success-ring";1977    ring.innerHTML = checkSvgStr();1978    const t = document.createElement("div"); t.className = "success-text"; t.textContent = `${title} saved`;1979    const s = document.createElement("div"); s.className = "success-sub"; s.textContent = sOrigin;1980    wrap.append(ring, t, s);1981    container.appendChild(wrap);1982    setTimeout(() => dismiss(), 1600);1983  }19841985  function flashActionBtn(btn: HTMLButtonElement) {1986    btn.classList.add("flashed");1987    setTimeout(() => btn.classList.remove("flashed"), 700);1988  }19891990  // M3/QUA-005: when both the direct clipboard write and the background COPY1991  // fallback fail, briefly show the user that the copy did not happen.1992  function flashCopyError(btn: HTMLButtonElement) {1993    const original = btn.textContent ?? "";1994    btn.textContent = "Blocked";1995    btn.classList.add("flashed");1996    setTimeout(() => {1997      btn.classList.remove("flashed");1998      if (btn.isConnected) btn.textContent = original;1999    }, 1200);2000  }20012002  function renderSilverPlatter(entry: SelectorEntry) {2003    container.innerHTML = "";2004    searchInput = null;2005    focusedIndex = -1;2006    currentMode = "silver-platter";2007    silverPlatterOrigin = entry;20082009    const domHdr = document.createElement("div");2010    domHdr.className = "domain-header";2011    const headText = document.createElement("div");2012    headText.className = "domain-header-text";2013    const eyebrow = document.createElement("div");2014    eyebrow.className = "domain-eyebrow";2015    eyebrow.textContent = "Saved for this site";2016    const domName = document.createElement("div");2017    domName.className = "domain-name";2018    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2019    headText.append(eyebrow, domName);2020    domHdr.appendChild(headText);2021    if (!options.isSignup) {2022      const actions = document.createElement("div");2023      actions.className = "domain-header-actions";20242025      // Search shortcut — same idea as type-to-search below, but visible so2026      // the user can discover that another entry is reachable from a2027      // single-match platter. Sits to the left of the create button.2028      const searchBtn = document.createElement("button");2029      searchBtn.className = "domain-search-btn";2030      searchBtn.type = "button";2031      searchBtn.setAttribute("aria-label", "Search for a different entry");2032      searchBtn.title = "Search for a different entry";2033      searchBtn.innerHTML = searchSvgStr();2034      searchBtn.addEventListener("click", (e) => {2035        e.stopPropagation();2036        query = "";2037        renderList();2038      });2039      actions.appendChild(searchBtn);20402041      const addBtn = document.createElement("button");2042      addBtn.className = "domain-add-btn";2043      addBtn.type = "button";2044      addBtn.setAttribute("aria-label", "Create new entry");2045      addBtn.title = "Create new entry";2046      addBtn.textContent = "+";2047      addBtn.addEventListener("click", (e) => { e.stopPropagation(); void showCreateForm(); });2048      actions.appendChild(addBtn);20492050      domHdr.appendChild(actions);2051    }2052    container.appendChild(domHdr);20532054    const platter = document.createElement("div");2055    platter.className = "silver-platter";20562057    const titleEl = document.createElement("div");2058    titleEl.className = "sp-title";2059    titleEl.textContent = entry.title;2060    platter.appendChild(titleEl);20612062    if (entry.email) {2063      const emailEl = document.createElement("div");2064      emailEl.className = "sp-identity-row";2065      const emailLbl = document.createElement("span");2066      emailLbl.className = "sp-identity-label";2067      emailLbl.textContent = "email";2068      const emailVal = document.createElement("span");2069      emailVal.className = "sp-username";2070      emailVal.textContent = entry.email;2071      emailEl.append(emailLbl, emailVal);2072      platter.appendChild(emailEl);2073    }20742075    if (entry.username) {2076      const userEl = document.createElement("div");2077      userEl.className = "sp-identity-row";2078      const userLbl = document.createElement("span");2079      userLbl.className = "sp-identity-label";2080      userLbl.textContent = entry.username.includes("@") ? "email" : "username";2081      const userVal = document.createElement("span");2082      userVal.className = "sp-username";2083      userVal.textContent = entry.username;2084      userEl.append(userLbl, userVal);2085      platter.appendChild(userEl);2086    }20872088    const fillBtn = document.createElement("button");2089    fillBtn.className = "sp-fill-btn";2090    fillBtn.type = "button";2091    fillBtn.textContent = "Fill credentials";2092    fillBtn.addEventListener("click", () => {2093      if (fillBtn.disabled) return;2094      fillBtn.disabled = true;2095      fillBtn.classList.add("filled");2096      fillBtn.innerHTML = checkSvgStr();2097      // Fire the fill, then exit via the standard exit animation. The fill2098      // itself is async (handled in index.ts) — by 400ms the form is filled2099      // and the popup begins its exit. Total dwell from click to host2100      // removal: 400ms + 130ms (exit animation) = 530ms.2101      onSelect(entry.id);2102      setTimeout(() => dismiss(), 400);2103    });2104    platter.appendChild(fillBtn);21052106    const actionsGroup = document.createElement("div");2107    actionsGroup.className = "sp-actions-group";2108    const actionsLabel = document.createElement("div");2109    actionsLabel.className = "sp-actions-label";2110    actionsLabel.textContent = "Copy";2111    actionsGroup.appendChild(actionsLabel);21122113    const actions = document.createElement("div");2114    actions.className = "sp-actions";2115    actionsGroup.appendChild(actions);21162117    if (entry.email) {2118      const copyEmail = document.createElement("button");2119      copyEmail.className = "sp-action-btn";2120      copyEmail.type = "button";2121      copyEmail.title = "Copy email";2122      copyEmail.textContent = "Email";2123      copyEmail.addEventListener("click", async (e) => {2124        e.stopPropagation();2125        let alreadyWritten = false;2126        try {2127          await navigator.clipboard.writeText(entry.email!);2128          alreadyWritten = true;2129        } catch (err) {2130          console.warn("[Peach] clipboard write denied:", err);2131        }2132        const resp = await chrome.runtime.sendMessage({2133          type: "COPY",2134          payload: { text: entry.email, label: "Email", alreadyWritten },2135        }).catch(() => null) as { ok?: boolean } | null;2136        if (alreadyWritten || resp?.ok) flashActionBtn(copyEmail);2137        else flashCopyError(copyEmail);2138      });2139      actions.appendChild(copyEmail);2140    }21412142    const copyU = document.createElement("button");2143    copyU.className = "sp-action-btn";2144    copyU.type = "button";2145    const usernameIsEmail = entry.username?.includes("@") ?? false;2146    copyU.title = usernameIsEmail ? "Copy email" : "Copy username";2147    copyU.textContent = usernameIsEmail ? "Email" : "Username";2148    copyU.disabled = !entry.username;2149    copyU.addEventListener("click", async (e) => {2150      e.stopPropagation();2151      if (!entry.username) return;2152      let alreadyWritten = false;2153      try {2154        await navigator.clipboard.writeText(entry.username);2155        alreadyWritten = true;2156      } catch (err) {2157        console.warn("[Peach] clipboard write denied:", err);2158      }2159      const resp = await chrome.runtime.sendMessage({2160        type: "COPY",2161        payload: { text: entry.username, label: entry.username.includes("@") ? "Email" : "Username", alreadyWritten },2162      }).catch(() => null) as { ok?: boolean } | null;2163      if (alreadyWritten || resp?.ok) flashActionBtn(copyU);2164      else flashCopyError(copyU);2165    });2166    actions.appendChild(copyU);21672168    const copyP = document.createElement("button");2169    copyP.className = "sp-action-btn";2170    copyP.type = "button";2171    copyP.title = "Copy password";2172    copyP.textContent = "Password";2173    copyP.addEventListener("click", async (e) => {2174      e.stopPropagation();2175      const resp = await chrome.runtime.sendMessage({2176        type: "GET_ENTRY_FOR_FILL",2177        payload: { id: entry.id },2178      }).catch(() => null) as { ok: boolean; data?: { password?: string } } | null;2179      if (!resp?.ok || !resp.data?.password) return;2180      let alreadyWritten = false;2181      try {2182        await navigator.clipboard.writeText(resp.data.password);2183        alreadyWritten = true;2184      } catch (err) {2185        console.warn("[Peach] clipboard write denied:", err);2186      }2187      const copyResp = await chrome.runtime.sendMessage({2188        type: "COPY",2189        payload: { text: resp.data.password, label: "Password", alreadyWritten },2190      }).catch(() => null) as { ok?: boolean } | null;2191      if (alreadyWritten || copyResp?.ok) flashActionBtn(copyP);2192      else flashCopyError(copyP);2193    });2194    actions.appendChild(copyP);21952196    let trayEl: HTMLDivElement | null = null;2197    let trayInterval: ReturnType<typeof setInterval> | null = null;21982199    function closeTray() {2200      if (trayInterval) { clearInterval(trayInterval); trayInterval = null; }2201      trayEl?.remove();2202      trayEl = null;2203    }2204    // Register so dismiss() will close the tray and clear the interval2205    // even if the user dismisses without explicitly closing the tray.2206    cleanupHooks.push(closeTray);22072208    async function openTOTPTray() {2209      // Fetch the current TOTP code from the background. The raw base32 seed2210      // never enters the content script (SEV-3-C): we receive the live 6-digit2211      // code plus the seconds remaining, count down locally, and re-fetch a2212      // fresh code only when the 30s window rolls over.2213      async function fetchCode(): Promise<{ code: string; remaining: number } | null> {2214        const r = await chrome.runtime.sendMessage({2215          type: "GET_ENTRY_FOR_FILL",2216          payload: { id: entry.id },2217        }).catch(() => null) as { ok: boolean; data?: { totpCode?: string; totpRemaining?: number } } | null;2218        if (!r?.ok || !r.data?.totpCode) return null;2219        return { code: r.data.totpCode, remaining: r.data.totpRemaining ?? 30 };2220      }2221      let current = await fetchCode();2222      if (!current) return;22232224      trayEl = document.createElement("div");2225      trayEl.className = "sp-tray";22262227      const label = document.createElement("span");2228      label.className = "sp-tray-label";2229      label.textContent = "2FA";2230      trayEl.appendChild(label);22312232      const codeEl = document.createElement("div");2233      codeEl.className = "sp-totp-code";2234      trayEl.appendChild(codeEl);22352236      const ringNs = "http://www.w3.org/2000/svg";2237      const ring = document.createElementNS(ringNs, "svg");2238      ring.setAttribute("class", "sp-totp-ring");2239      ring.setAttribute("viewBox", "0 0 24 24");2240      const trackC = document.createElementNS(ringNs, "circle");2241      trackC.setAttribute("class", "ring-track");2242      trackC.setAttribute("cx", "12"); trackC.setAttribute("cy", "12"); trackC.setAttribute("r", "10");2243      trackC.setAttribute("fill", "none"); trackC.setAttribute("stroke-width", "2");2244      const fillC = document.createElementNS(ringNs, "circle");2245      fillC.setAttribute("class", "ring-fill");2246      fillC.setAttribute("cx", "12"); fillC.setAttribute("cy", "12"); fillC.setAttribute("r", "10");2247      fillC.setAttribute("fill", "none"); fillC.setAttribute("stroke-width", "2");2248      fillC.setAttribute("stroke-linecap", "round");2249      fillC.setAttribute("stroke-dasharray", "62.83");2250      ring.append(trackC, fillC);2251      trayEl.appendChild(ring);22522253      const copyBtn = document.createElement("button");2254      copyBtn.className = "sp-totp-copy";2255      copyBtn.type = "button";2256      copyBtn.textContent = "Copy";2257      trayEl.appendChild(copyBtn);22582259      function render() {2260        const { code, remaining } = current!;2261        // Group as "847 291" — easier to read than "847291"2262        codeEl.textContent = code.length === 62263          ? `${code.slice(0, 3)} ${code.slice(3)}`2264          : code;2265        // Ring fills counter-clockwise as time elapses: dashoffset goes from2266        // 0 (full ring) to 62.83 (empty) over the 30s window.2267        const fraction = (30 - remaining) / 30;2268        fillC.setAttribute("stroke-dashoffset", String(62.83 * fraction));2269      }2270      render();2271      trayInterval = setInterval(async () => {2272        if (!current) return;2273        current = { code: current.code, remaining: current.remaining - 1 };2274        // Window rolled over — pull a fresh code from the background.2275        if (current.remaining <= 0) {2276          const next = await fetchCode();2277          current = next ?? { code: current.code, remaining: 30 };2278        }2279        render();2280      }, 1000);22812282      copyBtn.addEventListener("click", async (e) => {2283        e.stopPropagation();2284        const code = current?.code;2285        if (!code) return;2286        let alreadyWritten = false;2287        try {2288          await navigator.clipboard.writeText(code);2289          alreadyWritten = true;2290        } catch (err) {2291          console.warn("[Peach] clipboard write denied:", err);2292        }2293        const resp = await chrome.runtime.sendMessage({2294          type: "COPY",2295          payload: { text: code, label: "TOTP", alreadyWritten },2296        }).catch(() => null) as { ok?: boolean } | null;2297        copyBtn.textContent = alreadyWritten || resp?.ok ? "Copied" : "Blocked";2298        setTimeout(() => { if (copyBtn.isConnected) copyBtn.textContent = "Copy"; }, 1200);2299      });23002301      platter.appendChild(trayEl);2302    }23032304    const editBtn = document.createElement("button");2305    editBtn.className = "sp-action-btn sp-action-edit";2306    editBtn.type = "button";2307    editBtn.title = "Edit entry";2308    editBtn.textContent = "Edit";2309    editBtn.addEventListener("click", (e) => {2310      e.stopPropagation();2311      closeTray();2312      void renderInlineEdit(entry);2313    });2314    actions.appendChild(editBtn);23152316    // Always show the 2FA tray when the entry has TOTP — hiding it behind a2317    // "···" toggle was zero-savings (the toggle button took the same space2318    // the "2FA" label needed) and made the code one extra click away.2319    if (entry.hasTotp) void openTOTPTray();23202321    platter.appendChild(actionsGroup);2322    container.appendChild(platter);2323  }23242325  /**2326   * Inline-popup edit mode. Swaps the silver platter for an editable form2327   * over the same shadow-DOM surface so the user never leaves the page.2328   * Saves go through UPDATE_ENTRY; on success we refresh the silver platter2329   * with the new fields. Cancel returns without writing.2330   */2331  async function renderInlineEdit(summary: SelectorEntry) {2332    container.innerHTML = "";2333    const wrap = document.createElement("div");2334    wrap.className = "create-form-wrap";23352336    const head = document.createElement("div");2337    head.className = "create-head";2338    const back = document.createElement("button");2339    back.className = "back-btn";2340    back.type = "button";2341    back.title = "Cancel";2342    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>`;2343    back.addEventListener("click", () => renderSilverPlatter(summary));2344    head.appendChild(back);2345    const headLbl = document.createElement("div");2346    headLbl.className = "create-label";2347    headLbl.textContent = "Edit entry";2348    head.appendChild(headLbl);2349    wrap.appendChild(head);23502351    const body = document.createElement("div");2352    body.className = "create-body";23532354    // Loading shimmer while we fetch the full entry2355    const loading = document.createElement("div");2356    loading.className = "empty-hint";2357    loading.textContent = "loading…";2358    body.appendChild(loading);2359    wrap.appendChild(body);2360    container.appendChild(wrap);23612362    const [res, idRes] = await Promise.all([2363      // The edit form needs the raw TOTP seed so a save doesn't wipe it — use2364      // the trusted edit channel, not the seed-stripped GET_ENTRY_FOR_FILL.2365      chrome.runtime.sendMessage({2366        type: "GET_ENTRY_FOR_EDIT",2367        payload: { id: summary.id },2368      }).catch(() => null),2369      chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null),2370    ]);2371    const entryRes = res as { ok: boolean; data?: { title?: string; username?: string; email?: string; password?: string; url?: string; totp?: string; notes?: string } } | null;2372    const editIdentities: SavedIdentity[] = (idRes as { ok?: boolean; data?: SavedIdentity[] } | null)?.data ?? [];23732374    if (!entryRes || !entryRes.ok || !entryRes.data) {2375      loading.textContent = "couldn't load this entry. try again from the popup.";2376      return;2377    }2378    body.innerHTML = "";23792380    function field(label: string, value: string, type: "text" | "password" = "text"): { g: HTMLDivElement; inp: HTMLInputElement } {2381      const group = document.createElement("div");2382      group.className = "f-group";2383      const lbl = document.createElement("div");2384      lbl.className = "f-label";2385      lbl.textContent = label;2386      const input = document.createElement("input");2387      input.className = "f-input";2388      input.type = type;2389      input.value = value;2390      input.autocomplete = "off";2391      group.append(lbl, input);2392      body.appendChild(group);2393      return { g: group, inp: input };2394    }23952396    const titleInput = field("title", entryRes.data.title ?? "").inp;2397    const urlInput = field("url", entryRes.data.url ?? "").inp;2398    urlInput.classList.add("url-f");2399    const usernameLabel = (entryRes.data.username ?? "").includes("@") ? "email" : "username";2400    const { g: usernameGroup, inp: usernameInput } = field(usernameLabel, entryRes.data.username ?? "");2401    if (editIdentities.length) attachIdentitySuggestions(usernameGroup, usernameInput, editIdentities, "username");2402    const { g: emailGroup, inp: emailInput } = field("email", entryRes.data.email ?? "");2403    if (editIdentities.length) attachIdentitySuggestions(emailGroup, emailInput, editIdentities, "email");24042405    // Password row with reveal toggle + generator2406    const pwGroup = document.createElement("div");2407    pwGroup.className = "f-group";2408    const pwLbl = document.createElement("div");2409    pwLbl.className = "f-label";2410    pwLbl.textContent = "password";2411    const pwRow = document.createElement("div");2412    pwRow.className = "f-row";2413    const pwInput = document.createElement("input");2414    pwInput.className = "f-input";2415    pwInput.type = "password";2416    pwInput.value = entryRes.data.password ?? "";2417    pwInput.autocomplete = "new-password";2418    const revealBtn = document.createElement("button");2419    revealBtn.className = "gen-btn";2420    revealBtn.type = "button";2421    revealBtn.textContent = "show";2422    revealBtn.addEventListener("click", () => {2423      const reveal = pwInput.type === "password";2424      pwInput.type = reveal ? "text" : "password";2425      revealBtn.textContent = reveal ? "hide" : "show";2426    });2427    pwRow.append(pwInput, revealBtn);2428    const editSmartGen = createSmartGenerator({ policy: detectPasswordPolicy(), onChange: (pw) => { pwInput.value = pw; } });2429    editSmartGen.root.style.display = "none";2430    let editGenVisible = false;2431    const genToggleBtn = document.createElement("button");2432    genToggleBtn.className = "gen-toggle-link";2433    genToggleBtn.type = "button";2434    genToggleBtn.textContent = "⚙ generate";2435    genToggleBtn.addEventListener("click", () => {2436      editGenVisible = !editGenVisible;2437      pwRow.style.display = editGenVisible ? "none" : "";2438      editSmartGen.root.style.display = editGenVisible ? "" : "none";2439      genToggleBtn.textContent = editGenVisible ? "☰ hide generator" : "⚙ generate";2440    });2441    pwGroup.append(pwLbl, pwRow, genToggleBtn, editSmartGen.root);2442    body.appendChild(pwGroup);24432444    const totpInput = field("2fa secret", entryRes.data.totp ?? "").inp;24452446    // Notes2447    const notesGroup = document.createElement("div");2448    notesGroup.className = "f-group";2449    const notesLbl = document.createElement("div");2450    notesLbl.className = "f-label";2451    notesLbl.textContent = "notes";2452    const notesInput = document.createElement("textarea");2453    notesInput.className = "f-input";2454    notesInput.rows = 3;2455    notesInput.value = entryRes.data.notes ?? "";2456    notesInput.style.fontFamily = "Inter, sans-serif";2457    notesInput.style.resize = "vertical";2458    notesGroup.append(notesLbl, notesInput);2459    body.appendChild(notesGroup);24602461    // Save / Cancel row2462    const actionsRow = document.createElement("div");2463    actionsRow.className = "f-row";2464    const saveBtn = document.createElement("button");2465    saveBtn.className = "save-btn";2466    saveBtn.type = "button";2467    saveBtn.textContent = "Save changes";2468    saveBtn.style.flex = "1";2469    const cancelBtn = document.createElement("button");2470    cancelBtn.className = "gen-btn";2471    cancelBtn.type = "button";2472    cancelBtn.textContent = "cancel";2473    cancelBtn.addEventListener("click", () => renderSilverPlatter(summary));2474    actionsRow.append(saveBtn, cancelBtn);2475    body.appendChild(actionsRow);24762477    saveBtn.addEventListener("click", async () => {2478      saveBtn.disabled = true;2479      const originalLabel = saveBtn.textContent;2480      saveBtn.textContent = "Saving…";2481      const patch: Record<string, unknown> = {2482        title: titleInput.value.trim(),2483        url: urlInput.value.trim(),2484        username: usernameInput.value.trim(),2485        email: emailInput.value.trim() || undefined,2486        password: pwInput.value,2487        totp: totpInput.value.trim(),2488        notes: notesInput.value,2489      };2490      const updateRes = (await chrome.runtime.sendMessage({2491        type: "UPDATE_ENTRY",2492        payload: { id: summary.id, patch },2493      }).catch(() => null)) as { ok: boolean; error?: string } | null;2494      if (!updateRes?.ok) {2495        saveBtn.disabled = false;2496        saveBtn.textContent = originalLabel;2497        const err = document.createElement("div");2498        err.className = "empty-hint";2499        err.style.color = "color-mix(in srgb, #e55 70%, transparent)";2500        err.textContent = updateRes?.error ?? "Couldn't save. Try the popup.";2501        body.appendChild(err);2502        setTimeout(() => err.remove(), 3000);2503        return;2504      }2505      // Refresh the platter with updated summary fields2506      const refreshed: SelectorEntry = {2507        id: summary.id,2508        title: patch.title as string,2509        username: patch.username as string,2510        email: patch.email as string | undefined,2511        url: patch.url as string,2512        hasTotp: Boolean(patch.totp),2513        hasPasskey: summary.hasPasskey,2514      };2515      renderSilverPlatter(refreshed);2516    });25172518    queueMicrotask(() => titleInput.focus());2519  }25202521  function renderLocked() {2522    container.innerHTML = "";25232524    // Domain header (same as list view)2525    const domHdr = document.createElement("div");2526    domHdr.className = "domain-header";2527    const eyebrow = document.createElement("div");2528    eyebrow.className = "domain-eyebrow";2529    eyebrow.textContent = "vault locked";2530    const domName = document.createElement("div");2531    domName.className = "domain-name";2532    domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");2533    domHdr.append(eyebrow, domName);2534    container.appendChild(domHdr);25352536    const wrap = document.createElement("div");2537    wrap.className = "locked-wrap";25382539    // Icon + label row2540    const head = document.createElement("div"); head.className = "locked-head";2541    const icon = document.createElement("div"); icon.className = "locked-icon";2542    icon.innerHTML = keySvgStr();2543    const title = document.createElement("div"); title.className = "locked-title";2544    title.textContent = "unlock to autofill";2545    head.append(icon, title);25462547    // The master password is NEVER collected in page-hosted DOM. A malicious2548    // page can observe keystrokes on the shared DOM event stream (a capture-2549    // phase listener registered before Peach injects sees every key before any2550    // stopImmediatePropagation), which would leak the vault's root secret2551    // (audit HIGH). Instead, route unlocking to the trusted extension popup,2552    // where keystrokes are isolated from the page. After the user unlocks2553    // there, the background's VAULT_UNLOCKED broadcast re-triggers autofill2554    // automatically (see content/index.ts), so the flow resumes on its own.2555    const sub = document.createElement("div");2556    sub.className = "locked-sub";2557    sub.textContent = "Unlock in Peach — your master password is never typed on this page.";25582559    const openBtn = document.createElement("button");2560    openBtn.className = "locked-btn";2561    openBtn.type = "button";2562    openBtn.textContent = "Open Peach to unlock";2563    openBtn.addEventListener("click", () => {2564      chrome.runtime.sendMessage({ type: "OPEN_POPUP" }).catch(() => {});2565      openBtn.textContent = "opening Peach…";2566      openBtn.disabled = true;2567      // openPopup() can't always open programmatically (browser/version/gesture2568      // limits); reset so the user can retry or click the toolbar icon.2569      setTimeout(() => {2570        if (openBtn.isConnected) {2571          openBtn.textContent = "Open Peach to unlock";2572          openBtn.disabled = false;2573        }2574      }, 2500);2575    });25762577    wrap.append(head, sub, openBtn);2578    container.appendChild(wrap);2579  }25802581  function handleKeyDown(e: KeyboardEvent) {2582    if (options.locked) {2583      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2584      return;2585    }2586    if (currentMode === "create" || currentMode === "success" || currentMode === "silver-platter") {2587      if (e.key === "Escape") { e.preventDefault(); dismiss(true); }2588      return;2589    }2590    const allEntryEls = container.querySelectorAll(".entry:not(.empty-state)");2591    const count = allEntryEls.length;2592    if (document.activeElement === searchInput) {2593      if (e.key === "Escape" || e.key === "Tab") { e.preventDefault(); dismiss(true); return; }2594      if (count === 0) return;2595      if (!["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) return;2596    }2597    if (count === 0) return;2598    switch (e.key) {2599      case "ArrowDown": e.preventDefault(); setFocused(focusedIndex < count - 1 ? focusedIndex + 1 : 0); break;2600      case "ArrowUp": e.preventDefault(); setFocused(focusedIndex > 0 ? focusedIndex - 1 : count - 1); break;2601      case "Enter": {2602        if (focusedIndex >= 0) {2603          const el = allEntryEls[focusedIndex] as HTMLElement;2604          const id = el.dataset.id;2605          if (id) { onSelect(id); dismiss(); }2606          else if (el.classList.contains("is-new") || !id) {2607            // "New entry" row (last item, no data-id)2608            showCreateForm();2609          }2610        }2611        break;2612      }2613      case "Escape": case "Tab": e.preventDefault(); dismiss(true); break;2614    }2615  }26162617  document.addEventListener("keydown", handleKeyDown);26182619  // Type-to-search from the silver platter. A printable single-character2620  // keystroke (no modifier) seeds the search query and switches into the2621  // list view, so the user can pivot to a different entry without first2622  // clicking the search icon. Capture phase so the anchor input does not2623  // receive the character before we hijack it.2624  const silverPlatterTypeHandler = (e: KeyboardEvent) => {2625    if (currentMode !== "silver-platter") return;2626    if (e.ctrlKey || e.metaKey || e.altKey) return;2627    if (e.key.length !== 1) return;2628    e.preventDefault();2629    e.stopImmediatePropagation();2630    query = e.key;2631    renderList();2632  };2633  document.addEventListener("keydown", silverPlatterTypeHandler, true);2634  cleanupHooks.push(() => document.removeEventListener("keydown", silverPlatterTypeHandler, true));26352636  document.body.appendChild(host);26372638  function updatePosition() {2639    const r = anchorEl.getBoundingClientRect();2640    host.style.top = `${r.bottom + window.scrollY + 5}px`;2641    host.style.left = `${r.left + window.scrollX}px`;2642    host.style.width = `${popupWidth}px`;2643  }2644  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);26452646  if (options.locked) {2647    renderLocked();2648  } else if (options.isSignup && options.savedIdentities) {2649    // State 10: identity helper — signup form detected, show derived2650    // identity list (emails then usernames) instead of vault entry list.2651    renderIdentityHelper();2652  } else if (entries.length === 1 && !options.isSignup) {2653    // Silver platter (State 1): single domain match → focused fill view.2654    // Multi-match goes through renderList instead.2655    renderSilverPlatter(entries[0]!);2656  } else {2657    renderList();2658  }26592660  let exitScheduled = false;2661  function dismiss(userAction = false) {2662    // Idempotent: dismiss() can be called from multiple paths (Escape,2663    // outside click, entry select, fill success, host page nav). The exit2664    // animation must only play once and host.remove() must run exactly once.2665    if (exitScheduled) return;2666    exitScheduled = true;2667    // Detach listeners synchronously so nothing can re-trigger during the2668    // 130ms exit window (a focusin firing here would race against the2669    // dismiss-lock work in Pass 2).2670    stopObserving();2671    document.removeEventListener("click", outsideClick, { capture: true });2672    document.removeEventListener("keydown", handleKeyDown);2673    for (const cleanup of cleanupHooks) {2674      try { cleanup(); } catch { /* defensive — one hook must not block others */ }2675    }2676    if (userAction) options.onDismiss?.();2677    container.classList.add("is-exiting");2678    setTimeout(() => host.remove(), 130);2679  }26802681  function outsideClick(ev: MouseEvent) {2682    const path = ev.composedPath();2683    // Never dismiss when clicking the anchor field itself — that click is2684    // what triggered the selector to open, and the user may click the field2685    // again to re-focus it without intending to close the selector.2686    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2687  }2688  // capture: true so pages that call stopPropagation() on click don't block our dismiss handler2689  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);26902691  return dismiss;2692}26932694export function showTOTPSelector(2695  anchorEl: HTMLInputElement,2696  entries: SelectorEntry[],2697  onFill: (id: string) => void,2698  options: { domain?: string; onDismiss?: () => void } = {}2699): () => void {2700  const host = document.createElement("div");2701  host.style.cssText = "position: absolute; z-index: 2147483647;";2702  host.style.setProperty("--peach-accent", accentHex);2703  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));2704  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));2705  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));2706  const shadow = host.attachShadow({ mode: "closed" });27072708  const style = shadow.appendChild(document.createElement("style"));2709  style.textContent = SELECTOR_STYLES;27102711  const rect = anchorEl.getBoundingClientRect();2712  host.style.top = `${rect.bottom + window.scrollY + 5}px`;2713  host.style.left = `${rect.left + window.scrollX}px`;2714  const popupWidth = Math.min(Math.max(rect.width, 300), 360);2715  host.style.width = `${popupWidth}px`;27162717  const container = shadow.appendChild(document.createElement("div"));2718  container.className = "peach-inline-popup";2719  container.setAttribute("data-theme", popupTheme);27202721  const domain = options.domain ?? location.hostname.replace(/^www\./, "");2722  const current = entries.filter((entry) => entry.hasTotp);2723  let focusedIndex = current.length === 1 ? 0 : -1;27242725  function updatePosition() {2726    const r = anchorEl.getBoundingClientRect();2727    host.style.top = `${r.bottom + window.scrollY + 5}px`;2728    host.style.left = `${r.left + window.scrollX}px`;2729    host.style.width = `${popupWidth}px`;2730  }27312732  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);27332734  function choose(entry: SelectorEntry) {2735    onFill(entry.id);2736    dismiss();2737  }27382739  function render() {2740    container.innerHTML = "";27412742    const domHdr = document.createElement("div");2743    domHdr.className = "domain-header";2744    const headText = document.createElement("div");2745    headText.className = "domain-header-text";2746    const eyebrow = document.createElement("div");2747    eyebrow.className = "domain-eyebrow";2748    eyebrow.textContent = "2FA code";2749    const domName = document.createElement("div");2750    domName.className = "domain-name";2751    domName.textContent = domain;2752    headText.append(eyebrow, domName);2753    domHdr.appendChild(headText);2754    container.appendChild(domHdr);27552756    if (current.length === 1) {2757      const entry = current[0]!;2758      const platter = document.createElement("div");2759      platter.className = "silver-platter";27602761      const title = document.createElement("div");2762      title.className = "sp-title";2763      title.textContent = entry.title;2764      platter.appendChild(title);27652766      const sub = document.createElement("div");2767      sub.className = "sp-username";2768      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2769      platter.appendChild(sub);27702771      const fill = document.createElement("button");2772      fill.className = "sp-fill-btn";2773      fill.type = "button";2774      fill.textContent = "Fill 2FA code";2775      fill.addEventListener("click", () => choose(entry));2776      platter.appendChild(fill);27772778      container.appendChild(platter);2779      requestAnimationFrame(() => fill.focus({ preventScroll: true }));2780      return;2781    }27822783    const results = document.createElement("div");2784    results.className = "results";2785    container.appendChild(results);27862787    for (let i = 0; i < current.length; i++) {2788      const entry = current[i]!;2789      const row = document.createElement("div");2790      row.className = `entry${i === focusedIndex ? " focused" : ""}`;2791      row.dataset.index = String(i);2792      row.setAttribute("tabindex", "-1");27932794      const icon = document.createElement("div");2795      icon.className = "entry-icon";2796      icon.innerHTML = keySvgStr();2797      row.appendChild(icon);2798      const info = document.createElement("div");2799      info.className = "entry-info";2800      const title = document.createElement("div");2801      title.className = "entry-title";2802      title.textContent = entry.title;2803      const sub = document.createElement("div");2804      sub.className = "entry-sub";2805      sub.textContent = entry.username ?? entry.email ?? entry.url ?? "";2806      info.append(title, sub);2807      row.appendChild(info);28082809      const badge = document.createElement("span");2810      badge.className = "totp-badge";2811      badge.textContent = "Fill";2812      row.appendChild(badge);2813      row.addEventListener("click", () => choose(entry));2814      results.appendChild(row);2815    }2816  }28172818  function setFocused(index: number) {2819    focusedIndex = index;2820    container.querySelectorAll(".entry").forEach((el, i) => {2821      el.classList.toggle("focused", i === focusedIndex);2822      if (i === focusedIndex) (el as HTMLElement).scrollIntoView({ block: "nearest" });2823    });2824  }28252826  function handleKeyDown(e: KeyboardEvent) {2827    if (e.key === "Escape" || e.key === "Tab") {2828      e.preventDefault();2829      dismiss(true);2830      return;2831    }2832    if (current.length === 0) return;2833    if (e.key === "Enter") {2834      e.preventDefault();2835      choose(current[Math.max(0, focusedIndex)]!);2836      return;2837    }2838    if (current.length === 1) return;2839    if (e.key === "ArrowDown") {2840      e.preventDefault();2841      setFocused(focusedIndex < current.length - 1 ? focusedIndex + 1 : 0);2842    } else if (e.key === "ArrowUp") {2843      e.preventDefault();2844      setFocused(focusedIndex > 0 ? focusedIndex - 1 : current.length - 1);2845    }2846  }28472848  let exitScheduled = false;2849  function dismiss(userAction = false) {2850    if (exitScheduled) return;2851    exitScheduled = true;2852    stopObserving();2853    document.removeEventListener("click", outsideClick, { capture: true });2854    document.removeEventListener("keydown", handleKeyDown);2855    if (userAction) options.onDismiss?.();2856    container.classList.add("is-exiting");2857    setTimeout(() => host.remove(), 130);2858  }28592860  function outsideClick(ev: MouseEvent) {2861    const path = ev.composedPath();2862    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);2863  }28642865  document.addEventListener("keydown", handleKeyDown);2866  document.body.appendChild(host);2867  render();2868  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);28692870  return dismiss;2871}28722873export interface CardSelectorEntry {2874  id: string;2875  title: string;2876  cardholderName?: string;2877  last4?: string;2878  expMonth?: string;2879  expYear?: string;2880  network?: import("../shared/types").CardNetwork;2881}28822883interface CardSelectorOptions {2884  domain?: string;2885  /** Caller-provided fill — receives the full CardEntry payload from the SW. */2886  onFill: (entry: import("../shared/types").VaultEntry) => void;2887  /** Called when the user explicitly dismisses (Escape, click-outside, ✕). */2888  onDismiss?: () => void;2889}28902891/**2892 * State 11 — passkey Pro gate. Shown when a free user triggers a WebAuthn2893 * passkey create or get. Renders as a fixed-position floating popup (no2894 * field anchor needed — passkeys don't require a focused input). Uses the2895 * same theme tokens and entrance animation as all other inline popup states.2896 */2897export function showPasskeyProGate(): void {2898  const domain = location.hostname.replace(/^www\./, "");28992900  const host = document.createElement("div");2901  host.setAttribute("data-peach-passkey-gate", "1");2902  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;";2903  const shadow = host.attachShadow({ mode: "closed" });29042905  const style = document.createElement("style");2906  style.textContent = `2907    :host { all: initial; }2908    .gate-wrap {2909      position: fixed;2910      top: 50%;2911      left: 50%;2912      transform: translate(-50%, -50%);2913      width: 280px;2914      pointer-events: auto;2915      animation: g-in 220ms cubic-bezier(0.16,1,0.3,1) both;2916    }2917    @keyframes g-in {2918      from { opacity:0; transform: translate(-50%,-52%); }2919      to   { opacity:1; transform: translate(-50%,-50%); }2920    }2921    .gate-wrap.is-exiting {2922      animation: g-out 130ms ease-in forwards;2923    }2924    @keyframes g-out {2925      to { opacity:0; transform: translate(-50%,-52%); }2926    }2927    .gate {2928      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};2929      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};2930      border-radius: 12px;2931      box-shadow: 0 12px 48px rgba(0,0,0,0.75);2932      padding: 16px;2933      font-family: Inter, sans-serif;2934    }2935    .gate-header {2936      display: flex;2937      align-items: center;2938      gap: 7px;2939      margin-bottom: 12px;2940      padding-bottom: 10px;2941      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};2942    }2943    .gate-domain {2944      font-size: 12px;2945      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};2946      font-family: "IBM Plex Mono", monospace;2947      overflow: hidden;2948      text-overflow: ellipsis;2949      white-space: nowrap;2950    }2951    .gate-title {2952      font-size: 14px;2953      font-weight: 500;2954      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};2955      margin-bottom: 6px;2956    }2957    .gate-subtitle {2958      font-size: 12px;2959      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.45)"};2960      line-height: 1.5;2961      margin-bottom: 14px;2962    }2963    .gate-btn {2964      display: block;2965      width: 100%;2966      padding: 9px 0;2967      border-radius: 8px;2968      border: none;2969      cursor: pointer;2970      font-size: 13px;2971      font-family: Inter, sans-serif;2972      font-weight: 500;2973      transition: opacity 100ms;2974      margin-bottom: 7px;2975      text-align: center;2976    }2977    .gate-btn:last-child { margin-bottom: 0; }2978    .gate-btn--accent {2979      background: ${accentHex};2980      color: #fff;2981    }2982    .gate-btn--accent:hover { opacity: 0.88; }2983    .gate-btn--ghost {2984      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};2985      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.45)"};2986    }2987    .gate-btn--ghost:hover { opacity: 0.75; }2988    .backdrop {2989      position: fixed;2990      inset: 0;2991      pointer-events: auto;2992    }2993  `;2994  shadow.appendChild(style);29952996  const backdrop = document.createElement("div");2997  backdrop.className = "backdrop";2998  shadow.appendChild(backdrop);29993000  const wrap = document.createElement("div");3001  wrap.className = "gate-wrap";3002  shadow.appendChild(wrap);30033004  const gate = document.createElement("div");3005  gate.className = "gate";3006  wrap.appendChild(gate);30073008  // Header: peach icon + domain3009  const header = document.createElement("div");3010  header.className = "gate-header";3011  const icon = document.createElement("span");3012  icon.innerHTML = peachIconSvg();3013  const domainEl = document.createElement("span");3014  domainEl.className = "gate-domain";3015  domainEl.textContent = domain;3016  header.append(icon, domainEl);3017  gate.appendChild(header);30183019  const title = document.createElement("div");3020  title.className = "gate-title";3021  title.textContent = "Passkeys are part of Peach Pro.";3022  gate.appendChild(title);30233024  const subtitle = document.createElement("div");3025  subtitle.className = "gate-subtitle";3026  subtitle.textContent = "Store and use passkeys across all your devices, securely.";3027  gate.appendChild(subtitle);30283029  const upgradeBtn = document.createElement("button");3030  upgradeBtn.className = "gate-btn gate-btn--accent";3031  upgradeBtn.type = "button";3032  upgradeBtn.textContent = "Upgrade to Pro";3033  gate.appendChild(upgradeBtn);30343035  const laterBtn = document.createElement("button");3036  laterBtn.className = "gate-btn gate-btn--ghost";3037  laterBtn.type = "button";3038  laterBtn.textContent = "Not right now";3039  gate.appendChild(laterBtn);30403041  function dismiss() {3042    wrap.classList.add("is-exiting");3043    setTimeout(() => host.remove(), 130);3044  }30453046  upgradeBtn.addEventListener("click", () => {3047    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: { feature: "passkeys" } }).catch(() => {});3048    dismiss();3049  });3050  laterBtn.addEventListener("click", dismiss);3051  backdrop.addEventListener("click", dismiss);30523053  document.addEventListener("keydown", function onEsc(e: KeyboardEvent) {3054    if (e.key === "Escape") { dismiss(); document.removeEventListener("keydown", onEsc); }3055  });30563057  document.body.appendChild(host);3058}30593060/**3061 * State 12 — passkey registration offer. Shown on Firefox when the MAIN-world3062 * detector sees the page invoke navigator.credentials.create(); content/index.ts3063 * checks vault + decline state then calls this. "Save passkey to Peach"3064 * initiates the popup-context credential flow; "Not now" records a 30-day3065 * decline for the domain so we don't re-show on every page reload.3066 */3067export function showPasskeyRegistrationOffer(args: {3068  rpId: string;3069  rpName?: string;3070  userName?: string;3071  userDisplayName?: string;3072}): void {3073  const domain = location.hostname.replace(/^www\./, "");3074  const displayName = args.rpName || domain;30753076  const host = document.createElement("div");3077  host.setAttribute("data-peach-passkey-offer", "1");3078  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483645;pointer-events:none;";3079  const shadow = host.attachShadow({ mode: "closed" });30803081  const style = document.createElement("style");3082  style.textContent = `3083    :host { all: initial; }3084    .offer-wrap {3085      position: fixed;3086      top: 16px;3087      right: 16px;3088      width: 320px;3089      pointer-events: auto;3090      animation: o-in 220ms cubic-bezier(0.16,1,0.3,1) both;3091    }3092    @keyframes o-in {3093      from { opacity: 0; transform: translateY(-6px); }3094      to   { opacity: 1; transform: translateY(0); }3095    }3096    .offer-wrap.is-exiting { animation: o-out 130ms ease-in forwards; }3097    @keyframes o-out { to { opacity: 0; transform: translateY(-6px); } }3098    .offer {3099      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3100      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3101      border-radius: 12px;3102      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3103      padding: 14px 14px 12px;3104      font-family: Inter, sans-serif;3105      position: relative;3106    }3107    .offer-close {3108      position: absolute;3109      top: 8px;3110      right: 8px;3111      width: 18px;3112      height: 18px;3113      border: none;3114      background: transparent;3115      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3116      cursor: pointer;3117      font-size: 14px;3118      line-height: 1;3119      padding: 0;3120    }3121    .offer-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3122    .offer-header {3123      display: flex;3124      align-items: center;3125      gap: 7px;3126      margin-bottom: 8px;3127      padding-bottom: 8px;3128      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3129    }3130    .offer-domain {3131      font-size: 12px;3132      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3133      font-family: "IBM Plex Mono", monospace;3134      overflow: hidden;3135      text-overflow: ellipsis;3136      white-space: nowrap;3137    }3138    .offer-title {3139      font-size: 13px;3140      font-weight: 500;3141      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3142      margin-bottom: 4px;3143    }3144    .offer-subtitle {3145      font-size: 11px;3146      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3147      line-height: 1.45;3148      margin-bottom: 12px;3149    }3150    .offer-btn {3151      display: block;3152      width: 100%;3153      padding: 8px 0;3154      border-radius: 7px;3155      border: none;3156      cursor: pointer;3157      font-size: 12px;3158      font-family: Inter, sans-serif;3159      font-weight: 500;3160      transition: opacity 100ms;3161      margin-bottom: 6px;3162      text-align: center;3163    }3164    .offer-btn:last-child { margin-bottom: 0; }3165    .offer-btn--accent { background: ${accentHex}; color: #fff; }3166    .offer-btn--accent:hover { opacity: 0.88; }3167    .offer-btn--ghost {3168      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3169      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3170    }3171    .offer-btn--ghost:hover { opacity: 0.75; }3172  `;3173  shadow.appendChild(style);31743175  const wrap = document.createElement("div");3176  wrap.className = "offer-wrap";3177  shadow.appendChild(wrap);31783179  const offer = document.createElement("div");3180  offer.className = "offer";3181  wrap.appendChild(offer);31823183  const closeBtn = document.createElement("button");3184  closeBtn.className = "offer-close";3185  closeBtn.type = "button";3186  closeBtn.setAttribute("aria-label", "Dismiss");3187  closeBtn.textContent = "✕";3188  offer.appendChild(closeBtn);31893190  const header = document.createElement("div");3191  header.className = "offer-header";3192  const icon = document.createElement("span");3193  icon.innerHTML = peachIconSvg();3194  const domainEl = document.createElement("span");3195  domainEl.className = "offer-domain";3196  domainEl.textContent = domain;3197  header.append(icon, domainEl);3198  offer.appendChild(header);31993200  const title = document.createElement("div");3201  title.className = "offer-title";3202  title.textContent = "This site supports passkeys.";3203  offer.appendChild(title);32043205  const subtitle = document.createElement("div");3206  subtitle.className = "offer-subtitle";3207  subtitle.textContent = "Save one to Peach for faster, passwordless sign-in.";3208  offer.appendChild(subtitle);32093210  const saveBtn = document.createElement("button");3211  saveBtn.className = "offer-btn offer-btn--accent";3212  saveBtn.type = "button";3213  saveBtn.textContent = "Save passkey to Peach";3214  offer.appendChild(saveBtn);32153216  const laterBtn = document.createElement("button");3217  laterBtn.className = "offer-btn offer-btn--ghost";3218  laterBtn.type = "button";3219  laterBtn.textContent = "Not now";3220  offer.appendChild(laterBtn);32213222  function dismiss(decline: boolean) {3223    if (decline) {3224      chrome.runtime.sendMessage({3225        type: "PASSKEY_OFFER_DECLINE",3226        payload: { domain },3227      }).catch(() => {});3228    }3229    wrap.classList.add("is-exiting");3230    setTimeout(() => host.remove(), 130);3231  }32323233  saveBtn.addEventListener("click", () => {3234    chrome.runtime.sendMessage({3235      type: "INITIATE_FIREFOX_PASSKEY_CREATE",3236      payload: {3237        rpId: args.rpId,3238        rpName: args.rpName ?? displayName,3239        userName: args.userName ?? "user",3240        userDisplayName: args.userDisplayName,3241      },3242    }).catch(() => {});3243    dismiss(false);3244  });3245  laterBtn.addEventListener("click", () => dismiss(true));3246  closeBtn.addEventListener("click", () => dismiss(true));32473248  document.body.appendChild(host);3249}32503251/**3252 * State 11 — passkey available indicator. Shown when the user lands on a3253 * domain for which they already have a stored passkey. Tells them where to3254 * find it (the entry already shows in the vault list); the "Sign in with3255 * passkey" button opens the popup so they can use the platform authenticator3256 * UI directly. On Chrome, the existing webAuthenticationProxy flow handles3257 * the actual sign-in transparently, so this banner is informational only.3258 */3259export function showPasskeyAvailable(args: {3260  rpId: string;3261  userName: string;3262  fromBrowser?: "chrome" | "firefox";3263  currentBrowser?: "chrome" | "firefox" | "unknown";3264}): void {3265  const domain = location.hostname.replace(/^www\./, "");3266  const crossBrowser =3267    args.fromBrowser &&3268    args.currentBrowser &&3269    args.currentBrowser !== "unknown" &&3270    args.fromBrowser !== args.currentBrowser;32713272  const host = document.createElement("div");3273  host.setAttribute("data-peach-passkey-available", "1");3274  host.style.cssText = "all:initial;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483644;pointer-events:none;";3275  const shadow = host.attachShadow({ mode: "closed" });32763277  const style = document.createElement("style");3278  style.textContent = `3279    :host { all: initial; }3280    .avail-wrap {3281      position: fixed;3282      top: 16px;3283      right: 16px;3284      width: 320px;3285      pointer-events: auto;3286      animation: a-in 220ms cubic-bezier(0.16,1,0.3,1) both;3287    }3288    @keyframes a-in {3289      from { opacity: 0; transform: translateY(-6px); }3290      to   { opacity: 1; transform: translateY(0); }3291    }3292    .avail-wrap.is-exiting { animation: a-out 130ms ease-in forwards; }3293    @keyframes a-out { to { opacity: 0; transform: translateY(-6px); } }3294    .avail {3295      background: ${popupTheme === "light" ? "#f8f5f0" : "#1a1712"};3296      border: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.10)" : "rgba(240,232,216,0.09)"};3297      border-radius: 12px;3298      box-shadow: 0 12px 48px rgba(0,0,0,0.55);3299      padding: 14px 14px 12px;3300      font-family: Inter, sans-serif;3301      position: relative;3302    }3303    .avail-close {3304      position: absolute;3305      top: 8px;3306      right: 8px;3307      width: 18px;3308      height: 18px;3309      border: none;3310      background: transparent;3311      color: ${popupTheme === "light" ? "rgba(0,0,0,0.4)" : "rgba(240,232,216,0.4)"};3312      cursor: pointer;3313      font-size: 14px;3314      line-height: 1;3315      padding: 0;3316    }3317    .avail-close:hover { color: ${popupTheme === "light" ? "rgba(0,0,0,0.7)" : "rgba(240,232,216,0.7)"}; }3318    .avail-header {3319      display: flex;3320      align-items: center;3321      gap: 7px;3322      margin-bottom: 8px;3323      padding-bottom: 8px;3324      border-bottom: 1px solid ${popupTheme === "light" ? "rgba(0,0,0,0.07)" : "rgba(240,232,216,0.07)"};3325    }3326    .avail-domain {3327      font-size: 12px;3328      color: ${popupTheme === "light" ? "rgba(0,0,0,0.45)" : "rgba(240,232,216,0.45)"};3329      font-family: "IBM Plex Mono", monospace;3330    }3331    .avail-label {3332      font-size: 9px;3333      letter-spacing: 0.16em;3334      text-transform: uppercase;3335      color: ${accentHex};3336      margin-bottom: 4px;3337    }3338    .avail-user {3339      font-size: 13px;3340      font-weight: 500;3341      color: ${popupTheme === "light" ? "#1a1712" : "rgba(240,232,216,0.92)"};3342      margin-bottom: 12px;3343      overflow: hidden;3344      text-overflow: ellipsis;3345      white-space: nowrap;3346    }3347    .avail-cross {3348      font-size: 11px;3349      color: ${popupTheme === "light" ? "rgba(0,0,0,0.50)" : "rgba(240,232,216,0.50)"};3350      line-height: 1.45;3351      margin-bottom: 12px;3352      padding: 8px;3353      background: ${popupTheme === "light" ? "rgba(0,0,0,0.04)" : "rgba(240,232,216,0.04)"};3354      border-radius: 6px;3355    }3356    .avail-btn {3357      display: block;3358      width: 100%;3359      padding: 8px 0;3360      border-radius: 7px;3361      border: none;3362      cursor: pointer;3363      font-size: 12px;3364      font-family: Inter, sans-serif;3365      font-weight: 500;3366      transition: opacity 100ms;3367      margin-bottom: 6px;3368      text-align: center;3369    }3370    .avail-btn:last-child { margin-bottom: 0; }3371    .avail-btn--accent { background: ${accentHex}; color: #fff; }3372    .avail-btn--accent:hover { opacity: 0.88; }3373    .avail-btn--ghost {3374      background: ${popupTheme === "light" ? "rgba(0,0,0,0.06)" : "rgba(240,232,216,0.07)"};3375      color: ${popupTheme === "light" ? "rgba(0,0,0,0.55)" : "rgba(240,232,216,0.50)"};3376    }3377    .avail-btn--ghost:hover { opacity: 0.75; }3378  `;3379  shadow.appendChild(style);33803381  const wrap = document.createElement("div");3382  wrap.className = "avail-wrap";3383  shadow.appendChild(wrap);33843385  const avail = document.createElement("div");3386  avail.className = "avail";3387  wrap.appendChild(avail);33883389  const closeBtn = document.createElement("button");3390  closeBtn.className = "avail-close";3391  closeBtn.type = "button";3392  closeBtn.setAttribute("aria-label", "Dismiss");3393  closeBtn.textContent = "✕";3394  avail.appendChild(closeBtn);33953396  const header = document.createElement("div");3397  header.className = "avail-header";3398  const icon = document.createElement("span");3399  icon.innerHTML = peachIconSvg();3400  const domainEl = document.createElement("span");3401  domainEl.className = "avail-domain";3402  domainEl.textContent = domain;3403  header.append(icon, domainEl);3404  avail.appendChild(header);34053406  const label = document.createElement("div");3407  label.className = "avail-label";3408  label.textContent = "PASSKEY";3409  avail.appendChild(label);34103411  const user = document.createElement("div");3412  user.className = "avail-user";3413  user.textContent = args.userName;3414  avail.appendChild(user);34153416  if (crossBrowser) {3417    const cross = document.createElement("div");3418    cross.className = "avail-cross";3419    cross.textContent =3420      args.fromBrowser === "chrome"3421        ? "This passkey was created on Chrome. To use it on Firefox, re-register it on this device."3422        : "This passkey was created on Firefox. To use it on Chrome, re-register it on this device.";3423    avail.appendChild(cross);3424  }34253426  const signInBtn = document.createElement("button");3427  signInBtn.className = "avail-btn avail-btn--accent";3428  signInBtn.type = "button";3429  signInBtn.textContent = "Sign in with passkey";3430  avail.appendChild(signInBtn);34313432  const passwordBtn = document.createElement("button");3433  passwordBtn.className = "avail-btn avail-btn--ghost";3434  passwordBtn.type = "button";3435  passwordBtn.textContent = "Use password instead";3436  avail.appendChild(passwordBtn);34373438  function dismiss() {3439    wrap.classList.add("is-exiting");3440    setTimeout(() => host.remove(), 130);3441  }34423443  signInBtn.addEventListener("click", () => {3444    // On Chrome: the user clicking the page's own Sign-in button is what3445    //   triggers webAuthenticationProxy → existing background flow handles it.3446    //   Our button just dismisses since the page itself drives auth.3447    // On Firefox: cross-browser passkeys can't be used, so we just dismiss3448    //   and surface the entry for manual reference (popup view).3449    dismiss();3450    chrome.runtime.sendMessage({ type: "OPEN_PRO_GATE", payload: {} }).catch(() => {});3451  });3452  passwordBtn.addEventListener("click", dismiss);3453  closeBtn.addEventListener("click", dismiss);34543455  document.body.appendChild(host);3456}34573458/**3459 * State 7 — card silver platter. Single-card focused fill view rendered3460 * over the cc-number field. Reuses the SELECTOR_STYLES Shadow DOM, the3461 * theme tokens, and the .sp-fill-btn / .sp-actions primary action classes3462 * so card and login flows render identically. Multi-card list view is a3463 * follow-up; today this picks the first card.3464 */3465export function showCardSelector(3466  anchorEl: HTMLInputElement,3467  cards: CardSelectorEntry[],3468  options: CardSelectorOptions3469): () => void {3470  if (cards.length === 0) return () => {};3471  const card = cards[0]!;34723473  const host = document.createElement("div");3474  host.style.cssText = "position: absolute; z-index: 2147483647;";3475  host.style.setProperty("--peach-accent", accentHex);3476  host.style.setProperty("--peach-accent-dim", withAlpha(accentHex, "28"));3477  host.style.setProperty("--peach-glow", withAlpha(accentHex, "18"));3478  host.style.setProperty("--peach-border-accent", withAlpha(accentHex, "30"));3479  const shadow = host.attachShadow({ mode: "closed" });34803481  const style = shadow.appendChild(document.createElement("style"));3482  style.textContent = SELECTOR_STYLES;34833484  const rect = anchorEl.getBoundingClientRect();3485  host.style.top = `${rect.bottom + window.scrollY + 5}px`;3486  host.style.left = `${rect.left + window.scrollX}px`;3487  host.style.width = `${Math.min(Math.max(rect.width, 320), 400)}px`;34883489  const container = shadow.appendChild(document.createElement("div"));3490  container.className = "peach-inline-popup";3491  container.setAttribute("data-theme", popupTheme);34923493  // Domain header — eyebrow communicates the card context, not the site3494  const domHdr = document.createElement("div");3495  domHdr.className = "domain-header";3496  const eyebrow = document.createElement("div");3497  eyebrow.className = "domain-eyebrow";3498  eyebrow.textContent = "Pay with Peach";3499  const domName = document.createElement("div");3500  domName.className = "domain-name";3501  domName.textContent = options.domain ?? location.hostname.replace(/^www\./, "");3502  domHdr.append(eyebrow, domName);3503  container.appendChild(domHdr);35043505  const platter = document.createElement("div");3506  platter.className = "card-platter";35073508  if (card.network && card.network !== "unknown") {3509    const net = document.createElement("div");3510    net.className = "cp-network";3511    net.textContent = card.network;3512    platter.appendChild(net);3513  }35143515  const nick = document.createElement("div");3516  nick.className = "cp-nickname";3517  nick.textContent = card.title;3518  platter.appendChild(nick);35193520  if (card.last4) {3521    const l4 = document.createElement("div");3522    l4.className = "cp-last4";3523    l4.textContent = `•••• ${card.last4}`;3524    platter.appendChild(l4);3525  }35263527  const meta = document.createElement("div");3528  meta.className = "cp-meta";3529  if (card.cardholderName) {3530    const name = document.createElement("span");3531    name.textContent = card.cardholderName;3532    meta.appendChild(name);3533  }3534  if (card.expMonth && card.expYear) {3535    if (card.cardholderName) {3536      const sep = document.createElement("span");3537      sep.className = "cp-meta-sep";3538      sep.textContent = "·";3539      meta.appendChild(sep);3540    }3541    const exp = document.createElement("span");3542    const yy = card.expYear.length === 4 ? card.expYear.slice(-2) : card.expYear;3543    exp.textContent = `${card.expMonth.padStart(2, "0")}/${yy}`;3544    meta.appendChild(exp);3545  }3546  if (meta.childElementCount > 0) platter.appendChild(meta);35473548  const fillWrap = document.createElement("div");3549  fillWrap.className = "cp-fill-wrap";3550  const fillBtn = document.createElement("button");3551  fillBtn.className = "sp-fill-btn";3552  fillBtn.type = "button";3553  fillBtn.textContent = "Fill card details";3554  fillBtn.addEventListener("click", async () => {3555    if (fillBtn.disabled) return;3556    fillBtn.disabled = true;3557    fillBtn.classList.add("filled");3558    fillBtn.innerHTML = checkSvgStr();3559    const resp = await chrome.runtime.sendMessage({3560      type: "GET_ENTRY_FOR_FILL",3561      payload: { id: card.id },3562    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3563    if (resp?.ok && resp.data) options.onFill(resp.data);3564    setTimeout(() => dismiss(), 400);3565  });3566  fillWrap.appendChild(fillBtn);3567  platter.appendChild(fillWrap);35683569  // Secondary actions — copy number, copy CVC, dismiss3570  const actions = document.createElement("div");3571  actions.className = "sp-actions";35723573  function flashBtn(b: HTMLButtonElement) {3574    b.classList.add("flashed");3575    setTimeout(() => b.classList.remove("flashed"), 700);3576  }35773578  // M3/QUA-005: clipboard + background COPY both failed — show user.3579  function flashCopyError(b: HTMLButtonElement) {3580    const original = b.textContent ?? "";3581    b.textContent = "Blocked";3582    b.classList.add("flashed");3583    setTimeout(() => {3584      b.classList.remove("flashed");3585      if (b.isConnected) b.textContent = original;3586    }, 1200);3587  }35883589  async function fetchFullCard(): Promise<import("../shared/types").VaultEntry | null> {3590    const resp = await chrome.runtime.sendMessage({3591      type: "GET_ENTRY_FOR_FILL",3592      payload: { id: card.id },3593    }).catch(() => null) as { ok: boolean; data?: import("../shared/types").VaultEntry } | null;3594    return resp?.ok && resp.data ? resp.data : null;3595  }35963597  const copyNum = document.createElement("button");3598  copyNum.className = "sp-action-btn";3599  copyNum.type = "button";3600  copyNum.title = "Copy card number";3601  copyNum.textContent = "Copy number";3602  copyNum.addEventListener("click", async (e) => {3603    e.stopPropagation();3604    const full = await fetchFullCard();3605    if (!full?.cardNumber) return;3606    let alreadyWritten = false;3607    try {3608      await navigator.clipboard.writeText(full.cardNumber);3609      alreadyWritten = true;3610    } catch (err) {3611      console.warn("[Peach] clipboard write denied:", err);3612    }3613    const resp = await chrome.runtime.sendMessage({3614      type: "COPY",3615      payload: { text: full.cardNumber, label: "Card number", alreadyWritten },3616    }).catch(() => null) as { ok?: boolean } | null;3617    if (alreadyWritten || resp?.ok) flashBtn(copyNum);3618    else flashCopyError(copyNum);3619  });3620  actions.appendChild(copyNum);36213622  const copyCvc = document.createElement("button");3623  copyCvc.className = "sp-action-btn";3624  copyCvc.type = "button";3625  copyCvc.title = "Copy CVC";3626  copyCvc.textContent = "Copy CVC";3627  copyCvc.addEventListener("click", async (e) => {3628    e.stopPropagation();3629    const full = await fetchFullCard();3630    if (!full?.cvc) return;3631    let alreadyWritten = false;3632    try {3633      await navigator.clipboard.writeText(full.cvc);3634      alreadyWritten = true;3635    } catch (err) {3636      console.warn("[Peach] clipboard write denied:", err);3637    }3638    const resp = await chrome.runtime.sendMessage({3639      type: "COPY",3640      payload: { text: full.cvc, label: "CVC", alreadyWritten },3641    }).catch(() => null) as { ok?: boolean } | null;3642    if (alreadyWritten || resp?.ok) flashBtn(copyCvc);3643    else flashCopyError(copyCvc);3644  });3645  actions.appendChild(copyCvc);36463647  const closeBtn = document.createElement("button");3648  closeBtn.className = "sp-action-btn";3649  closeBtn.type = "button";3650  closeBtn.title = "Dismiss";3651  closeBtn.textContent = "✕";3652  closeBtn.addEventListener("click", (e) => {3653    e.stopPropagation();3654    dismiss(true);3655  });3656  actions.appendChild(closeBtn);36573658  platter.appendChild(actions);3659  container.appendChild(platter);36603661  document.body.appendChild(host);3662  function updatePosition() {3663    const r = anchorEl.getBoundingClientRect();3664    host.style.top = `${r.bottom + window.scrollY + 5}px`;3665    host.style.left = `${r.left + window.scrollX}px`;3666  }3667  const stopObserving = observeAnchorPosition(anchorEl, updatePosition);36683669  function onKeyDown(e: KeyboardEvent) {3670    if (e.key === "Escape") { e.preventDefault(); dismiss(true); }3671  }3672  document.addEventListener("keydown", onKeyDown);36733674  let exitScheduled = false;3675  function dismiss(userAction = false) {3676    if (exitScheduled) return;3677    exitScheduled = true;3678    stopObserving();3679    document.removeEventListener("click", outsideClick, { capture: true });3680    document.removeEventListener("keydown", onKeyDown);3681    if (userAction) options.onDismiss?.();3682    container.classList.add("is-exiting");3683    setTimeout(() => host.remove(), 130);3684  }36853686  function outsideClick(ev: MouseEvent) {3687    const path = ev.composedPath();3688    if (!path.includes(host) && !path.includes(anchorEl)) dismiss(true);3689  }3690  setTimeout(() => document.addEventListener("click", outsideClick, { capture: true }), 0);36913692  return dismiss;3693}