index.ts

39.0 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  getDeepActiveInput,5  getPageDomain,6  isLoginForm,7  isSignupForm,8  isVisible,9} from "./detect";10import {11  CardSelectorEntry,12  injectFieldIcon,13  observeAnchorPosition,14  SelectorEntry,15  showAutofillSelector,16  showCardSelector,17  showPasskeyAvailable,18  showPasskeyProGate,19  showPasskeyRegistrationOffer,20  showRememberSiteToast,21} from "./inject";22import { detectBrowser } from "../shared/browser";23import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";24import { fillCardForm, fillFields, setNativeValue } from "./fill";25import { setupSaveDetection } from "./save";26import { contentMLDetector } from "./content-ml-detector";27import { detectPasswordPolicy } from "./policy";28import type { FieldPrediction } from "../shared/ml";29import { generateTOTP } from "../crypto/totp";30import type { SavedIdentity, VaultEntry } from "../shared/types";3132// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value33// so we can tear down listeners if we ever need to re-process the same field.34// When the input is GC'd (SPA nav, React re-render), the map entry goes with35// it and we can re-inject without leaking the old handler.36const processedInputs = new WeakMap<HTMLInputElement, () => void>();37const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3839let currentDismiss: (() => void) | null = null;40// Field whose selector is currently open — used to avoid dismiss+reopen flicker41let currentAnchorField: HTMLInputElement | null = null;42// Prevents two concurrent handleFieldInteraction calls for the same field43const pendingInteractions = new WeakSet<HTMLInputElement>();44// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).45// Suppresses spurious reopens until focus moves to a different field. Layer 146// of the dismissal model — see Projects.md §4.12.47let lastDismissedField: HTMLInputElement | null = null;4849// ── Dismissal lock (Layer 2) ────────────────────────────────────────50// After any user-initiated dismiss, briefly block ALL reopens regardless of51// which field is focused. Catches the case where a page rapidly moves focus52// between fields after Escape — without this, focus moving to a SECOND field53// in <100ms would re-trigger the popup before the user finished dismissing.54const DISMISS_LOCK_MS = 800;55let dismissLock = false;56let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;57function startDismissLock(): void {58  dismissLock = true;59  if (dismissLockTimer) clearTimeout(dismissLockTimer);60  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);61}62function canOpen(): boolean { return !dismissLock; }6364// ── Fill-success lock ───────────────────────────────────────────────65// After Peach autofills a form, the popup must NOT reappear on the filled66// fields, on the submit button (some sites refocus it briefly), or on any67// field in that form — even when host-page DOM mutations or the form's own68// validation flow refocus an input. Implemented as a WeakSet of forms plus69// a page-level timestamp:70//   - filledForms: every form Peach has filled this page session. Survives71//     until the form leaves the DOM (WeakSet GC).72//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders73//     window for fields that aren't inside a <form> element (some SPAs).74// SPA navigation resets pageFilledAt via the urlObserver below; filledForms75// self-empties as old form elements get GC'd.76const filledForms = new WeakSet<HTMLFormElement>();77let pageFilledAt: number | null = null;78const PAGE_FILL_GRACE_MS = 3000;7980function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {81  for (const f of fields) {82    if (!f) continue;83    const form = f.closest("form");84    if (form) filledForms.add(form);85  }86  pageFilledAt = Date.now();87}8889function wasAlreadyFilled(field: HTMLInputElement): boolean {90  const form = field.closest("form");91  if (form && filledForms.has(form)) return true;92  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;93  return false;94}9596function clearFillStateForExplicitSummon(field: HTMLInputElement): void {97  const form = field.closest("form");98  if (form) filledForms.delete(form);99  pageFilledAt = null;100}101102// Some sites briefly focus the submit button when the user clicks it (visual103// feedback, blur/focus dance for validation animations). Catch those at the104// focusin layer so we don't re-trigger handleFieldInteraction for an event105// target that was never going to be a credential field anyway.106function isSubmitButton(el: EventTarget | null): boolean {107  if (!(el instanceof HTMLElement)) return false;108  if (el instanceof HTMLButtonElement && el.type !== "button") return true;109  if (el instanceof HTMLInputElement && el.type === "submit") return true;110  if (el.getAttribute("type") === "submit") return true;111  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();112  if (!text || text.length > 24) return false;113  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);114}115116function debounce<T extends (...args: unknown[]) => void>(117  fn: T,118  ms: number119): (...args: Parameters<T>) => void {120  let timer: ReturnType<typeof setTimeout>;121  return (...args: Parameters<T>) => {122    clearTimeout(timer);123    timer = setTimeout(() => fn(...args), ms);124  };125}126127function showToast(message: string): void {128  const toast = document.createElement("div");129  toast.style.cssText = `130    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);131    background: #131109; color: #F0E8D8; padding: 8px 16px;132    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;133    font-size: 11px; z-index: 2147483647; opacity: 0;134    transition: opacity 200ms ease;135    border: 1px solid rgba(240,232,216,0.07);136    pointer-events: none;137  `;138  toast.textContent = message;139  document.body.appendChild(toast);140  requestAnimationFrame(() => { toast.style.opacity = "1"; });141  setTimeout(() => {142    toast.style.opacity = "0";143    setTimeout(() => toast.remove(), 200);144  }, 2000);145}146147function showSearchPalette(): void {148  const host = document.createElement("div");149  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";150  document.body.appendChild(host);151  const shadow = host.attachShadow({ mode: "closed" });152153  const style = document.createElement("style");154  style.textContent = `155    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;156      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;157      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}158    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);159      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}160    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}161    .s{padding:8px 12px}162    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);163      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;164      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}165    .l{max-height:220px;overflow-y:auto}166    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}167    .e:hover{background:rgba(240,232,216,.06)}168    .et{font-size:12px}169    .eu{font-size:10px;color:rgba(240,232,216,.45)}170    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}171  `;172173  let allEntries: SelectorEntry[] = [];174  let query = "";175176  const panel = document.createElement("div");177  panel.className = "p";178179  const hdr = document.createElement("div");180  hdr.className = "h";181  const hdrText = document.createElement("span");182  hdrText.textContent = "No form detected — search your vault";183  const closeBtn = document.createElement("button");184  closeBtn.className = "x";185  closeBtn.textContent = "✕";186  hdr.appendChild(hdrText);187  hdr.appendChild(closeBtn);188189  const searchWrap = document.createElement("div");190  searchWrap.className = "s";191  const searchInput = document.createElement("input");192  searchInput.placeholder = "search...";193  searchWrap.appendChild(searchInput);194195  const list = document.createElement("div");196  list.className = "l";197198  panel.appendChild(hdr);199  panel.appendChild(searchWrap);200  panel.appendChild(list);201  shadow.appendChild(style);202  shadow.appendChild(panel);203204  function close() { host.remove(); }205206  closeBtn.onclick = close;207208  function onKeyDown(e: KeyboardEvent) {209    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }210  }211  document.addEventListener("keydown", onKeyDown, true);212213  function render() {214    const q = query.toLowerCase();215    const filtered = q216      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))217      : allEntries;218    list.innerHTML = "";219    if (filtered.length === 0) {220      const em = document.createElement("div");221      em.className = "em";222      em.textContent = query ? "no matches" : "vault is empty";223      list.appendChild(em);224      return;225    }226    for (const entry of filtered.slice(0, 20)) {227      const row = document.createElement("div");228      row.className = "e";229      const title = document.createElement("div");230      title.className = "et";231      title.textContent = entry.title;232      row.appendChild(title);233      if (entry.username) {234        const user = document.createElement("div");235        user.className = "eu";236        user.textContent = entry.username;237        row.appendChild(user);238      }239      row.onclick = async () => {240        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });241        const r = resp as { ok: boolean; data?: { password?: string } };242        if (r.ok && r.data?.password) {243          let alreadyWritten = false;244          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}245          await chrome.runtime.sendMessage({246            type: "COPY",247            payload: { text: r.data.password, label: "Password", alreadyWritten },248          });249          showToast("Password copied");250        } else {251          showToast("Could not copy password");252        }253        close();254        document.removeEventListener("keydown", onKeyDown, true);255      };256      list.appendChild(row);257    }258  }259260  searchInput.oninput = () => { query = searchInput.value; render(); };261262  fetchAutofillEntries(getPageDomain(), true).then(result => {263    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }264    allEntries = result.entries;265    render();266    searchInput.focus();267  });268}269270function setNativeValue(el: HTMLInputElement, value: string): void {271  const nativeSetter = Object.getOwnPropertyDescriptor(272    HTMLInputElement.prototype, "value"273  )!.set!;274  nativeSetter.call(el, value);275  el.dispatchEvent(new Event("input", { bubbles: true }));276  el.dispatchEvent(new Event("change", { bubbles: true }));277}278279function findTOTPField(): HTMLInputElement | null {280  const inputs = document.querySelectorAll<HTMLInputElement>("input");281  for (const input of inputs) {282    if (!isVisible(input)) continue;283    const autocomplete = input.autocomplete.toLowerCase();284    const nameId = (input.name + input.id).toLowerCase();285    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();286    if (287      autocomplete === "one-time-code" ||288      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)289    ) {290      return input;291    }292    const labelEl = input.closest("label");293    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {294      return input;295    }296  }297  return null;298}299300async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {301  await new Promise((r) => setTimeout(r, 400));302  if (totpField.value === "" || totpField.value.trim() === "") {303    const { code } = generateTOTP(totpSecret);304    setNativeValue(totpField, code);305    showToast("TOTP autofilled");306  }307}308309310async function handleAutofill(311  field: HTMLInputElement,312  usernameEl: HTMLInputElement | null,313  passwordEl: HTMLInputElement,314  entry: VaultEntry315): Promise<void> {316  if (!entry.username && !entry.password) return;317  const pageDomain = getPageDomain();318  const form = passwordEl.closest("form") as HTMLFormElement | null;319  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);320321  if (entry.canary) {322    chrome.runtime.sendMessage({323      type: "FIRE_CANARY_PING",324      payload: {325        webhookUrl: entry.canary.webhookUrl,326        entryTitle: entry.title,327        trigger: "autofilled",328      },329    }).catch(() => {});330    chrome.runtime.sendMessage({331      type: "UPDATE_ENTRY",332      payload: {333        id: entry.id,334        patch: {335          canary: {336            ...entry.canary,337            lastPinged: Date.now(),338            pingCount: (entry.canary.pingCount ?? 0) + 1,339          },340        },341      },342    }).catch(() => {});343  }344345  if (entry.totp) {346    const { code } = generateTOTP(entry.totp);347    let alreadyWritten = false;348    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}349    const response = await chrome.runtime.sendMessage({350      type: "COPY",351      payload: { text: code, label: "TOTP", alreadyWritten },352    });353    if (alreadyWritten || (response as { ok?: boolean }).ok) {354      showToast("TOTP copied · " + code);355    }356    const totpField = findTOTPField();357    if (totpField) {358      autofillTOTP(totpField, entry.totp);359    }360  }361}362363async function fetchAutofillEntries(364  domain: string,365  includeAll = false366): Promise<{ entries: SelectorEntry[]; locked: boolean }> {367  const response = await chrome.runtime.sendMessage({368    type: "AUTOFILL_QUERY",369    payload: { domain, includeAll },370  });371  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };372  if (!res.ok && res.error === "VAULT_LOCKED") {373    return { entries: [], locked: true };374  }375  return { entries: res.data ?? [], locked: false };376}377378379function resolveAutofillFieldType(380  el: HTMLInputElement,381  predictedType?: FieldPrediction["type"] | null382): "password" | "username" | "email" | null {383  if (384    predictedType === "password" ||385    predictedType === "username" ||386    predictedType === "email"387  ) {388    return predictedType;389  }390391  const detected = detectLoginFields().find((field) => field.el === el)?.type;392  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {393    return detected;394  }395396  const htmlType = el.type.toLowerCase();397  if (htmlType === "password") return "password";398  if (htmlType === "email") return "email";399  return null;400}401402async function openAutofillSelector(403  anchorField: HTMLInputElement,404  usernameEl: HTMLInputElement | null,405  passwordEl: HTMLInputElement,406  domainEntries: SelectorEntry[],407  searchableEntries: SelectorEntry[],408  domain: string409): Promise<void> {410  // No saved entries for this site → signup/new-account mode.411  // Fetch vault identities for the identity-first surface and locate412  // the confirm-password field so "Copy & fill" can populate it too.413  const isSignup = domainEntries.length === 0;414  let savedIdentities: SavedIdentity[] | undefined;415  let confirmEl: HTMLInputElement | null = null;416  if (isSignup) {417    try {418      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as419        { ok: boolean; data?: SavedIdentity[] } | null;420      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;421    } catch { /* silent fallback */ }422423    const form = passwordEl.closest("form") ?? document.body;424    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));425    confirmEl = allPwInputs.find(426      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)427    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);428  }429430  currentDismiss?.();431  currentAnchorField = anchorField;432  currentDismiss = showAutofillSelector(433    anchorField,434    domainEntries,435    async (id: string) => {436      currentDismiss = null;437      currentAnchorField = null;438      const entryResponse = await chrome.runtime.sendMessage({439        type: "GET_ENTRY_FOR_FILL",440        payload: { id },441      });442      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;443      if (entry) {444        await handleAutofill(anchorField, usernameEl, passwordEl, entry);445        recordFillSuccess(anchorField, usernameEl, passwordEl);446        // Offer to remember the current site for this entry only if none of447        // its known domains (primary + additional) match — otherwise the448        // user already mapped it and the prompt would be noise.449        const pageDomain = location.hostname.replace(/^www\./, "");450        const entryDomains = new Set<string>();451        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {452          try {453            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));454          } catch { /* ignore unparseable */ }455        }456        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {457          showRememberSiteToast(pageDomain, entry.id);458        }459      }460    },461    {462      domain,463      searchableEntries,464      isSignup,465      savedIdentities,466      onFillFields: (username, password) => {467        const form = passwordEl.closest("form") as HTMLFormElement | null;468        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());469        if (password && confirmEl) setNativeValue(confirmEl, password);470        recordFillSuccess(anchorField, usernameEl, passwordEl);471      },472      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },473    }474  );475}476477478async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {479  const field = anchorField ?? getDeepActiveInput();480  if (!field) return;481  if (!isVisible(field)) return;482483  // Layer 2: post-dismiss global lock. Catches rapid focus moves between484  // fields immediately after Escape/click-outside.485  if (!canOpen()) return;486487  // If a selector is already open for this exact field, don't flicker it.488  if (currentDismiss && currentAnchorField === field) return;489490  // If focus moved to a different field, the previous per-field dismiss lock491  // no longer applies.492  if (field !== lastDismissedField) lastDismissedField = null;493  // Layer 1: the user explicitly dismissed this field's selector — don't494  // reopen it until focus has genuinely moved away and come back.495  if (field === lastDismissedField) return;496497  // Fill-success lock: Peach already filled this form (or fired a fill498  // anywhere on the page within the grace window). Sites often refocus an499  // input on submit click, on validation, or on a transition to a success500  // state — none of those should re-open the popup.501  if (wasAlreadyFilled(field)) return;502503  // Prevent two concurrent calls for the same field (e.g. focusin + icon click504  // firing simultaneously — the second call would dismiss the first's selector).505  if (pendingInteractions.has(field)) return;506  pendingInteractions.add(field);507508  try {509    const fieldType = field.type.toLowerCase();510511    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {512      return preds[0] ?? null;513    });514515    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {516      const timeout = setTimeout(() => resolve(null), 150);517      mlPromise.then((pred) => {518        clearTimeout(timeout);519        resolve(pred);520      });521    });522523    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {524      return;525    }526527    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);528    if (autofillFieldType) {529      reattachListeners(field, autofillFieldType);530    }531532    let fields = detectLoginFields();533    const loginForm = isLoginForm(fields);534    const signupForm = isSignupForm(fields);535    if (!loginForm && !signupForm) {536      return;537    }538539    const domain = getPageDomain();540    const firstResult = await fetchAutofillEntries(domain);541542    // Vault is locked — show an inline unlock prompt.543    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so544    // there is no double-trigger race between onUnlocked and the broadcast.545    if (firstResult.locked) {546      currentDismiss?.();547      currentAnchorField = field;548      currentDismiss = showAutofillSelector(549        field,550        [],551        () => {},552        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }553      );554      return;555    }556557    const entries = firstResult.entries;558    const allEntries = entries.length === 0559      ? (await fetchAutofillEntries(domain, true)).entries560      : entries;561562    let usernameEl: HTMLInputElement | null = null;563    const userField = fields.find((f) => f.type === "username" || f.type === "email");564    if (userField) usernameEl = userField.el;565    const pwField = fields.find((f) => f.type === "password");566    if (!pwField) return;567    const passwordEl = pwField.el;568569    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);570  } finally {571    pendingInteractions.delete(field);572  }573}574575async function onFocusIn(e: Event): Promise<void> {576  // Submit-button focus: catch the brief refocus some sites do when the577  // user clicks the login/submit button. Without this guard, that focus578  // event reaches handleFieldInteraction → getDeepActiveInput, and on579  // pages where the button is also a labelled <input> we briefly attempt580  // to open the popup over the very button the user just clicked.581  if (isSubmitButton(e.target)) return;582  await handleFieldInteraction();583}584585function reattachListeners(586  el: HTMLInputElement,587  detectedType?: "password" | "username" | "email",588  contextFields?: ReturnType<typeof detectLoginFields>589): void {590  if (processedInputs.has(el)) return;591  if (!resolveAutofillFieldType(el, detectedType)) return;592  // Only inject icon when a real login/signup form is present on the page593  const fields = contextFields ?? detectLoginFields();594  if (!isLoginForm(fields) && !isSignupForm(fields)) return;595596  const cleanup = injectFieldIcon(el, () => {597    currentDismiss?.();598    currentDismiss = null;599    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock600    dismissLock = false; // ...and the global lock601    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }602    clearFillStateForExplicitSummon(el);603    el.focus({ preventScroll: true });604    void handleFieldInteraction(el);605  });606  processedInputs.set(el, cleanup);607}608609const debouncedReattach = debounce(() => {610  const allFields = detectLoginFields();611  // Don't inject anything if there's no real login/signup form on this page612  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;613  const newFields = allFields.filter(614    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)615  );616  for (const f of newFields) {617    reattachListeners(f.el, f.type, allFields);618  }619  // 200ms debounce — below this, Peach and the host page's reactive layer620  // fight over the same layout properties every frame on React/Vue/Angular621  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.622}, 200);623624function setupMutationObserver(): void {625  const observer = new MutationObserver(debouncedReattach);626  observer.observe(document.body, {627    childList: true,628    subtree: true,629    attributes: true,630    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],631  });632}633634function initialScan(aggressionLevel = 0, isFinalPass = false) {635  const allFields = detectLoginFields();636  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);637638  if (aggressionLevel === 0 && !hasKnownForm) return;639640  const newFields = allFields.filter(641    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)642  );643644  for (const f of newFields) {645    reattachListeners(f.el, f.type, allFields);646  }647648  // Level 2, final pass: inject icon on any visible password field even if649  // the form-context gate in reattachListeners would normally skip it.650  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {651    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');652    for (const el of pwInputs) {653      if (isVisible(el) && !processedInputs.has(el)) {654        const cleanup = injectFieldIcon(el, () => {655          currentDismiss?.();656          currentDismiss = null;657          lastDismissedField = null;658          dismissLock = false;659          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }660          clearFillStateForExplicitSummon(el);661          el.focus({ preventScroll: true });662          void handleFieldInteraction(el);663        });664        processedInputs.set(el, cleanup);665      }666    }667  }668}669670document.addEventListener("focusin", onFocusIn);671672setupMutationObserver();673setupSaveDetection();674setupCardAutofill();675676// SPA navigation reset: the content script does not reload across in-app677// route changes (history.pushState, hash navigation, framework routers).678// When the URL changes we clear the page-level fill timestamp so the next679// page works normally; filledForms (a WeakSet) self-empties as old form680// elements leave the DOM. subtree:false because route swaps reliably681// mutate document.body's direct children — subtree:true would fire on682// every internal DOM update and cost us a re-check per mutation.683let lastObservedUrl = location.href;684new MutationObserver(() => {685  if (location.href !== lastObservedUrl) {686    lastObservedUrl = location.href;687    pageFilledAt = null;688  }689}).observe(document.body, { childList: true, subtree: false });690691// Async init: check recall map before running the initial scans so we can692// apply the right aggression level for domains the user has needed before.693(async () => {694  let aggressionLevel = 0;695  try {696    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });697    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;698    const domain = getPageDomain();699    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;700    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;701  } catch { /* SW may be starting up; proceed with normal scan */ }702703  setTimeout(() => initialScan(aggressionLevel, false), 0);704  setTimeout(() => initialScan(aggressionLevel, false), 500);705  setTimeout(() => initialScan(aggressionLevel, true), 1500);706})();707708// ── Card autofill (State 7) ─────────────────────────────────────────709// Card forms get a parallel injection path. The login icon-injection gate710// in reattachListeners deliberately skips non-text fields, so we wire711// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping712// card detection contained makes the boundary easy to follow.713const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();714let currentCardDismiss: (() => void) | null = null;715let currentCardAnchor: HTMLInputElement | null = null;716let lastDismissedCardField: HTMLInputElement | null = null;717718async function fetchSavedCards(): Promise<CardSelectorEntry[]> {719  const resp = await chrome.runtime.sendMessage({720    type: "AUTOFILL_QUERY",721    payload: { domain: getPageDomain(), kind: "card" },722  }).catch(() => null);723  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;724  return r?.ok ? (r.data ?? []) : [];725}726727async function openCardSelector(anchor: HTMLInputElement): Promise<void> {728  if (!canOpen()) return;729  if (currentCardDismiss && currentCardAnchor === anchor) return;730  if (anchor === lastDismissedCardField) return;731  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;732  if (wasAlreadyFilled(anchor)) return;733734  const cards = await fetchSavedCards();735  if (cards.length === 0) return; // no saved cards → nothing to offer736737  const cardForm = detectCardForm();738  if (!cardForm?.number) return;739740  currentCardDismiss?.();741  currentCardAnchor = anchor;742  currentCardDismiss = showCardSelector(743    anchor,744    cards,745    {746      domain: getPageDomain(),747      onFill: (entry) => {748        if (!cardForm) return;749        fillCardForm(cardForm, {750          cardNumber: entry.cardNumber ?? "",751          expMonth: entry.expMonth ?? "",752          expYear: entry.expYear ?? "",753          cvc: entry.cvc ?? "",754          cardholderName: entry.cardholderName ?? "",755        });756        // All four card field types share the same form — recording the757        // number field's form is sufficient to suppress reopens on any of758        // them via wasAlreadyFilled().759        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);760        currentCardDismiss = null;761        currentCardAnchor = null;762      },763      onDismiss: () => {764        lastDismissedCardField = anchor;765        startDismissLock();766        currentCardDismiss = null;767        currentCardAnchor = null;768      },769    }770  );771}772773function injectCardIcon(field: HTMLInputElement): void {774  if (processedCardInputs.has(field)) return;775  const cleanup = injectFieldIcon(field, () => {776    currentCardDismiss?.();777    currentCardDismiss = null;778    lastDismissedCardField = null;779    dismissLock = false;780    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }781    clearFillStateForExplicitSummon(field);782    field.focus({ preventScroll: true });783    void openCardSelector(field);784  });785  processedCardInputs.set(field, cleanup);786}787788function setupCardAutofill(): void {789  function scan() {790    const cardForm = detectCardForm();791    if (!cardForm?.number) return;792    if (!isVisible(cardForm.number)) return;793    injectCardIcon(cardForm.number);794  }795796  // Initial detection sweep — same retry cadence as login fields so797  // late-hydrating SPA checkout pages get caught.798  setTimeout(scan, 0);799  setTimeout(scan, 500);800  setTimeout(scan, 1500);801802  // Re-scan on DOM mutation (separate from the login MutationObserver803  // because card forms typically appear on a single navigation event,804  // not field-by-field — coarser observation is sufficient here).805  let pending = false;806  new MutationObserver(() => {807    if (pending) return;808    pending = true;809    setTimeout(() => { pending = false; scan(); }, 200);810  }).observe(document.body, { childList: true, subtree: true });811812  // Field-focus path: on focus of a cc-number input, ensure icon is813  // present and consider opening the selector when the user explicitly814  // clicks into the card number field.815  document.addEventListener("focusin", (e) => {816    const target = e.target;817    if (!(target instanceof HTMLInputElement)) return;818    const cardForm = detectCardForm();819    if (cardForm?.number === target) {820      injectCardIcon(target);821    }822  }, true);823}824825chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {826  // Ignore anything not originating from our own background/service worker.827  if (sender.id !== chrome.runtime.id) return;828  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {829    const policy = detectPasswordPolicy();830    sendResponse({ ok: true, data: policy });831    return true;832  }833  if (msg?.type === "PING") {834    sendResponse({ ok: true });835    return true;836  }837  if (msg?.type === "SUMMON_AUTOFILL") {838    const source = (msg as { type: string; source?: string }).source;839    const isShortcut = source === "shortcut";840    const isPasskeyUnlock = source === "passkey-unlock";841842    const activeInput = getDeepActiveInput();843    const fields = detectLoginFields();844    const hasForm = isLoginForm(fields) || isSignupForm(fields);845846    if (hasForm) {847      // Prefer the currently focused field if it's a login field, otherwise848      // fall back to the first password field, then username/email.849      const inForm = activeInput && fields.some(f => f.el === activeInput);850      const target = inForm851        ? activeInput852        : (fields.find(f => f.type === "password")?.el853            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);854      if (target) {855        // Explicit user summon (shortcut or extension button) — bypass all856        // suppression layers. The user is asking for the popup right now.857        clearFillStateForExplicitSummon(target);858        dismissLock = false;859        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }860        lastDismissedField = null;861        void handleFieldInteraction(target);862      }863    } else if (isPasskeyUnlock) {864      // Vault is locked during a passkey GET request. Show the inline unlock865      // prompt anchored to whatever element is focused on the page (typically866      // the passkey/sign-in button the user just tapped).867      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)868        ? document.activeElement as unknown as HTMLInputElement869        : null;870      if (anchor) {871        currentDismiss?.();872        currentAnchorField = null;873        currentDismiss = showAutofillSelector(anchor, [], () => {}, {874          domain: getPageDomain(),875          locked: true,876          onDismiss: () => {},877        });878      }879    } else if (isShortcut) {880      // Shortcut on a page with no login form — show clipboard-copy search mode.881      showSearchPalette();882    }883884    // Record this domain for the recall system when triggered via shortcut.885    if (isShortcut) {886      const domain = getPageDomain();887      if (domain) {888        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});889      }890    }891892    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });893    return true;894  }895  if (msg?.type === "PASSKEY_PRO_GATE") {896    // Background rejected a passkey request for a free user. Show State 11897    // so they know what happened and can choose to upgrade.898    showPasskeyProGate();899    sendResponse({ ok: true });900    return true;901  }902  if (msg?.type === "VAULT_UNLOCKED") {903    // Close any open selector (e.g. the locked-state prompt) and re-open904    // with fresh entry data. Use the saved anchor field so we reopen exactly905    // where the user was — covers both inline unlock and popup unlock.906    const savedField = currentAnchorField;907    if (currentDismiss) {908      currentDismiss();909      currentDismiss = null;910      currentAnchorField = null;911    }912    void handleFieldInteraction(savedField ?? undefined);913    sendResponse({ ok: true });914    return true;915  }916  return true;917});918919// ── Firefox passkey detection bridge (legacy observer path) ─────────────920//921// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it922// emitted `peach-passkey-firefox` postMessages so this content script could923// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.0924// replaced the observer with a full interception proxy (the page never925// reaches a real navigator.credentials.create on Firefox anymore), and the926// approval UI is opened by the background as part of the ceremony itself.927// When the proxy is active the offer would be redundant noise, so the928// listener gates on the flag. Once the proxy is removed (Firefox ships929// webAuthenticationProxy) this whole block goes too.930if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {931  let lastPasskeyOfferAt = 0;932  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;933934  window.addEventListener("message", (event: MessageEvent) => {935    if (event.source !== window) return;936    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;937    if (!data || data.source !== "peach-passkey-firefox") return;938    if (detectBrowser() !== "firefox") return;939    if (data.type !== "create") return;940941    // Cooldown: a single page interaction can fire multiple credentials.create942    // calls. Show the offer at most once per 30 seconds per page session.943    const now = Date.now();944    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;945    lastPasskeyOfferAt = now;946947    const domain = location.hostname.replace(/^www\./, "");948    chrome.runtime.sendMessage({949      type: "GET_PASSKEY_OFFER_DECLINED",950      payload: { domain },951    }).then((res: { ok: boolean; data?: boolean } | undefined) => {952      if (res?.data === true) return;953      const rpId = data.rpId ?? domain;954      showPasskeyRegistrationOffer({955        rpId,956        rpName: data.rpName,957        userName: data.userName,958        userDisplayName: data.userDisplayName,959      });960    }).catch(() => {});961  });962}963964// Surface State 11 (passkey-available) only when it adds value:965//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither966//     browser will auto-route, so the banner explains the re-register need.967//   - Firefox + same-browser entry: Firefox has no equivalent of968//     webAuthenticationProxy, so without a banner the user has no signal that969//     Peach is the source.970// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles971// the page's own credentials.get transparently and the popup approval view972// already surfaces it. A banner here would just be noise.973//974// Dedupe across navigation: each navigation re-injects this content script.975// chrome.storage.session keyed by domain is the natural per-tab/per-session976// memory; session storage clears when the user closes the browser.977{978  function checkPasskeyAvailability() {979    const domain = location.hostname.replace(/^www\./, "");980    if (!domain) return;981    const sessionKey = `peach_state11_shown:${domain}`;982    chrome.storage.session?.get(sessionKey).then((stored) => {983      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;984      chrome.runtime.sendMessage({985        type: "GET_PASSKEY_FOR_DOMAIN",986        payload: { domain },987      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {988        const data = res?.data;989        if (!data) return;990        const current = detectBrowser();991        const isCrossBrowser =992          data.browser && current !== "unknown" && data.browser !== current;993        const valuableOnFirefox = current === "firefox";994        if (!isCrossBrowser && !valuableOnFirefox) return;995        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});996        showPasskeyAvailable({997          rpId: data.rpId,998          userName: data.userName,999          fromBrowser: data.browser,1000          currentBrowser: current,1001        });1002      }).catch(() => {});1003    }).catch(() => {});1004  }10051006  // Defer until DOM is interactive — content_scripts run at document_idle but1007  // some pages still mutate visibly afterwards. A short delay also avoids1008  // surfacing the State 11 toast while the user is in the middle of typing.1009  if (document.readyState === "loading") {1010    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1011  } else {1012    setTimeout(checkPasskeyAvailability, 800);1013  }1014}