index.ts

49.6 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  findOTPDigitBoxGroup,5  findOtpSignalingGroup,6  getDeepActiveInput,7  getPageDomain,8  isAnyCredentialForm,9  isEmailFirstForm,10  isLoginForm,11  isSignupForm,12  isTOTPField,13  isVisible,14} from "./detect";15import {16  type CardSelectorEntry,17  injectFieldIcon,18  type SelectorEntry,19  showAutofillSelector,20  showCardSelector,21  showPasskeyAvailable,22  showPasskeyProGate,23  showPasskeyRegistrationOffer,24  showRememberSiteToast,25  showTotpCopyToast,26  showTOTPSelector,27} from "./inject";28import { detectBrowser } from "../shared/browser";29import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";30import { fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";31import { resolveAutofillInteractionTargets } from "./interaction";32import { setupSaveDetection } from "./save";33import { contentMLDetector } from "./content-ml-detector";34import { detectPasswordPolicy } from "./policy";35import type { FieldPrediction } from "../shared/ml";36import type { SavedIdentity, VaultEntry } from "../shared/types";3738// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value39// so we can tear down listeners if we ever need to re-process the same field.40// When the input is GC'd (SPA nav, React re-render), the map entry goes with41// it and we can re-inject without leaking the old handler.42const processedInputs = new WeakMap<HTMLInputElement, () => void>();43const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4445let currentDismiss: (() => void) | null = null;46// Field whose selector is currently open — used to avoid dismiss+reopen flicker47let currentAnchorField: HTMLInputElement | null = null;48// Prevents two concurrent handleFieldInteraction calls for the same field49const pendingInteractions = new WeakSet<HTMLInputElement>();50// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).51// Suppresses spurious reopens until focus moves to a different field. Layer 152// of the dismissal model — see Projects.md §4.12.53let lastDismissedField: HTMLInputElement | null = null;5455// ── Dismissal lock (Layer 2) ────────────────────────────────────────56// After any user-initiated dismiss, briefly block ALL reopens regardless of57// which field is focused. Catches the case where a page rapidly moves focus58// between fields after Escape — without this, focus moving to a SECOND field59// in <100ms would re-trigger the popup before the user finished dismissing.60const DISMISS_LOCK_MS = 800;61let dismissLock = false;62let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;63// Set when the inline popup was summoned specifically for a passkey-unlock64// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill65// (the passkey toast handles the next step instead).66let passkeySummonActive = false;67// Set while the passkey approval toast is visible. Prevents handleFieldInteraction68// from opening the autofill selector alongside it. Cleared by a window message69// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).70let passkeyToastActive = false;71function startDismissLock(): void {72  dismissLock = true;73  if (dismissLockTimer) clearTimeout(dismissLockTimer);74  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);75}76function canOpen(): boolean { return !dismissLock; }7778// ── Fill-success lock ───────────────────────────────────────────────79// After Peach autofills a form, the popup must NOT reappear on the filled80// fields, on the submit button (some sites refocus it briefly), or on any81// field in that form — even when host-page DOM mutations or the form's own82// validation flow refocus an input. Implemented as a WeakSet of forms plus83// a page-level timestamp:84//   - filledForms: every form Peach has filled this page session. Survives85//     until the form leaves the DOM (WeakSet GC).86//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders87//     window for fields that aren't inside a <form> element (some SPAs).88// SPA navigation resets pageFilledAt via the urlObserver below; filledForms89// self-empties as old form elements get GC'd.90const filledForms = new WeakSet<HTMLFormElement>();91let pageFilledAt: number | null = null;92const PAGE_FILL_GRACE_MS = 3000;9394function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {95  for (const f of fields) {96    if (!f) continue;97    const form = f.closest("form");98    if (form) filledForms.add(form);99  }100  pageFilledAt = Date.now();101}102103export /* @testable */ function wasAlreadyFilled(field: HTMLInputElement): boolean {104  const form = field.closest("form");105  if (form && filledForms.has(form)) return true;106  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;107  return false;108}109110function clearFillStateForExplicitSummon(field: HTMLInputElement): void {111  const form = field.closest("form");112  if (form) filledForms.delete(form);113  pageFilledAt = null;114}115116// Some sites briefly focus the submit button when the user clicks it (visual117// feedback, blur/focus dance for validation animations). Catch those at the118// focusin layer so we don't re-trigger handleFieldInteraction for an event119// target that was never going to be a credential field anyway.120function isSubmitButton(el: EventTarget | null): boolean {121  if (!(el instanceof HTMLElement)) return false;122  if (el instanceof HTMLButtonElement && el.type !== "button") return true;123  if (el instanceof HTMLInputElement && el.type === "submit") return true;124  if (el.getAttribute("type") === "submit") return true;125  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();126  if (!text || text.length > 24) return false;127  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);128}129130function debounce<T extends (...args: unknown[]) => void>(131  fn: T,132  ms: number133): (...args: Parameters<T>) => void {134  let timer: ReturnType<typeof setTimeout>;135  return (...args: Parameters<T>) => {136    clearTimeout(timer);137    timer = setTimeout(() => fn(...args), ms);138  };139}140141function showToast(message: string): void {142  const toast = document.createElement("div");143  toast.style.cssText = `144    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);145    background: #131109; color: #F0E8D8; padding: 8px 16px;146    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;147    font-size: 11px; z-index: 2147483647; opacity: 0;148    transition: opacity 200ms ease;149    border: 1px solid rgba(240,232,216,0.07);150    pointer-events: none;151  `;152  toast.textContent = message;153  document.body.appendChild(toast);154  requestAnimationFrame(() => { toast.style.opacity = "1"; });155  setTimeout(() => {156    toast.style.opacity = "0";157    setTimeout(() => toast.remove(), 200);158  }, 2000);159}160161function showSearchPalette(): void {162  const host = document.createElement("div");163  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";164  document.body.appendChild(host);165  const shadow = host.attachShadow({ mode: "closed" });166167  const style = document.createElement("style");168  style.textContent = `169    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;170      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;171      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}172    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);173      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}174    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}175    .s{padding:8px 12px}176    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);177      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;178      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}179    .l{max-height:220px;overflow-y:auto}180    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}181    .e:hover{background:rgba(240,232,216,.06)}182    .et{font-size:12px}183    .eu{font-size:10px;color:rgba(240,232,216,.45)}184    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}185  `;186187  let allEntries: SelectorEntry[] = [];188  let query = "";189190  const panel = document.createElement("div");191  panel.className = "p";192193  const hdr = document.createElement("div");194  hdr.className = "h";195  const hdrText = document.createElement("span");196  hdrText.textContent = "No form detected — search your vault";197  const closeBtn = document.createElement("button");198  closeBtn.className = "x";199  closeBtn.textContent = "✕";200  hdr.appendChild(hdrText);201  hdr.appendChild(closeBtn);202203  const searchWrap = document.createElement("div");204  searchWrap.className = "s";205  const searchInput = document.createElement("input");206  searchInput.placeholder = "search...";207  searchWrap.appendChild(searchInput);208209  const list = document.createElement("div");210  list.className = "l";211212  panel.appendChild(hdr);213  panel.appendChild(searchWrap);214  panel.appendChild(list);215  shadow.appendChild(style);216  shadow.appendChild(panel);217218  function close() { host.remove(); }219220  closeBtn.onclick = close;221222  function onKeyDown(e: KeyboardEvent) {223    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }224  }225  document.addEventListener("keydown", onKeyDown, true);226227  function render() {228    const q = query.toLowerCase();229    const filtered = q230      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))231      : allEntries;232    list.innerHTML = "";233    if (filtered.length === 0) {234      const em = document.createElement("div");235      em.className = "em";236      em.textContent = query ? "no matches" : "vault is empty";237      list.appendChild(em);238      return;239    }240    for (const entry of filtered.slice(0, 20)) {241      const row = document.createElement("div");242      row.className = "e";243      const title = document.createElement("div");244      title.className = "et";245      title.textContent = entry.title;246      row.appendChild(title);247      if (entry.username) {248        const user = document.createElement("div");249        user.className = "eu";250        user.textContent = entry.username;251        row.appendChild(user);252      }253      row.onclick = async () => {254        // MV-1: vault-wide search list is a cross-domain summon — the user255        // explicitly picked this entry to fill on this page.256        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, explicitSummon: true } });257        const r = resp as { ok: boolean; data?: { password?: string } };258        if (r.ok && r.data?.password) {259          let alreadyWritten = false;260          try {261            await navigator.clipboard.writeText(r.data.password);262            alreadyWritten = true;263          } catch (err) {264            console.warn("[Peach] clipboard write denied:", err);265          }266          const copyResp = await chrome.runtime.sendMessage({267            type: "COPY",268            payload: { text: r.data.password, label: "Password", alreadyWritten },269          }) as { ok?: boolean } | undefined;270          if (alreadyWritten || copyResp?.ok) {271            showToast("Password copied");272          } else {273            showToast("Could not copy password — clipboard blocked");274          }275        } else {276          showToast("Could not copy password");277        }278        close();279        document.removeEventListener("keydown", onKeyDown, true);280      };281      list.appendChild(row);282    }283  }284285  searchInput.oninput = () => { query = searchInput.value; render(); };286287  // MV-2: the summon palette is an explicit user gesture (keyboard shortcut /288  // toolbar icon), so it may load the vault-wide inventory.289  fetchAutofillEntries(getPageDomain(), true, true).then(result => {290    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }291    allEntries = result.entries;292    render();293    searchInput.focus();294  });295}296297function findTOTPField(root: Document | Element = document): HTMLInputElement | null {298  const inputs = root.querySelectorAll<HTMLInputElement>("input");299  for (const input of inputs) {300    if (isTOTPField(input)) return input;301  }302  return null;303}304305function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {306  const form = passwordEl.closest("form");307  return findTOTPField(form ?? document);308}309310311async function handleAutofill(312  _field: HTMLInputElement,313  usernameEl: HTMLInputElement | null,314  passwordEl: HTMLInputElement | null,315  entry: VaultEntry,316  emailEl?: HTMLInputElement | null317): Promise<HTMLInputElement | null> {318  if (!entry.username && !entry.password && !entry.email) return null;319  const pageDomain = getPageDomain();320  const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;321  // Fill the email field with entry.email if set; fall back to entry.username when322  // it looks like an email address (sites that store email-as-username and have a323  // separate email field on signup forms).324  const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");325  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);326  let filledTOTPField: HTMLInputElement | null = null;327328  if (entry.canary) {329    chrome.runtime.sendMessage({330      type: "FIRE_CANARY_PING",331      payload: {332        webhookUrl: entry.canary.webhookUrl,333        entryTitle: entry.title,334        trigger: "autofilled",335      },336    }).catch(() => {});337    chrome.runtime.sendMessage({338      type: "UPDATE_ENTRY",339      payload: {340        id: entry.id,341        patch: {342          canary: {343            ...entry.canary,344            lastPinged: Date.now(),345            pingCount: (entry.canary.pingCount ?? 0) + 1,346          },347        },348      },349    }).catch(() => {});350  }351352  // The background sends a freshly-generated 6-digit code (totpCode), never the353  // base32 seed (SEV-3-C). Fill the code straight in.354  const totpCode = (entry as { totpCode?: string }).totpCode;355  if (totpCode) {356    const code = totpCode;357    const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;358    if (fillTOTPCode(totpField, code)) {359      filledTOTPField = totpField;360    }361    let alreadyWritten = false;362    try {363      await navigator.clipboard.writeText(code);364      alreadyWritten = true;365    } catch (err) {366      console.warn("[Peach] clipboard write denied:", err);367    }368    const response = await chrome.runtime.sendMessage({369      type: "COPY",370      payload: { text: code, label: "TOTP", alreadyWritten },371    });372    const res = response as { ok?: boolean; clearSeconds?: number };373    if (filledTOTPField) {374      showToast("2FA code filled");375    } else if (alreadyWritten || res.ok) {376      // Don't render the live code into the toast — the page can read it from the377      // DOM and consume the one-time code (audit LOW). The code is already on the378      // clipboard; the toast confirms the copy and shows how long until the379      // clipboard self-clears (Addendum 2). 30 mirrors DEFAULT_CLEAR_SECONDS.380      showTotpCopyToast(res.clearSeconds ?? 30);381    } else {382      showToast("Could not copy TOTP — clipboard blocked");383    }384  }385386  return filledTOTPField;387}388389async function fetchAutofillEntries(390  domain: string,391  includeAll = false,392  userGesture = false393): Promise<{ entries: SelectorEntry[]; locked: boolean }> {394  const response = await chrome.runtime.sendMessage({395    type: "AUTOFILL_QUERY",396    payload: { domain, includeAll, userGesture },397  });398  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };399  if (!res.ok && res.error === "vault_locked") {400    return { entries: [], locked: true };401  }402  return { entries: res.data ?? [], locked: false };403}404405async function fetchTOTPEntries(406  domain: string407): Promise<{ entries: SelectorEntry[]; locked: boolean }> {408  const response = await chrome.runtime.sendMessage({409    type: "AUTOFILL_QUERY",410    payload: { domain, kind: "totp" },411  });412  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };413  if (!res.ok && res.error === "vault_locked") {414    return { entries: [], locked: true };415  }416  return { entries: res.data ?? [], locked: false };417}418419420function resolveAutofillFieldType(421  el: HTMLInputElement,422  predictedType?: FieldPrediction["type"] | null423): "password" | "username" | "email" | null {424  if (425    predictedType === "password" ||426    predictedType === "username" ||427    predictedType === "email"428  ) {429    return predictedType;430  }431432  const detected = detectLoginFields().find((field) => field.el === el)?.type;433  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {434    return detected;435  }436437  const htmlType = el.type.toLowerCase();438  if (htmlType === "password") return "password";439  if (htmlType === "email") return "email";440  return null;441}442443async function openAutofillSelector(444  anchorField: HTMLInputElement,445  usernameEl: HTMLInputElement | null,446  passwordEl: HTMLInputElement | null,447  domainEntries: SelectorEntry[],448  loadSearchableEntries: () => Promise<SelectorEntry[]>,449  domain: string,450  identityKind: "email" | "username",451  emailEl?: HTMLInputElement | null452): Promise<void> {453  // No saved entries for this site → signup/new-account mode.454  // Fetch vault identities for the identity-first surface and locate455  // the confirm-password field so "Copy & fill" can populate it too.456  const isSignup = domainEntries.length === 0;457  let savedIdentities: SavedIdentity[] | undefined;458  let confirmEl: HTMLInputElement | null = null;459  if (isSignup) {460    try {461      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as462        { ok: boolean; data?: SavedIdentity[] } | null;463      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;464    } catch { /* silent fallback */ }465466    const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;467    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));468    confirmEl = allPwInputs.find(469      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)470    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);471  }472473  currentDismiss?.();474  currentAnchorField = anchorField;475  currentDismiss = showAutofillSelector(476    anchorField,477    domainEntries,478    async (id: string) => {479      currentDismiss = null;480      currentAnchorField = null;481      const entryResponse = await chrome.runtime.sendMessage({482        type: "GET_ENTRY_FOR_FILL",483        payload: { id },484      });485      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;486      if (entry) {487        const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);488        recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);489        // Offer to remember the current site for this entry only if none of490        // its known domains (primary + additional) match — otherwise the491        // user already mapped it and the prompt would be noise.492        const pageDomain = location.hostname.replace(/^www\./, "");493        const entryDomains = new Set<string>();494        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {495          try {496            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));497          } catch { /* ignore unparseable */ }498        }499        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {500          showRememberSiteToast(pageDomain, entry.id);501        }502      }503    },504    {505      domain,506      loadSearchableEntries,507      isSignup,508      identityKind,509      hasEmailField: !!emailEl,510      savedIdentities,511      onFillFields: (username, password, email) => {512        const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;513        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email);514        if (password && confirmEl) setNativeValue(confirmEl, password);515        recordFillSuccess(anchorField, usernameEl, passwordEl);516      },517      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },518    }519  );520}521522async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {523  if (!canOpen()) return;524  if (currentDismiss && currentAnchorField === anchorField) return;525  if (anchorField !== lastDismissedField) lastDismissedField = null;526  if (anchorField === lastDismissedField) return;527  if (wasAlreadyFilled(anchorField)) return;528529  const domain = getPageDomain();530  const result = await fetchTOTPEntries(domain);531532  if (result.locked) {533    currentDismiss?.();534    currentAnchorField = anchorField;535    currentDismiss = showAutofillSelector(536      anchorField,537      [],538      () => {},539      {540        domain,541        locked: true,542        onUnlocked: () => void openTOTPSelector(anchorField),543        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },544      }545    );546    return;547  }548549  if (result.entries.length === 0) {550    lastDismissedField = anchorField;551    startDismissLock();552    showToast("No 2FA entries for this site — add a code in Peach first");553    return;554  }555556  currentDismiss?.();557  currentAnchorField = anchorField;558  currentDismiss = showTOTPSelector(559    anchorField,560    result.entries,561    async (id: string) => {562      try {563        const entryResponse = await chrome.runtime.sendMessage({564          type: "GET_ENTRY_FOR_FILL",565          payload: { id },566        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;567        const entry = entryResponse?.ok ? entryResponse.data : undefined;568        const code = (entry as { totpCode?: string } | undefined)?.totpCode;569        if (!code) return;570        if (otpDigitBoxes && otpDigitBoxes.length > 1) {571          fillOTPDigitBoxes(otpDigitBoxes, code);572        } else {573          setNativeValue(anchorField, code);574        }575        recordFillSuccess(anchorField);576        showToast("2FA code filled");577      } finally {578        currentDismiss = null;579        currentAnchorField = null;580      }581    },582    {583      domain,584      onDismiss: () => {585        lastDismissedField = anchorField;586        startDismissLock();587        currentDismiss = null;588        currentAnchorField = null;589      },590    }591  );592}593594595export /* @testable */ async function handleFieldInteraction(596  anchorField?: HTMLInputElement | null,597  explicitSummon = false598): Promise<void> {599  const field = anchorField ?? getDeepActiveInput();600  if (!field) return;601  if (!isVisible(field)) return;602603  // Passkey toast is visible — don't open the credential selector alongside it.604  if (passkeyToastActive) return;605606  // Layer 2: post-dismiss global lock. Catches rapid focus moves between607  // fields immediately after Escape/click-outside.608  if (!canOpen()) return;609610  // If a selector is already open for this exact field, don't flicker it.611  if (currentDismiss && currentAnchorField === field) return;612613  // If focus moved to a different field, the previous per-field dismiss lock614  // no longer applies.615  if (field !== lastDismissedField) lastDismissedField = null;616  // Layer 1: the user explicitly dismissed this field's selector — don't617  // reopen it until focus has genuinely moved away and come back.618  if (field === lastDismissedField) return;619620  // Fill-success lock: Peach already filled this form (or fired a fill621  // anywhere on the page within the grace window). Sites often refocus an622  // input on submit click, on validation, or on a transition to a success623  // state — none of those should re-open the popup.624  if (wasAlreadyFilled(field)) return;625626  // Prevent two concurrent calls for the same field (e.g. focusin + icon click627  // firing simultaneously — the second call would dismiss the first's selector).628  if (pendingInteractions.has(field)) return;629  pendingInteractions.add(field);630631  try {632    // Multi-digit OTP entry: a group of digit boxes opens one selector anchored633    // on the first box and fills every box at once — never one icon per box.634    // findOTPDigitBoxGroup covers maxlength=1 boxes; findOtpSignalingGroup635    // covers boxes that carry OTP signaling (autocomplete=one-time-code,636    // name/id/label matches otp/totp/2fa) but lack maxlength="1".637    const otpGroup = findOTPDigitBoxGroup(field) ?? findOtpSignalingGroup(field);638    if (otpGroup) {639      await openTOTPSelector(otpGroup[0]!, otpGroup);640      return;641    }642643    if (isTOTPField(field)) {644      const formFields = detectLoginFields();645      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {646        await openTOTPSelector(field);647        return;648      }649    }650651    const fieldType = field.type.toLowerCase();652653    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {654      return preds[0] ?? null;655    });656657    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {658      const timeout = setTimeout(() => resolve(null), 150);659      mlPromise.then((pred) => {660        clearTimeout(timeout);661        resolve(pred);662      });663    });664665    if (passkeyToastActive) return;666667    if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {668      return;669    }670671    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);672    if (autofillFieldType) {673      reattachListeners(field, autofillFieldType);674    }675676    const fields = detectLoginFields();677    const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);678    if (!targets.shouldOpen) {679      return;680    }681682    const domain = getPageDomain();683    const firstResult = await fetchAutofillEntries(domain);684    if (passkeyToastActive) return;685686    // Vault is locked — show an inline unlock prompt.687    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so688    // there is no double-trigger race between onUnlocked and the broadcast.689    if (firstResult.locked) {690      currentDismiss?.();691      currentAnchorField = field;692      currentDismiss = showAutofillSelector(693        field,694        [],695        () => {},696        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }697      );698      return;699    }700701    const entries = firstResult.entries;702    // MV-2: the vault-wide list is NOT fetched here. It is loaded lazily,703    // only when the user activates the search affordance inside the inline704    // popup (an explicit gesture), via the thunk below. Passive form focus705    // never ships the full account inventory into the page's content-script706    // world — and never hands out the entry ids that made MV-1 a full-vault707    // primitive.708    const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>709      (await fetchAutofillEntries(domain, true, true)).entries;710711    if (passkeyToastActive) return;712713    const pwField = fields.find((f) => f.type === "password");714    // For email-first flows there is no password field on this step — that is expected.715    if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;716    const usernameEl = targets.usernameEl;717    const passwordEl = targets.passwordEl;718    const emailEl = targets.emailEl;719720    await openAutofillSelector(721      field,722      usernameEl,723      passwordEl,724      entries,725      loadSearchableEntries,726      domain,727      autofillFieldType === "email" ? "email" : "username",728      emailEl,729    );730  } finally {731    pendingInteractions.delete(field);732  }733}734735async function onFocusIn(e: Event): Promise<void> {736  // Submit-button focus: catch the brief refocus some sites do when the737  // user clicks the login/submit button. Without this guard, that focus738  // event reaches handleFieldInteraction → getDeepActiveInput, and on739  // pages where the button is also a labelled <input> we briefly attempt740  // to open the popup over the very button the user just clicked.741  if (isSubmitButton(e.target)) return;742  await handleFieldInteraction();743}744745function reattachListeners(746  el: HTMLInputElement,747  detectedType?: "password" | "username" | "email",748  contextFields?: ReturnType<typeof detectLoginFields>749): void {750  if (processedInputs.has(el)) return;751  if (!resolveAutofillFieldType(el, detectedType)) return;752  // Only inject icon when a credential form is present on the page753  const fields = contextFields ?? detectLoginFields();754  if (!isAnyCredentialForm(fields)) return;755756  const cleanup = injectFieldIcon(el, () => {757    currentDismiss?.();758    currentDismiss = null;759    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock760    dismissLock = false; // ...and the global lock761    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }762    clearFillStateForExplicitSummon(el);763    el.focus({ preventScroll: true });764    void handleFieldInteraction(el, true);765  });766  processedInputs.set(el, cleanup);767}768769const debouncedReattach = debounce(() => {770  const allFields = detectLoginFields();771  if (!isAnyCredentialForm(allFields)) return;772  const newFields = allFields.filter(773    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)774  );775  for (const f of newFields) {776    reattachListeners(f.el, f.type, allFields);777  }778  // 200ms debounce — below this, Peach and the host page's reactive layer779  // fight over the same layout properties every frame on React/Vue/Angular780  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.781}, 200);782783function setupMutationObserver(): void {784  const observer = new MutationObserver(debouncedReattach);785  observer.observe(document.body, {786    childList: true,787    subtree: true,788    attributes: true,789    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],790  });791}792793export /* @testable */ function initialScan(aggressionLevel = 0, isFinalPass = false) {794  const allFields = detectLoginFields();795  const hasKnownForm = isAnyCredentialForm(allFields);796797  if (aggressionLevel === 0 && !hasKnownForm) return;798799  const newFields = allFields.filter(800    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)801  );802803  for (const f of newFields) {804    reattachListeners(f.el, f.type, allFields);805  }806807  // Level 2, final pass: inject icon on any visible password field even if808  // the form-context gate in reattachListeners would normally skip it.809  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {810    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');811    for (const el of pwInputs) {812      if (isVisible(el) && !processedInputs.has(el)) {813        const cleanup = injectFieldIcon(el, () => {814          currentDismiss?.();815          currentDismiss = null;816          lastDismissedField = null;817          dismissLock = false;818          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }819          clearFillStateForExplicitSummon(el);820          el.focus({ preventScroll: true });821          void handleFieldInteraction(el, true);822        });823        processedInputs.set(el, cleanup);824      }825    }826  }827}828829// @testable seam — gives unit tests read/write access to module-private state830// without exposing it in the production API surface.831export const _testSeam = {832  getLastDismissedField(): HTMLInputElement | null { return lastDismissedField; },833  setLastDismissedField(f: HTMLInputElement | null): void { lastDismissedField = f; },834  isDismissLocked(): boolean { return dismissLock; },835  DISMISS_LOCK_MS,836} as const;837838// ── TOTP-only fields ───────────────────────────────────────────────────────839// After a username/password submission, many sites swap the whole form for a840// lone "verification code" input. The credential selector intentionally gates841// on login/signup forms, so TOTP fields need a narrow path of their own.842const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();843844function hasLoginOrSignupForm(): boolean {845  const fields = detectLoginFields();846  return isAnyCredentialForm(fields);847}848849function injectTOTPFieldIcon(850  field: HTMLInputElement,851  otpDigitBoxes?: HTMLInputElement[]852): void {853  if (processedTOTPInputs.has(field)) return;854  const cleanup = injectFieldIcon(field, () => {855    currentDismiss?.();856    currentDismiss = null;857    currentAnchorField = null;858    lastDismissedField = null;859    dismissLock = false;860    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }861    clearFillStateForExplicitSummon(field);862    field.focus({ preventScroll: true });863    void openTOTPSelector(field, otpDigitBoxes);864  });865  processedTOTPInputs.set(field, cleanup);866}867868// A split-OTP group (4+ OTP-signaling boxes lacking maxlength="1") shows one869// icon on the first box, not one per box. Returns the anchor to inject on870// (group[0]) and its full group, or just the field itself when it's a lone871// TOTP input.872function resolveTOTPIconTarget(873  field: HTMLInputElement874): { anchor: HTMLInputElement; group?: HTMLInputElement[] } {875  const group = findOtpSignalingGroup(field);876  if (group) return { anchor: group[0]!, group };877  return { anchor: field };878}879880export /* @testable */ function scanTOTPFields(): void {881  if (hasLoginOrSignupForm()) return;882  const inputs = document.querySelectorAll<HTMLInputElement>("input");883  for (const input of inputs) {884    if (!isTOTPField(input)) continue;885    const { anchor, group } = resolveTOTPIconTarget(input);886    injectTOTPFieldIcon(anchor, group);887  }888}889890function setupTOTPAutofill(): void {891  setTimeout(scanTOTPFields, 0);892  setTimeout(scanTOTPFields, 500);893  setTimeout(scanTOTPFields, 1500);894895  const debouncedScan = debounce(scanTOTPFields, 200);896  new MutationObserver(debouncedScan).observe(document.body, {897    childList: true,898    subtree: true,899    attributes: true,900    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],901  });902903  document.addEventListener("focusin", (e) => {904    const target = e.target;905    if (!(target instanceof HTMLInputElement)) return;906    if (hasLoginOrSignupForm()) return;907    if (!isTOTPField(target)) return;908    const { anchor, group } = resolveTOTPIconTarget(target);909    injectTOTPFieldIcon(anchor, group);910  }, true);911}912913document.addEventListener("focusin", onFocusIn);914915setupMutationObserver();916setupTOTPAutofill();917setupSaveDetection();918setupCardAutofill();919920// SPA navigation reset: the content script does not reload across in-app921// route changes (history.pushState, hash navigation, framework routers).922// When the URL changes we clear the page-level fill timestamp so the next923// page works normally; filledForms (a WeakSet) self-empties as old form924// elements leave the DOM. subtree:false because route swaps reliably925// mutate document.body's direct children — subtree:true would fire on926// every internal DOM update and cost us a re-check per mutation.927let lastObservedUrl = globalThis.location.href;928new MutationObserver(() => {929  const currentUrl = globalThis.location?.href;930  if (!currentUrl || currentUrl === lastObservedUrl) return;931  lastObservedUrl = currentUrl;932  pageFilledAt = null;933}).observe(document.body, { childList: true, subtree: false });934935// Async init: check recall map before running the initial scans so we can936// apply the right aggression level for domains the user has needed before.937(async () => {938  let aggressionLevel = 0;939  try {940    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });941    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;942    const domain = getPageDomain();943    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;944    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;945  } catch { /* SW may be starting up; proceed with normal scan */ }946947  setTimeout(() => initialScan(aggressionLevel, false), 0);948  setTimeout(() => initialScan(aggressionLevel, false), 500);949  setTimeout(() => initialScan(aggressionLevel, true), 1500);950})();951952// ── Card autofill (State 7) ─────────────────────────────────────────953// Card forms get a parallel injection path. The login icon-injection gate954// in reattachListeners deliberately skips non-text fields, so we wire955// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping956// card detection contained makes the boundary easy to follow.957const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();958let currentCardDismiss: (() => void) | null = null;959let currentCardAnchor: HTMLInputElement | null = null;960let lastDismissedCardField: HTMLInputElement | null = null;961962async function fetchSavedCards(): Promise<CardSelectorEntry[]> {963  const resp = await chrome.runtime.sendMessage({964    type: "AUTOFILL_QUERY",965    payload: { domain: getPageDomain(), kind: "card" },966  }).catch(() => null);967  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;968  return r?.ok ? (r.data ?? []) : [];969}970971async function openCardSelector(anchor: HTMLInputElement): Promise<void> {972  if (!canOpen()) return;973  if (currentCardDismiss && currentCardAnchor === anchor) return;974  if (anchor === lastDismissedCardField) return;975  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;976  if (wasAlreadyFilled(anchor)) return;977978  const cards = await fetchSavedCards();979  if (cards.length === 0) return; // no saved cards → nothing to offer980981  const cardForm = detectCardForm();982  if (!cardForm?.number) return;983984  currentCardDismiss?.();985  currentCardAnchor = anchor;986  currentCardDismiss = showCardSelector(987    anchor,988    cards,989    {990      domain: getPageDomain(),991      onFill: (entry) => {992        if (!cardForm) return;993        fillCardForm(cardForm, {994          cardNumber: entry.cardNumber ?? "",995          expMonth: entry.expMonth ?? "",996          expYear: entry.expYear ?? "",997          cvc: entry.cvc ?? "",998          cardholderName: entry.cardholderName ?? "",999        });1000        // All four card field types share the same form — recording the1001        // number field's form is sufficient to suppress reopens on any of1002        // them via wasAlreadyFilled().1003        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);1004        currentCardDismiss = null;1005        currentCardAnchor = null;1006      },1007      onDismiss: () => {1008        lastDismissedCardField = anchor;1009        startDismissLock();1010        currentCardDismiss = null;1011        currentCardAnchor = null;1012      },1013    }1014  );1015}10161017function injectCardIcon(field: HTMLInputElement): void {1018  if (processedCardInputs.has(field)) return;1019  const cleanup = injectFieldIcon(field, () => {1020    currentCardDismiss?.();1021    currentCardDismiss = null;1022    lastDismissedCardField = null;1023    dismissLock = false;1024    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1025    clearFillStateForExplicitSummon(field);1026    field.focus({ preventScroll: true });1027    void openCardSelector(field);1028  });1029  processedCardInputs.set(field, cleanup);1030}10311032function setupCardAutofill(): void {1033  function scan() {1034    const cardForm = detectCardForm();1035    if (!cardForm?.number) return;1036    if (!isVisible(cardForm.number)) return;1037    injectCardIcon(cardForm.number);1038  }10391040  // Initial detection sweep — same retry cadence as login fields so1041  // late-hydrating SPA checkout pages get caught.1042  setTimeout(scan, 0);1043  setTimeout(scan, 500);1044  setTimeout(scan, 1500);10451046  // Re-scan on DOM mutation (separate from the login MutationObserver1047  // because card forms typically appear on a single navigation event,1048  // not field-by-field — coarser observation is sufficient here).1049  let pending = false;1050  new MutationObserver(() => {1051    if (pending) return;1052    pending = true;1053    setTimeout(() => { pending = false; scan(); }, 200);1054  }).observe(document.body, { childList: true, subtree: true });10551056  // Field-focus path: on focus of a cc-number input, ensure icon is1057  // present and consider opening the selector when the user explicitly1058  // clicks into the card number field.1059  document.addEventListener("focusin", (e) => {1060    const target = e.target;1061    if (!(target instanceof HTMLInputElement)) return;1062    const cardForm = detectCardForm();1063    if (cardForm?.number === target) {1064      injectCardIcon(target);1065    }1066  }, true);1067}10681069chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1070  // Ignore anything not originating from our own background/service worker.1071  if (sender.id !== chrome.runtime.id) return;1072  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1073    const policy = detectPasswordPolicy();1074    sendResponse({ ok: true, data: policy });1075    return true;1076  }1077  if (msg?.type === "PING") {1078    sendResponse({ ok: true });1079    return true;1080  }1081  if (msg?.type === "SUMMON_AUTOFILL") {1082    const source = (msg as { type: string; source?: string }).source;1083    const isShortcut = source === "shortcut";1084    const isPasskeyUnlock = source === "passkey-unlock";10851086    const activeInput = getDeepActiveInput();1087    const fields = detectLoginFields();1088    const hasForm = isAnyCredentialForm(fields);10891090    if (hasForm) {1091      // Prefer the currently focused field if it's a login field, otherwise1092      // fall back to the first password field, then username/email.1093      const inForm = activeInput && fields.some(f => f.el === activeInput);1094      const target = inForm1095        ? activeInput1096        : (fields.find(f => f.type === "password")?.el1097            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1098      if (target) {1099        // Explicit user summon (shortcut or extension button) — bypass all1100        // suppression layers. The user is asking for the popup right now.1101        clearFillStateForExplicitSummon(target);1102        dismissLock = false;1103        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1104        lastDismissedField = null;1105        void handleFieldInteraction(target);1106      }1107    } else if (isPasskeyUnlock) {1108      // Vault is locked during a passkey GET request. Show the inline unlock1109      // prompt anchored to whatever element is focused on the page (typically1110      // the passkey/sign-in button the user just tapped).1111      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1112        ? document.activeElement as unknown as HTMLInputElement1113        : null;1114      if (anchor) {1115        currentDismiss?.();1116        currentAnchorField = null;1117        passkeySummonActive = true;1118        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1119          domain: getPageDomain(),1120          locked: true,1121          onDismiss: () => { passkeySummonActive = false; },1122        });1123      }1124    } else if (isShortcut) {1125      // Shortcut on a page with no login form — show clipboard-copy search mode.1126      showSearchPalette();1127    }11281129    // Record this domain for the recall system when triggered via shortcut.1130    if (isShortcut) {1131      const domain = getPageDomain();1132      if (domain) {1133        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1134      }1135    }11361137    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1138    return true;1139  }1140  if (msg?.type === "PASSKEY_PRO_GATE") {1141    // Background rejected a passkey request for a free user. Show State 111142    // so they know what happened and can choose to upgrade.1143    showPasskeyProGate();1144    sendResponse({ ok: true });1145    return true;1146  }1147  if (msg?.type === "SHOW_PASSKEY_TOAST") {1148    // Block autofill selector for the lifetime of the toast and dismiss anything open.1149    passkeyToastActive = true;1150    if (currentDismiss) {1151      currentDismiss();1152      currentDismiss = null;1153      currentAnchorField = null;1154    }1155    return false; // inject.tsx owns the toast and calls sendResponse1156  }1157  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1158    passkeyToastActive = false;1159    return false; // inject.tsx handles the actual dismissal1160  }1161  if (msg?.type === "VAULT_UNLOCKED") {1162    if (passkeySummonActive) {1163      // This unlock was for a pending passkey GET request. Just dismiss the1164      // inline popup — the passkey approval toast takes over from here.1165      passkeySummonActive = false;1166      if (currentDismiss) {1167        currentDismiss();1168        currentDismiss = null;1169        currentAnchorField = null;1170      }1171      sendResponse({ ok: true });1172      return true;1173    }1174    // Normal autofill path: close the locked-state prompt and re-open with1175    // fresh entry data at the same anchor field.1176    const savedField = currentAnchorField;1177    if (currentDismiss) {1178      currentDismiss();1179      currentDismiss = null;1180      currentAnchorField = null;1181    }1182    void handleFieldInteraction(savedField ?? undefined);1183    sendResponse({ ok: true });1184    return true;1185  }1186  return true;1187});11881189// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)1190// so we know it's safe to allow autofill again.1191window.addEventListener("message", (e: MessageEvent) => {1192  // Reject postMessages from cross-frame senders — only the same window's1193  // injected toast may flip this flag.1194  if (e.source !== window) return;1195  const d = e.data as { source?: string; type?: string } | undefined;1196  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1197    passkeyToastActive = false;1198  }1199});12001201// ── Firefox passkey detection bridge (legacy observer path) ─────────────1202//1203// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it1204// emitted `peach-passkey-firefox` postMessages so this content script could1205// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.01206// replaced the observer with a full interception proxy (the page never1207// reaches a real navigator.credentials.create on Firefox anymore), and the1208// approval UI is opened by the background as part of the ceremony itself.1209// When the proxy is active the offer would be redundant noise, so the1210// listener gates on the flag. Once the proxy is removed (Firefox ships1211// webAuthenticationProxy) this whole block goes too.1212if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1213  let lastPasskeyOfferAt = 0;1214  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;12151216  window.addEventListener("message", (event: MessageEvent) => {1217    if (event.source !== window) return;1218    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1219    if (!data || data.source !== "peach-passkey-firefox") return;1220    if (detectBrowser() !== "firefox") return;1221    if (data.type !== "create") return;12221223    // Cooldown: a single page interaction can fire multiple credentials.create1224    // calls. Show the offer at most once per 30 seconds per page session.1225    const now = Date.now();1226    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1227    lastPasskeyOfferAt = now;12281229    const domain = location.hostname.replace(/^www\./, "");1230    chrome.runtime.sendMessage({1231      type: "GET_PASSKEY_OFFER_DECLINED",1232      payload: { domain },1233    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1234      if (res?.data === true) return;1235      const rpId = data.rpId ?? domain;1236      showPasskeyRegistrationOffer({1237        rpId,1238        rpName: data.rpName,1239        userName: data.userName,1240        userDisplayName: data.userDisplayName,1241      });1242    }).catch(() => {});1243  });1244}12451246// Surface State 11 (passkey-available) only when it adds value:1247//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1248//     browser will auto-route, so the banner explains the re-register need.1249//   - Firefox + same-browser entry: Firefox has no equivalent of1250//     webAuthenticationProxy, so without a banner the user has no signal that1251//     Peach is the source.1252// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1253// the page's own credentials.get transparently and the popup approval view1254// already surfaces it. A banner here would just be noise.1255//1256// Dedupe across navigation: each navigation re-injects this content script.1257// chrome.storage.session keyed by domain is the natural per-tab/per-session1258// memory; session storage clears when the user closes the browser.1259{1260  function checkPasskeyAvailability() {1261    const domain = location.hostname.replace(/^www\./, "");1262    if (!domain) return;1263    const sessionKey = `peach_state11_shown:${domain}`;1264    chrome.storage.session?.get(sessionKey).then((stored) => {1265      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1266      chrome.runtime.sendMessage({1267        type: "GET_PASSKEY_FOR_DOMAIN",1268        payload: { domain },1269      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1270        const data = res?.data;1271        if (!data) return;1272        const current = detectBrowser();1273        const isCrossBrowser =1274          data.browser && current !== "unknown" && data.browser !== current;1275        const valuableOnFirefox = current === "firefox";1276        if (!isCrossBrowser && !valuableOnFirefox) return;1277        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1278        showPasskeyAvailable({1279          rpId: data.rpId,1280          userName: data.userName,1281          fromBrowser: data.browser,1282          currentBrowser: current,1283        });1284      }).catch(() => {});1285    }).catch(() => {});1286  }12871288  // Defer until DOM is interactive — content_scripts run at document_idle but1289  // some pages still mutate visibly afterwards. A short delay also avoids1290  // surfacing the State 11 toast while the user is in the middle of typing.1291  if (document.readyState === "loading") {1292    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1293  } else {1294    setTimeout(checkPasskeyAvailability, 800);1295  }1296}